diff --git a/.github/ISSUE_TEMPLATE/Bug_report.md b/.github/ISSUE_TEMPLATE/Bug_report.md index fe94434490c..6add1cccb58 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.2.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..20b47dbe30c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,8 @@ language: node_js node_js: - - 'stable' - - '8' + - 'node' + - '10' - '6' sudo: false @@ -20,6 +20,7 @@ branches: - release-2.8 - release-2.9 - release-3.0 + - release-3.1 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..fbce8186fac 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 @@ -104,7 +104,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 +137,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 +153,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 +194,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..867f35d4ff7 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"); diff --git a/Jakefile.js b/Jakefile.js index 6ecb67ab9ce..68cfbf7eef6 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -147,14 +147,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 +520,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; 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/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..e4080a9bb37 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -135,9 +135,9 @@ - + - + @@ -741,6 +741,18 @@ + + + + + + + + + + + + @@ -861,9 +873,21 @@ - + - + + + + + + + + + + + + + @@ -1095,6 +1119,12 @@ + + + + + + @@ -1203,6 +1233,12 @@ + + + + + + @@ -1233,6 +1269,12 @@ + + + + + + @@ -1401,6 +1443,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2001,6 +2073,24 @@ + + + {1}'?]]> + + + + + + + + + + + + + + + @@ -2259,6 +2349,12 @@ + + + + + + @@ -2349,6 +2445,12 @@ + + + + + + @@ -2421,9 +2523,9 @@ - + - + @@ -2691,12 +2793,24 @@ + + + + + + + + + + + + @@ -2775,12 +2889,30 @@ + + + + + + + + + + + + + + + + + + @@ -2829,12 +2961,6 @@ - - - - - - @@ -3225,6 +3351,12 @@ + + + + + + @@ -3255,6 +3387,12 @@ + + + + + + @@ -3483,6 +3621,12 @@ + + + + + + @@ -3705,6 +3849,12 @@ + + + + + + @@ -3843,6 +3993,12 @@ + + + + + + @@ -3909,9 +4065,9 @@ - + - + @@ -3999,6 +4155,12 @@ + + + + + + @@ -4203,6 +4365,12 @@ + + + + + + @@ -4317,6 +4485,18 @@ + + + + + + + + + + + + @@ -4359,6 +4539,12 @@ + + + + + + @@ -4773,6 +4959,12 @@ + + + + + + @@ -5025,12 +5217,6 @@ - - - - - - @@ -5313,6 +5499,12 @@ + + + + + + @@ -5391,9 +5583,9 @@ - + - + @@ -5481,9 +5673,9 @@ - + - + @@ -5589,6 +5781,12 @@ + + + + + + @@ -5679,6 +5877,18 @@ + + + + + + + + + + + + @@ -6051,6 +6261,12 @@ + + + + + + @@ -6141,6 +6357,12 @@ + + + + + + @@ -6165,6 +6387,18 @@ + + + + + + + + + + + + @@ -6207,6 +6441,12 @@ + + + + + + @@ -6243,6 +6483,12 @@ + + + + + + @@ -6393,6 +6639,12 @@ + + + + + + @@ -6657,12 +6909,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + @@ -6831,6 +7107,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..f04ae41349c 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -59,10 +59,11 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook }; var ts; (function (ts) { - ts.versionMajorMinor = "3.1"; + ts.versionMajorMinor = "3.2"; ts.version = ts.versionMajorMinor + ".0-dev"; })(ts || (ts = {})); (function (ts) { + ts.emptyArray = []; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -428,7 +429,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 +461,7 @@ var ts; } return result; } - ts.flatMap = flatMap; + ts.flatMapToMutable = flatMapToMutable; function flatMapIterator(iter, mapfn) { var first = iter.next(); if (first.done) { @@ -661,18 +679,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 +715,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 +727,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 +838,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 +917,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 +942,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 +1029,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 +1143,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 +1298,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 +1697,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 +1715,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 +1787,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 +2087,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 +2177,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 +2372,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 +2658,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 +3213,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 +3252,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."), @@ -2980,14 +3313,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'."), @@ -3167,7 +3500,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 +3527,14 @@ 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."), 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 +3626,14 @@ 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}'."), 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 +3747,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 +3843,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 +3941,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 +3983,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 +3993,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 +4021,14 @@ 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."), 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 +4059,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."), @@ -3816,148 +4188,103 @@ 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"), }; })(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,]; @@ -4418,6 +4745,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -4428,8 +4756,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 +4775,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -4522,18 +4851,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 +4884,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 +4912,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 +4977,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 +5074,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 +5150,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 +5180,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 +5252,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 +5283,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 +5341,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 +5411,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 +5463,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 +5483,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 +5509,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 +5529,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 +5559,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 +5612,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 +5673,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 +5695,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 +5725,7 @@ var ts; } pos++; } - return firstNonWhitespace === -1 ? 11 : 10; + return firstNonWhitespace === -1 ? 12 : 11; } function scanJsxIdentifier() { if (tokenIsIdentifierOrKeyword(token)) { @@ -5378,7 +5749,7 @@ var ts; case 34: case 39: tokenValue = scanString(true); - return token = 9; + return token = 10; default: return scan(); } @@ -5401,43 +5772,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 +5883,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -5527,7 +5901,6 @@ var ts; ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics; })(ts || (ts = {})); (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -5573,7 +5946,6 @@ var ts; getText: function () { return str; }, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -5582,7 +5954,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 +5980,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 +6087,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 +6145,7 @@ var ts; } } function getSourceFileOfNode(node) { - while (node && node.kind !== 277) { + while (node && node.kind !== 279) { node = node.parent; } return node; @@ -5786,11 +6153,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 +6250,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 +6268,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 +6300,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 +6345,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 +6369,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 +6387,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 +6405,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 +6428,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 +6440,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 +6468,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 +6478,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 +6511,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 +6526,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 +6575,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 +6587,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 +6644,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 +6657,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 +6669,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 +6697,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 +6791,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 +6817,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 +6846,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 +6859,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 +6872,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 +6891,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 +6903,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 +6920,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 +6928,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 +6951,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 +6988,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 +7037,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 +7053,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 +7083,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 +7098,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 +7125,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 +7137,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 +7167,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 +7179,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 +7189,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 +7248,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 +7298,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 +7307,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 +7335,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 +7361,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 +7391,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 +7471,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 +7504,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 +7541,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 +7568,7 @@ var ts; } return 0; } - ts.getSpecialPropertyAccessKind = getSpecialPropertyAccessKind; + ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind; function getInitializerOfBinaryExpression(expr) { while (ts.isBinaryExpression(expr.right)) { expr = expr.right; @@ -7157,12 +7577,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 +7591,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 +7600,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 +7617,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 +7631,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 +7643,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 +7663,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 +7679,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 +7709,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 +7723,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 +7738,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 +7769,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 +7804,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 +7854,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 +7886,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 +7927,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 +8010,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 +8020,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 +8036,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 +8070,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 +8086,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 +8101,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 +8121,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 +8142,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 +8153,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 +8174,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 +8185,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 +8201,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 +8210,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 +8222,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 +8244,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 +8284,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 +8302,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 +8377,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 +8476,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 +8522,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 +8603,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 +8629,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 +8750,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 +8762,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 +8819,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 +8833,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 +8856,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 +8876,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 +8888,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 +8896,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 +8924,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 +8942,7 @@ var ts; } } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -8523,7 +9022,7 @@ var ts; } } else { - writer.write(text.substring(commentPos, commentEnd)); + writer.writeComment(text.substring(commentPos, commentEnd)); } } ts.writeCommentRange = writeCommentRange; @@ -8531,13 +9030,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 +9088,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 +9096,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 +9145,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 +9155,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 +9168,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 +9189,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 +9313,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 +9414,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 +9480,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 +9547,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 +9661,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) { @@ -9254,12 +9793,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 +9840,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 +9850,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 +9880,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 +9998,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 +10040,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 +10118,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 +10209,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 +10241,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 +10919,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 +10931,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 +10939,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 +10948,12 @@ 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 isStringTextContainingNode(node) { - return node.kind === 9 || isTemplateLiteralKind(node.kind); + return node.kind === 10 || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; function isGeneratedIdentifier(node) { @@ -10404,17 +10962,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 +10983,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 +10992,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 +11021,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 +11035,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 +11055,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 +11085,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,36 +11098,37 @@ 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 + return (kind >= 163 && kind <= 183) + || kind === 120 + || kind === 143 || kind === 135 - || kind === 122 - || kind === 137 + || kind === 146 + || kind === 136 + || kind === 123 || kind === 138 - || kind === 99 - || kind === 105 - || kind === 140 - || kind === 95 - || kind === 131 - || kind === 209 - || kind === 282 - || kind === 283 + || 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 === 288 + || kind === 289 + || kind === 290; } function isTypeNode(node) { return isTypeNodeKind(node.kind); @@ -10577,8 +11136,8 @@ var ts; ts.isTypeNode = isTypeNode; function isFunctionOrConstructorTypeNode(node) { switch (node.kind) { - case 163: - case 164: + case 165: + case 166: return true; } return false; @@ -10587,29 +11146,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 +11181,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 +11190,8 @@ var ts; ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern; function isArrayBindingOrAssignmentPattern(node) { switch (node.kind) { - case 183: case 185: + case 187: return true; } return false; @@ -10640,25 +11199,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 +11225,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 +11240,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 +11279,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 +11293,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 +11309,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 +11325,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 +11344,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 +11376,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 +11498,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 +11509,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 +11592,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 +11624,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 +11677,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 +11829,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 +11857,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 +11870,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 +12070,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 +12264,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 +12316,7 @@ var ts; return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]); }); } + ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards; function isImplicitGlob(lastPathComponent) { return !/[.*?]/.test(lastPathComponent); } @@ -11925,35 +12503,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 +12656,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 +12818,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 +12907,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 +12945,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 +12975,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,357 +12983,358 @@ 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: + case 291: return visitNodes(cbNode, cbNodes, node.tags); - case 297: - case 303: + case 299: + case 305: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -12661,17 +13343,17 @@ var ts; 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: + return visitNode(cbNode, node.typeExpression); + case 295: + return visitNode(cbNode, node.class); + case 303: + return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); + case 304: if (node.typeExpression && - node.typeExpression.kind === 281) { + node.typeExpression.kind === 283) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -12679,20 +13361,20 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 295: + case 297: return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 299: + case 301: return visitNode(cbNode, node.typeExpression); - case 296: + case 298: return visitNode(cbNode, node.typeExpression); - case 291: + case 293: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 290: + case 292: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -12700,7 +13382,7 @@ var ts; } } return; - case 306: + case 308: return visitNode(cbNode, node.expression); } } @@ -12710,7 +13392,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 +13458,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 +13493,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 +13512,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 +13633,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 +13790,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 +13840,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 +13896,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 +13914,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 +13923,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 +13933,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 +13951,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 +13969,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 +13992,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 +14014,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 +14050,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 +14100,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 +14127,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 +14165,7 @@ var ts; if (isInOrOfKeyword(token())) { return true; } - if (token() === 36) { + if (token() === 37) { return true; } return false; @@ -13579,17 +14275,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 +14294,8 @@ var ts; function isReusableSwitchClause(node) { if (node) { switch (node.kind) { - case 269: - case 270: + case 271: + case 272: return true; } } @@ -13608,65 +14304,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 +14416,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 +14465,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 +14476,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 +14485,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 +14521,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 +14546,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 +14570,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 +14591,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 +14599,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 +14666,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 +14721,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 +14749,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 +14786,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 +14820,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 +14828,7 @@ var ts; idToken = true; nextToken(); } - if (token() === 21) { + if (token() === 22) { return true; } if (isLiteralPropertyName()) { @@ -14139,21 +14836,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 +14861,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 +14893,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 +14988,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 +15070,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 +15115,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 +15159,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 +15176,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 +15199,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 +15227,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 +15248,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 +15259,7 @@ var ts; } function parseTypePredicatePrefix() { var id = parseIdentifier(); - if (token() === 127 && !scanner.hasPrecedingLineBreak()) { + if (token() === 128 && !scanner.hasPrecedingLineBreak()) { nextToken(); return id; } @@ -14566,47 +15268,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 +15320,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 +15341,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 +15354,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 +15363,7 @@ var ts; return expr; } function parseInitializer() { - return parseOptional(58) ? parseAssignmentExpressionOrHigher() : undefined; + return parseOptional(59) ? parseAssignmentExpressionOrHigher() : undefined; } function parseAssignmentExpressionOrHigher() { if (isYieldExpression()) { @@ -14671,7 +15374,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 +15383,7 @@ var ts; return parseConditionalExpressionRest(expr); } function isYieldExpression() { - if (token() === 116) { + if (token() === 117) { if (inYieldContext()) { return true; } @@ -14693,11 +15396,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 +15409,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 +15439,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 +15541,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 +15551,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 +15591,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 +15610,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 +15641,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 +15694,7 @@ var ts; return false; } function parseAwaitExpression() { - var node = createNode(199); + var node = createNode(201); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -14999,16 +15702,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 +15722,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 +15745,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 +15763,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 +15786,7 @@ var ts; } function parseLeftHandSideExpressionOrHigher() { var expression; - if (token() === 91) { + if (token() === 92) { if (lookAhead(nextTokenIsOpenParenOrLessThan)) { sourceFile.flags |= 524288; expression = parseTokenNode(); @@ -15092,8 +15795,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 +15806,7 @@ var ts; } } else { - expression = token() === 97 ? parseSuperExpression() : parseMemberExpressionOrHigher(); + expression = token() === 98 ? parseSuperExpression() : parseMemberExpressionOrHigher(); } return parseCallExpressionRest(expression); } @@ -15113,20 +15816,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 +15838,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 +15865,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 +15880,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 +15909,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 +15925,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 +15947,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 +15958,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 +15995,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 +16068,7 @@ var ts; } indexedAccess.argumentExpression = argument; } - parseExpected(22); + parseExpected(23); expression = finishNode(indexedAccess); continue; } @@ -15377,13 +16080,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 +16094,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 +16103,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 +16121,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 +16140,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 +16171,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 +16293,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 +16304,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 +16316,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 +16335,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 +16375,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 +16424,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 +16458,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 +16466,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 +16475,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 +16546,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 +16572,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 +16638,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: - return isStartOfDeclaration(); - case 120: - case 124: - case 109: - case 129: - case 130: - case 139: - case 144: + 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 121: + case 125: + case 110: + case 130: + 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 +16686,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 +16761,7 @@ var ts; return parseExpressionOrLabeledStatement(); } function isDeclareModifier(modifier) { - return modifier.kind === 124; + return modifier.kind === 125; } function parseDeclaration() { var node = createNodeWithJSDoc(0); @@ -16075,40 +16780,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 +16824,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 +16860,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 +16889,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 +16902,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 +16928,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 +16976,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 +16987,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 +17003,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 +17036,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 +17052,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 +17069,7 @@ var ts; } function parseModifiersForArrowFunction() { var modifiers; - if (token() === 120) { + if (token() === 121) { var modifierStart = scanner.getStartPos(); var modifierKind = token(); nextToken(); @@ -16374,54 +17079,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 +17139,7 @@ var ts; : undefined; } function isImplementsClause() { - return token() === 108 && lookAhead(nextTokenIsIdentifierOrKeyword); + return token() === 109 && lookAhead(nextTokenIsIdentifierOrKeyword); } function parseHeritageClauses() { if (isHeritageClause()) { @@ -16444,33 +17149,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 +17183,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 +17212,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 +17223,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 +17242,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 +17252,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 +17330,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 +17348,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 +17371,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 +17382,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 +17404,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 +17422,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 +17438,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 +17454,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 +17529,7 @@ var ts; } loop: while (true) { switch (token()) { - case 57: + case 58: if (state === 0 || state === 1) { removeTrailingWhitespace(comments); addTag(parseTag(indent)); @@ -16841,7 +17546,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 +17557,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 +17591,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 +17624,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 +17706,7 @@ var ts; } indent = 0; break; - case 57: + case 58: scanner.setTextPos(scanner.getTextPos() - 1); case 1: break loop; @@ -17022,9 +17722,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 +17732,7 @@ var ts; } pushComment(scanner.getTokenText()); break; - case 39: + case 40: if (state === 0) { state = 1; indent += 1; @@ -17049,9 +17749,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 +17769,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 +17806,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 +17822,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 +17845,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 +17924,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 +17941,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 +17958,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 +17972,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 +18022,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 +18046,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 +18060,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 +18085,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 +18121,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 +18135,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 +18218,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 +18643,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 +18692,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 +18711,48 @@ 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 + }, + ]; + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -18069,26 +18794,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 +18813,8 @@ var ts; es2018: 5, esnext: 6, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: ts.Diagnostics.VERSION, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18121,6 +18833,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 +18846,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 +18854,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 +18872,7 @@ var ts; "react-native": 3, "react": 2 }), + affectsSourceFile: true, paramType: ts.Diagnostics.KIND, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, @@ -18265,6 +18981,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18273,6 +18990,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18281,14 +18999,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 +19025,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18305,6 +19034,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -18337,6 +19067,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -18348,6 +19079,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 +19087,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 +19095,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 +19109,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 +19121,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 +19132,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 @@ -18477,30 +19214,12 @@ var ts; 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 +19277,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 +19297,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 +19343,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 +19351,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 +19379,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 +19406,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 +19486,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 +19532,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 +19552,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 +19592,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -18877,8 +19635,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 +19658,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 +19795,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 +19915,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 +19958,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 +19990,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 +20006,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 +20045,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 +20259,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 +20277,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 +20328,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 +20347,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -19505,12 +20363,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 +20462,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 +20489,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 +20519,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 +20665,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 +20674,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 +20685,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 +20871,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 +20898,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 +21018,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 +21043,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 +21055,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 +21068,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 +21090,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 +21127,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 +21144,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 +21247,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 +21281,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 +21292,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 +21307,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 +21362,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 +21379,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 +21390,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 +21461,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 +21477,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 +21508,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 +21541,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 +21581,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 +21604,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 +21642,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 +21654,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 +21724,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 +21733,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 +21867,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 +21934,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 +21952,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 +21985,9 @@ var ts; }); return state_1; } - case 242: + case 244: return getModuleInstanceState(node); - case 71: + case 72: if (node.isInJSDocNamespace) { return 0; } @@ -21046,16 +22093,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 +22115,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 +22126,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 +22184,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 +22203,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 +22230,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 +22239,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 +22260,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 +22288,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 +22300,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 +22349,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 +22379,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 +22464,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 +22498,7 @@ var ts; } } } - if (expr.expression.kind === 187 && + if (expr.expression.kind === 189 && isNarrowableReference(expr.expression.expression)) { return true; } @@ -21458,32 +22512,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 +22571,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 +22610,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 +22678,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 +22710,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 +22738,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 +22758,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 +22821,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 +22843,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 +22886,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 +22903,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 +22914,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 +22931,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 +22942,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 +22952,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 +22979,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 +22990,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 187) { + if (node.expression.kind === 189) { bindAssignmentTargetFlow(node.expression); } } @@ -21981,10 +23034,10 @@ var ts; } 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 +23045,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 +23054,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 +23113,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 +23161,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 +23191,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 +23200,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 +23217,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 +23233,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 +23269,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 +23285,6 @@ var ts; declareSymbol(blockScopeContainer.locals, undefined, node, symbolFlags, symbolExcludes); } } - function bindBlockScopedVariableDeclaration(node) { - bindBlockScopedDeclaration(node, 2, 67216319); - } function delayedBindJSDocTypedefTag() { if (!delayedTypeAliases) { return; @@ -22252,9 +23302,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 +23318,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 +23347,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 +23356,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 +23389,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 +23409,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 +23452,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 +23476,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 +23510,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 +23563,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 +23731,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 +23779,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 +23823,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 +23843,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 +23875,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 +23889,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 +23914,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 (ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } var init = !node ? undefined : ts.isVariableDeclaration(node) ? node.initializer : ts.isBinaryExpression(node) ? node.right : @@ -22873,7 +23968,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 +24008,7 @@ var ts; } } function bindClassLikeDeclaration(node) { - if (node.kind === 238) { + if (node.kind === 240) { bindBlockScopedDeclaration(node, 32, 68008383); } else { @@ -22945,19 +24040,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 +24065,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 +24081,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 +24122,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 +24153,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 +24182,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 +24218,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 +24290,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 +24341,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 +24379,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 +24416,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23327,7 +24427,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 +24435,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23343,11 +24443,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 +24459,7 @@ var ts; || !node.body) { transformFlags |= 3; } - if (subtreeFlags & 1048576) { + if (subtreeFlags & 262144) { transformFlags |= 8; } if (ts.hasModifier(node, 256)) { @@ -23369,7 +24469,7 @@ var ts; transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003668801; + return transformFlags & ~653616449; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23380,19 +24480,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 +24502,7 @@ var ts; transformFlags = 3; } else { - transformFlags = subtreeFlags | 33554432; + transformFlags = subtreeFlags | 8388608; if (modifierFlags & 2270 || node.typeParameters || node.type) { @@ -23411,10 +24511,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 +24522,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~1003935041; + return transformFlags & ~653620545; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23434,17 +24534,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 +24556,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 +24605,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 +24627,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -23535,7 +24635,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~939525441; + return transformFlags & ~637535553; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3; @@ -23544,71 +24644,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 +24718,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 +24758,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 +24967,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 +24983,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 +25076,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 +25118,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 +25139,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 +25149,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"); @@ -24204,10 +25324,6 @@ var ts; 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); @@ -24230,14 +25346,15 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, 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 +25362,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 +25412,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -24318,24 +25436,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 +25481,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 +25498,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -24379,6 +25515,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -24390,7 +25527,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 +25537,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 +25560,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 +25689,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 +25749,7 @@ var ts; (source.flags | target.flags) & 67108864) { ts.Debug.assert(source !== target); if (!(target.flags & 33554432)) { - target = cloneSymbol(target); + target = cloneSymbol(resolveSymbol(target)); } if (source.flags & 512 && target.flags & 512 && target.constEnumOnlyModule && !source.constEnumOnlyModule) { target.constEnumOnlyModule = false; @@ -24614,6 +25757,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 +25779,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 +25841,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 +25896,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 +25918,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 +25942,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 +25958,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 +25969,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 +25989,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 +26026,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 +26059,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 +26076,7 @@ var ts; var moduleExport = moduleExports.get(name); if (moduleExport && moduleExport.flags === 2097152 && - ts.getDeclarationOfKind(moduleExport, 255)) { + ts.getDeclarationOfKind(moduleExport, 257)) { break; } } @@ -24936,26 +26089,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 +26119,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 +26127,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 +26138,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 +26172,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; } @@ -25043,8 +26196,8 @@ var ts; } 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 +26206,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 +26247,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 +26263,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 +26280,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 +26328,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 +26340,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 +26361,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 +26396,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 +26413,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 +26427,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 +26443,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 +26471,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 +26505,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 +26558,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 +26592,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 +26602,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 +26656,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 +26669,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 +26681,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 +26719,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 +26748,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 +26764,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,6 +26784,16 @@ var ts; return symbol && symbol.valueDeclaration; } } + 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) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -25645,7 +26823,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.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(false, errorNode, resolvedModule, moduleReference); } return getMergedSymbol(sourceFile.symbol); @@ -25661,7 +26839,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 +26869,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 +26877,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 +26889,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 +26926,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 +26993,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") : @@ -25937,13 +27118,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 +27147,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 +27197,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 +27211,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 +27250,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 +27280,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 +27294,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 +27308,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 +27336,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 +27385,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 +27428,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); @@ -26271,6 +27460,9 @@ var ts; if (flags & 8) { nodeFlags |= 16384; } + if (flags & 16) { + nodeFlags |= 67108864; + } var builder = flags & 4 ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -26287,15 +27479,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 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; } } @@ -26353,9 +27545,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 & 67108864 ? { + 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 +27576,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 +27675,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 +27694,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 +27721,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 +27747,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 +27769,54 @@ 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); + if (!(context.flags & 1)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), undefined); + } + return ts.createKeywordTypeNode(120); } } 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) { + context.approximateLength += 3; + if (!(context.flags & 1)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), undefined); + } + return ts.createKeywordTypeNode(120); + } + 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 +27829,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 +27849,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 +27881,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 +27918,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 +27931,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,11 +27979,11 @@ 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 ? @@ -26801,25 +28025,21 @@ var ts; 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) { @@ -26831,9 +28051,9 @@ var ts; else { var savedFlags = context.flags; context.flags |= !!(ts.getCheckFlags(propertySymbol) & 2048) ? 33554432 : 0; - var propertyTypeNode = propertyType ? typeToTypeNodeHelper(propertyType, context) : ts.createKeywordTypeNode(119); + var 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 +28102,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 +28120,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 +28139,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 +28161,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 +28173,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 +28184,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 & 67108864)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, true)); ts.Debug.assert(chain && chain.length > 0); } @@ -27061,7 +28293,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 +28321,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,7 +28332,7 @@ 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); @@ -27194,6 +28429,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; } @@ -27247,12 +28485,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 +28500,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 +28517,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 +28526,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 +28543,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 +28583,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 +28651,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 +28675,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 +28712,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 +28722,8 @@ var ts; return !!target.resolvedReturnType; case 4: return !!target.immediateBaseConstraint; + case 6: + return !!getSymbolLinks(target).resolvedJSDocType; } return ts.Debug.assertNever(propertyName); } @@ -27490,12 +28735,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 +28763,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 +28811,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 +28832,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 +28877,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 +28905,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 +28915,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 +28929,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 +28958,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 +28974,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 +28989,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 +29036,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 +29049,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 +29101,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 +29121,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 +29130,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 +29141,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 +29178,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 +29194,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 +29206,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 +29253,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 +29284,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 +29306,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 +29322,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 +29349,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 +29375,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 +29389,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 +29397,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 +29428,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 +29439,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 +29463,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 +29472,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 +29533,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 +29553,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 +29620,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 +29655,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 +29663,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 +29703,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 +29719,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); @@ -28497,14 +29756,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); @@ -28533,7 +29792,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 +29801,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 +29828,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 +29843,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 +29864,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 +29878,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 +29900,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 +29915,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 +29927,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 +29962,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 +30001,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 +30033,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 +30042,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 +30085,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 +30108,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 +30126,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 +30219,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 +30327,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 +30347,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 +30374,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 +30415,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 +30449,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 +30467,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 +30501,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 +30513,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 +30530,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 +30540,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 +30555,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 +30569,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 +30585,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 +30608,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 +30621,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 +30632,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 +30660,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 +30677,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 +30715,7 @@ var ts; } } } - if (type.flags & 262144) { + if (type.flags & 1048576) { break; } } @@ -29465,12 +30725,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 +30739,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 +30757,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 +30810,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 +30830,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 +30840,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 +30853,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 +30861,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 +30880,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 +30952,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 +31006,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 +31080,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 +31114,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 +31162,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 +31198,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 +31219,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 +31254,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 +31263,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 +31273,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 +31285,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 +31321,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 +31344,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 +31405,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 +31422,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 +31432,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 +31446,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 +31472,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 +31482,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 +31502,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 +31541,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 +31554,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 +31568,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 +31595,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 +31603,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 +31622,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 +31645,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 +31711,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 +31740,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 +31762,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 +31787,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 +31853,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 +31868,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 +31881,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 +31939,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 +31976,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 +31987,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 +31998,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 +32028,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 +32057,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 +32110,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 +32132,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 +32167,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 +32177,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 +32206,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 +32224,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 +32239,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 +32252,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 +32265,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 +32294,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 +32314,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 +32368,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 +32378,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 +32398,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 +32413,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 +32431,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 +32444,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 +32458,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 +32489,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 +32519,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 +32548,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 +32558,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 +32581,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 +32590,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 +32610,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 +32629,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 +32641,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; + 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 +32704,7 @@ var ts; } return indexInfo.type; } - if (indexType.flags & 32768) { + if (indexType.flags & 131072) { return neverType; } if (isJSLiteralType(objectType)) { @@ -31380,15 +32730,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 +32748,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 +32785,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 +32811,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 +32828,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 +32857,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 +32877,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 +32885,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 +32910,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 +32942,7 @@ var ts; return true; } while (node) { - if (node.kind === 173) { + if (node.kind === 175) { if (isTypeParameterPossiblyReferenced(tp, node.extendsType)) { return true; } @@ -31610,7 +32965,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 +33008,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 +33037,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 +33051,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 +33083,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 +33093,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 +33139,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 +33154,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 +33163,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 +33202,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 +33214,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 +33242,7 @@ var ts; return links.resolvedType; } function createUniqueESSymbolType(symbol) { - var type = createType(2048); + var type = createType(8192); type.symbol = symbol; return type; } @@ -31878,9 +33257,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 +33275,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 +33418,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 +33432,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 +33473,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 +33500,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 +33510,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 +33539,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 +33614,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 +33652,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 +33763,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 +33773,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 +33791,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 +33805,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 +33815,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 +33832,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 +33951,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 +33997,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 +34029,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 +34053,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 +34084,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 +34106,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 +34130,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 +34151,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 +34224,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 +34269,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 +34345,7 @@ var ts; } function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; + var relatedInfo; var maybeKeys; var sourceStack; var targetStack; @@ -32862,7 +34353,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 +34378,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 +34431,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 +34447,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 +34479,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 +34495,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 +34515,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 +34564,9 @@ var ts; return result; } } + if (!headMessage && maybeSuppress) { + return result; + } reportRelationError(headMessage, source, target); } return result; @@ -33070,49 +34574,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 +34599,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 +34632,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 +34657,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 +34670,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 +34698,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 +34733,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 +34758,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 +34799,7 @@ var ts; } return result; } - function recursiveTypeRelatedTo(source, target, reportErrors) { + function recursiveTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { if (overflow) { return 0; } @@ -33362,7 +34839,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 +34859,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 +34915,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 +34925,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 +34945,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 +34971,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 +35023,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 +35056,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 +35089,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 +35105,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 +35169,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 +35232,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 +35263,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 +35343,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 +35432,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 +35596,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; @@ -34114,7 +35689,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 +35709,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 +35730,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) { @@ -34171,7 +35746,7 @@ var ts; } 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 +35756,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 +35811,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 +35849,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 +35876,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 +35910,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 +35920,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 +36006,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 +36026,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 +36062,78 @@ 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: + 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 +36179,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 +36192,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 +36212,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 +36248,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 +36307,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 +36330,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 +36346,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 +36358,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 +36372,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 +36415,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 +36429,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 +36463,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 +36471,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 +36501,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 +36520,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 +36530,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 +36569,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 +36581,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 +36622,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 +36665,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 +36681,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 +36703,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 +36711,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 +36722,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 +36741,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 +36769,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 +36832,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 +36852,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 +36887,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 +36896,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 +36968,7 @@ var ts; } } } - if (callExpression.expression.kind === 187 && + if (callExpression.expression.kind === 189 && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -35250,13 +36981,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 +37010,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 +37024,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 +37091,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 +37103,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 +37111,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 +37136,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 +37158,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 +37173,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 +37213,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 +37235,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 +37266,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 +37316,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 +37350,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 +37367,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 +37386,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 +37405,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 +37427,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 +37497,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 +37528,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 +37561,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 +37583,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 +37593,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 +37691,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 +37713,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 +37734,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 +37742,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 +37773,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 +37790,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 +37822,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 +37867,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 +37952,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 +37999,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 +38014,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 +38037,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 +38053,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 +38070,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 +38090,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 +38113,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 +38125,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 +38141,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,7 +38172,7 @@ 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; } @@ -36353,28 +38196,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 +38226,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 +38235,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 +38257,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 +38310,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 +38354,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 +38388,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 +38433,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 +38498,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 +38513,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 +38528,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 +38538,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 +38549,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 +38568,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 +38580,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 +38605,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 +38616,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 +38632,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -36730,7 +38644,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 +38653,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 +38679,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 +38705,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 +38717,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 +38738,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 +38800,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 +38815,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 +38852,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 +38913,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1) || + getIndexTypeOfContextualType(t, 0); } return undefined; }, true); @@ -36953,9 +38922,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 +38934,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 +38947,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 +38980,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 +39026,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 +39082,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 +39103,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 +39145,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 +39161,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 +39194,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 +39207,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 +39216,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 +39251,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 +39263,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 +39273,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 +39329,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 +39353,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); } @@ -37438,13 +39380,13 @@ var ts; 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 +39396,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 +39415,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 +39424,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 +39448,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 +39465,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 +39505,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 +39514,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 +39525,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 +39579,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 +39606,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 +39616,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 +39625,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 +39665,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 +39682,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 +39714,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 +39738,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 +39755,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 +39763,54 @@ var ts; function getJsxElementChildrenPropertyName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType) { - if (!propsType) { - 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); - } - 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; - } - } - } - } - 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; - } - } - 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); + function getUninstantiatedJsxSignaturesOfType(elementType) { 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)); - } + } + if (signatures.length === 0 && elementType.flags & 1048576) { + signatures = getUnionSignatures(ts.map(elementType.types, getUninstantiatedJsxSignaturesOfType)); + } + 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; + } + return anyType; + } + 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); + } + } + 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); + } + } + 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 +39829,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 +39858,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { + function checkJsxOpeningLikeElementOrOpeningFragment(node) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -38098,7 +39867,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 +39875,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 +39889,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 +39897,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 +39922,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 +39949,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 +39979,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 +40003,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 +40055,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,9 +40066,9 @@ 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)); @@ -38327,23 +40077,29 @@ var ts; } 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 +40117,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 +40130,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 +40165,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 +40205,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); @@ -38499,16 +40255,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 +40290,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 +40310,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 +40334,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 +40346,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 +40363,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 +40387,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 +40418,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 +40448,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 +40519,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 +40529,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 +40537,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 +40552,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 +40573,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 +40621,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 +40675,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 +40793,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 +40816,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 +40848,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 +40884,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 +40925,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 +41004,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 +41015,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 +41042,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 +41081,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 +41108,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 +41177,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 +41196,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 +41250,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 +41275,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 +41287,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 +41309,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 +41329,70 @@ 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); + } + if (exprTypes.flags & 128) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes, node); + if (!intrinsicType) { + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, exprTypes.value, "JSX." + JsxNames.IntrinsicElements); + return resolveUntypedCall(node); + } + else { + var fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), undefined), intrinsicType, node.tagName, node.attributes); + return fakeSignature; + } + } + var signatures = getUninstantiatedJsxSignaturesOfType(apparentType); + if (exprTypes.flags & 4 || 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 +41408,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 +41450,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 +41483,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 +41507,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 +41541,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 +41554,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 +41596,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 +41604,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 +41641,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 +41655,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 +41719,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 +41732,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 +41756,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 +41763,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 +41823,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 +41837,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 +41853,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 +41882,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 +41967,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 +42015,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 +42032,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 +42045,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 +42065,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 +42095,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 +42104,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 +42143,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -40396,7 +42153,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 +42163,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 +42181,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 +42238,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 +42252,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 +42261,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 +42297,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 +42350,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 +42383,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 +42413,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 +42427,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 +42440,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 +42458,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 +42513,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 +42536,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 +42553,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 +42567,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 +42592,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 +42663,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 +42751,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 +42782,29 @@ 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, right); + if (isAssignmentDeclaration(declKind)) { 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 +42812,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _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 +42830,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 +42844,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 +42865,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2: return true; case 1: @@ -41043,7 +42875,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 +42892,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 +42960,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 +43000,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 +43022,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 +43080,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 +43125,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 +43249,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 +43265,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 +43319,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 +43339,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 +43351,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 +43381,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 +43408,7 @@ var ts; checkAsyncFunctionReturnType(node, returnTypeNode); } } - if (node.kind !== 160 && node.kind !== 287) { + if (node.kind !== 162 && node.kind !== 289) { registerForUnusedIdentifiersCheck(node); } } @@ -41580,7 +43418,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 +43433,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 +43494,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 +43519,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 +43534,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 +43542,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 134: + case 135: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -41726,7 +43564,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 +43585,7 @@ var ts; return; } function isInstancePropertyWithInitializer(n) { - return n.kind === 152 && + return n.kind === 154 && !ts.hasModifier(n, 32) && !!n.initializer; } @@ -41767,7 +43605,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 +43629,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 +43656,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 156) { + if (node.kind === 158) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -41835,7 +43673,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 +43704,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 +43751,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 +43760,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 +43775,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 +43801,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 +43819,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 +43834,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 +43916,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 +43949,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 +44004,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 +44066,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 +44128,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 +44152,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 +44212,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 +44232,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 +44250,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 +44282,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 +44300,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 +44358,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 +44373,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 +44438,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 +44476,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 +44488,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 +44504,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); @@ -42691,42 +44540,42 @@ 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: + case 241: 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 176: checkUnusedTypeParameters(node, addDiagnostic); break; default: @@ -42747,11 +44596,11 @@ var ts; 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) { + case 154: + case 158: + case 159: + if (member.kind === 159 && member.symbol.flags & 32768) { break; } var symbol = getSymbolOfNode(member); @@ -42759,7 +44608,7 @@ var ts; addDiagnostic(member, 0, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 155: + 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)) { @@ -42767,8 +44616,8 @@ var ts; } } break; - case 160: - case 215: + case 162: + case 217: break; default: ts.Debug.fail(); @@ -42777,9 +44626,9 @@ var ts; } } function checkUnusedTypeParameters(node, addDiagnostic) { - if (node.flags & 4194304 || node.kind !== 174 && ts.last(getSymbolOfNode(node).declarations) !== node) + if (node.flags & 4194304 || node.kind !== 176 && ts.last(getSymbolOfNode(node).declarations) !== node) return; - if (node.kind === 174) { + if (node.kind === 176) { 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))); @@ -42794,7 +44643,7 @@ var ts; continue; var name = ts.idText(typeParameter.name); var parent = typeParameter.parent; - if (parent.kind !== 174 && parent.typeParameters.every(isTypeParameterUnused)) { + if (parent.kind !== 176 && parent.typeParameters.every(isTypeParameterUnused)) { if (seenParentsWithEveryUnused.tryAdd(parent)) { var range = ts.isJSDocTemplateTag(parent) ? ts.rangeOfNode(parent) @@ -42874,7 +44723,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 +44741,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 +44762,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 +44774,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 +44819,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 +44839,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 +44854,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 +44877,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 +44889,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 +44897,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 +44909,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 +44927,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 +44936,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 +44950,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 +44960,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 +44986,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; @@ -43158,24 +45007,24 @@ var ts; 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 (parent.initializer && property) { + checkPropertyAccessibility(parent, 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 +45041,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 +45067,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 +45081,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 +45123,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 +45140,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 +45179,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 +45203,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 +45214,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 +45224,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 +45266,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 +45284,7 @@ var ts; reportedError = true; } } - if (arrayType.flags & 32768) { + if (arrayType.flags & 131072) { return stringType; } } @@ -43456,7 +45309,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 +45334,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 +45365,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 +45442,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 +45457,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 +45485,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 +45510,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 +45522,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 +45546,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 +45641,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 +45666,7 @@ var ts; case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -43965,13 +45825,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); } } @@ -44013,7 +45875,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 +45893,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 +45916,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 +45934,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 +45981,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 +46013,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 +46023,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 +46045,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 +46141,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 +46225,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 +46256,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 +46279,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 +46315,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 +46338,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 +46381,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 +46405,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 +46418,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 +46426,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 +46449,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 +46468,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 +46504,7 @@ var ts; checkImportBinding(importClause); } if (importClause.namedBindings) { - if (importClause.namedBindings.kind === 249) { + if (importClause.namedBindings.kind === 251) { checkImportBinding(importClause.namedBindings); } else { @@ -44663,16 +46527,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 +46558,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 +46577,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 +46585,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 +46603,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 +46616,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 +46648,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 +46683,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 +46699,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 +46906,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 +46971,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 +46984,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -45181,24 +47051,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 +47103,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 +47142,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 +47157,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 +47172,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 +47189,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 +47198,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 +47230,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 +47245,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 +47257,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 +47279,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; @@ -45432,12 +47302,12 @@ var ts; 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 +47317,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 +47332,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 +47360,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 +47430,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 +47464,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 +47526,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 +47542,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 +47568,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 +47583,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 +47596,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 +47638,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 +47657,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 +47668,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 +47681,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 +47715,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 +47743,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 +47764,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 +47775,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 +47797,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 +47831,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 +47849,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 +47857,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 +47877,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 +47892,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 +47942,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -46056,12 +47972,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 +47985,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 +48043,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 +48057,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 +48079,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 +48115,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 +48141,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 +48174,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 +48221,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 +48245,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 +48275,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 +48288,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 +48298,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 +48310,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 +48333,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 +48390,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 +48405,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 +48420,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 +48443,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 +48486,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 +48542,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 +48606,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 +48641,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 +48671,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 +48684,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 +48699,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 +48715,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 +48740,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 +48817,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 +48827,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 +48836,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 +48849,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 +48889,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 +48913,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 +48939,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 +48964,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 +48987,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 +49005,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 +49015,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 +49029,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 +49057,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 +49106,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 +49117,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 +49134,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 +49162,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 +49188,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 +49229,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 +49248,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 +49256,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 +49264,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 +49273,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 +49288,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 +49308,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 +49325,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 +49391,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 +49400,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 +49424,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 +49477,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 +49499,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 +49523,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 +49599,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 +49625,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 +49680,7 @@ var ts; : expression; } function createComputedPropertyName(expression) { - var node = createSynthesizedNode(147); + var node = createSynthesizedNode(149); node.expression = parenthesizeForComputedName(expression); return node; } @@ -47700,7 +49692,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 +49708,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 +49732,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 +49744,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 +49764,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 +49779,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 +49788,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 +49805,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 +49833,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 +49853,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 +49876,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 +49897,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 +49905,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 +49913,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 +49951,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 +49965,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 +49979,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 +49987,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 +49995,7 @@ var ts; } ts.updateConstructorTypeNode = updateConstructorTypeNode; function createTypeQueryNode(exprName) { - var node = createSynthesizedNode(165); + var node = createSynthesizedNode(167); node.exprName = exprName; return node; } @@ -48015,7 +50007,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 +50019,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 +50031,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 +50043,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 +50055,7 @@ var ts; } ts.updateOptionalTypeNode = updateOptionalTypeNode; function createRestTypeNode(type) { - var node = createSynthesizedNode(170); + var node = createSynthesizedNode(172); node.type = type; return node; } @@ -48075,7 +50067,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 +50075,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 +50094,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 +50112,7 @@ var ts; } ts.updateConditionalTypeNode = updateConditionalTypeNode; function createInferTypeNode(typeParameter) { - var node = createSynthesizedNode(174); + var node = createSynthesizedNode(176); node.typeParameter = typeParameter; return node; } @@ -48132,7 +50124,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 +50142,7 @@ var ts; } ts.updateImportTypeNode = updateImportTypeNode; function createParenthesizedType(type) { - var node = createSynthesizedNode(175); + var node = createSynthesizedNode(177); node.type = type; return node; } @@ -48162,12 +50154,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 +50169,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 +50183,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 +50201,7 @@ var ts; } ts.updateMappedTypeNode = updateMappedTypeNode; function createLiteralTypeNode(literal) { - var node = createSynthesizedNode(180); + var node = createSynthesizedNode(182); node.literal = literal; return node; } @@ -48221,7 +50213,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 +50225,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 +50237,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 +50255,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 +50269,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 +50283,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 +50298,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 +50312,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 +50328,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 +50344,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 +50367,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 +50381,7 @@ var ts; } ts.updateTypeAssertion = updateTypeAssertion; function createParen(expression) { - var node = createSynthesizedNode(193); + var node = createSynthesizedNode(195); node.expression = expression; return node; } @@ -48401,7 +50393,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 +50417,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 +50439,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 +50451,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 +50463,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 +50475,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 +50487,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 +50500,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 +50513,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 +50530,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 +50550,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 +50564,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 +50602,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 +50614,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 +50635,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 +50653,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 +50667,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 +50679,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 +50692,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 +50706,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 +50724,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 +50739,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 +50757,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 +50773,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 +50787,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 +50801,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 +50819,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 +50835,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 +50853,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 +50865,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 +50877,7 @@ var ts; } ts.updateBreak = updateBreak; function createReturn(expression) { - var node = createSynthesizedNode(228); + var node = createSynthesizedNode(230); node.expression = expression; return node; } @@ -48897,7 +50889,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 +50903,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 +50917,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 +50931,7 @@ var ts; } ts.updateLabel = updateLabel; function createThrow(expression) { - var node = createSynthesizedNode(232); + var node = createSynthesizedNode(234); node.expression = expression; return node; } @@ -48951,7 +50943,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 +50959,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 +50980,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 +50993,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 +51019,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 +51041,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 +51063,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 +51083,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 +51102,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 +51121,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 +51133,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 +51145,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 +51157,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 +51175,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 +51193,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 +51207,7 @@ var ts; } ts.updateImportClause = updateImportClause; function createNamespaceImport(name) { - var node = createSynthesizedNode(249); + var node = createSynthesizedNode(251); node.name = name; return node; } @@ -49227,7 +51219,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 +51231,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 +51245,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 +51262,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 +51280,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 +51292,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 +51306,7 @@ var ts; } ts.updateExportSpecifier = updateExportSpecifier; function createExternalModuleReference(expression) { - var node = createSynthesizedNode(257); + var node = createSynthesizedNode(259); node.expression = expression; return node; } @@ -49325,8 +51317,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 +51375,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 +51391,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 +51407,7 @@ var ts; } ts.updateJsxOpeningElement = updateJsxOpeningElement; function createJsxClosingElement(tagName) { - var node = createSynthesizedNode(261); + var node = createSynthesizedNode(263); node.tagName = tagName; return node; } @@ -49386,7 +51419,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 +51435,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 +51449,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 +51461,7 @@ var ts; } ts.updateJsxAttributes = updateJsxAttributes; function createJsxSpreadAttribute(expression) { - var node = createSynthesizedNode(267); + var node = createSynthesizedNode(269); node.expression = expression; return node; } @@ -49440,7 +51473,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 +51486,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 +51500,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 +51512,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 +51525,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 +51539,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 +51554,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 +51568,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 +51580,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 +51600,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 +51674,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 +51711,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 +51734,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 +51749,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 +51776,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 +51858,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 +52289,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 +52301,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 +52329,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 +52341,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 +52353,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 +52406,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 +52421,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 +52584,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 +52607,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 +52618,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 +52627,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 +52638,7 @@ var ts; case -1: if (!isLeftSideOfBinary && binaryOperatorAssociativity === 1 - && operand.kind === 205) { + && operand.kind === 207) { return false; } return true; @@ -50617,7 +52654,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 +52667,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 +52692,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 +52713,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 +52724,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 +52737,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 +52775,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 +52786,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 +52816,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 +52844,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 +52872,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 +52917,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 +52925,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 +52995,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 +53006,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 +53061,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 +53081,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 +53093,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 +53101,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 +53109,7 @@ var ts; : propertyName; } break; - case 275: + case 277: return bindingElement.name; } var target = getTargetOfBindingOrAssignmentElement(bindingElement); @@ -51086,16 +53123,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 +53171,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 +53312,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 +53592,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 +53634,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 +53716,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 +53839,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 +53847,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 +54025,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 +54066,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 +54102,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.getPositionOfLineAndCharacter(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.getPositionOfLineAndCharacter(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 +54697,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 +54741,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 +54777,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 +54790,7 @@ var ts; } } break; - case 237: + case 239: if (ts.hasModifier(node, 1)) { if (ts.hasModifier(node, 512)) { if (!hasExportDefault) { @@ -52440,7 +54808,7 @@ var ts; } } break; - case 238: + case 240: if (ts.hasModifier(node, 1)) { if (ts.hasModifier(node, 512)) { if (!hasExportDefault) { @@ -52706,8 +55074,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 +55122,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 +55253,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 +55267,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 +55305,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 +55322,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 +55347,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 +55365,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 +55381,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 +55401,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 +55419,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 +55429,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 +55552,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 +55592,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 +55666,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 +55701,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 +55745,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 +55779,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 +55795,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 +55856,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 +55940,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 +56009,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 +56024,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 +56051,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 +56091,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 +56113,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 +56211,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 +56221,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 +56249,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 +56262,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 +56278,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 +56329,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 +56531,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 +56584,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 +56654,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 +56678,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 +56704,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 +56806,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 +56825,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 +56891,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 +56907,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 +56925,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 +57020,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 +57041,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 +57070,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 +57239,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 +57247,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 +57288,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -54904,14 +57314,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 +57336,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 +57354,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 +57389,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 +57435,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 +57447,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 +57469,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 +57488,7 @@ var ts; return visitorWorker(node, true); } function visitorNoAsyncModifier(node) { - if (node.kind === 120) { + if (node.kind === 121) { return undefined; } return node; @@ -55055,48 +57498,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 +57581,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 +57593,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 +57602,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 +57613,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 +57635,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 +57656,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 +57743,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 +57820,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 +57868,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 +57883,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 +57905,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 +57923,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 +57958,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 +58057,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 +58071,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 +58138,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 +58203,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 +58503,7 @@ var ts; return node; } switch (node.kind) { - case 202: + case 204: return visitBinaryExpression(node); default: return ts.visitEachChild(node, visitor, context); @@ -56038,9 +58511,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 +58593,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 +58618,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 +58796,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 +58813,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 +58832,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 +58893,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 +58949,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 +58977,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 +59016,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 +59059,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 +59099,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 +59126,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 +59143,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 +59174,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 +59258,7 @@ var ts; return call; } function visitArrowFunction(node) { - if (node.transformFlags & 16384) { + if (node.transformFlags & 8192) { enableSubstitutionsForCapturedThis(); } var savedConvertedLoopState = convertedLoopState; @@ -56839,7 +59312,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 +59344,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 +59375,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 +59397,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 +59407,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 +59435,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 +59466,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 +59540,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 +59667,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 +59693,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 +59718,7 @@ var ts; } visit(node.name); function visit(node) { - if (node.kind === 71) { + if (node.kind === 72) { state.hoistedLocalVariables.push(node); } else { @@ -57237,7 +59732,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 +59746,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 +59822,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 +60041,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 +60073,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 +60158,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 +60239,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 +60266,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 +60292,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 +60364,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 +60406,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 +60431,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 +60468,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 +60479,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 +60532,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 +60570,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 +60588,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 +60641,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 +60722,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 +60736,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 +60769,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 +60791,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 +60895,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 +60926,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 +60950,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 +60975,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 +60989,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 +61005,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 +61108,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 +61154,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 +61476,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 +61486,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 +61576,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 +61608,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 +61721,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 +62301,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 +62315,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 +62359,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 +62497,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 +62538,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 +62587,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 +62870,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 +62902,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 +63006,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 +63053,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 +63073,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 +63109,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 +63179,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 +63198,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 +63288,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 +63311,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 +63362,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 +63392,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 +63519,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 +63541,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 +63580,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 +63683,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 +63813,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 +63856,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 +63864,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 +63905,7 @@ var ts; } function substituteUnspecified(node) { switch (node.kind) { - case 274: + case 276: return substituteShorthandPropertyAssignment(node); } return node; @@ -61332,12 +63927,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 +63977,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 +64008,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 +64036,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 +64063,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 +64151,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 +64180,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 +64227,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 +64243,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 +64267,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 +64304,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 +64328,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 +64341,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 +64366,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 +64394,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 +64406,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 +64420,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 +64461,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 +64495,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 +64519,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -61942,6 +64537,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 +64547,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) { @@ -62018,15 +64614,16 @@ var ts; } } 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 +64635,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 +64671,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 +64684,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 +64720,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 +64746,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 +64768,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 +64780,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 +64791,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 +64802,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 +64820,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 +64836,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 +64907,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 +64927,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 +64947,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 +65027,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 +65089,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 +65105,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 +65140,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 +65149,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 +65171,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 +65184,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 +65207,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 +65251,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 +65262,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 +65287,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 +65295,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 +65313,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 +65333,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 242) { + if (input.kind === 244) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -62724,7 +65354,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 +65417,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 +65437,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 +65451,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 +65486,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 +65495,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 +65590,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 +65607,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 +65799,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 +65829,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 +65865,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 +65882,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 +65904,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 +65968,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 +65988,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 +66003,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 +66014,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 +66123,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 +66160,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 +66172,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 +66185,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 +66200,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 +66225,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 +66252,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 +66278,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 +66342,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 +66611,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 +66701,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 +66738,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -64678,13 +66746,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 +66765,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 +66773,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 71) { + if (node.kind === 72) { emitExpression(node); } else { @@ -64738,7 +66806,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 +66824,7 @@ var ts; emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); @@ -64766,7 +66834,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 +66845,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitMethodDeclaration(node) { @@ -64796,7 +66864,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 +66876,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitConstructSignature(node) { @@ -64820,7 +66888,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitIndexSignature(node) { @@ -64828,10 +66896,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 +66923,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 +66959,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 +66969,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 +67038,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 +67086,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 +67106,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 +67115,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 +67128,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 +67161,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 +67190,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 +67211,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 +67239,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,23 +67266,23 @@ 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); } @@ -65256,36 +67324,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 +67368,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 +67391,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 +67438,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 +67471,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 +67513,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 +67530,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 +67578,7 @@ var ts; } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } function emitSignatureHead(node) { @@ -65551,7 +67624,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 +67635,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 +67662,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 +67675,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 +67692,7 @@ var ts; writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); @@ -65628,7 +67701,7 @@ var ts; emit(node.name); writeSpace(); writePunctuation("{"); - emitList(node, node.members, 81); + emitList(node, node.members, 145); writePunctuation("}"); } function emitModuleDeclaration(node) { @@ -65640,8 +67713,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 +67729,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 +67754,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 +67787,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 +67835,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 +67855,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 +67867,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 +67882,6 @@ var ts; writePunctuation(">"); } function emitJsxText(node) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, true)); } function emitJsxClosingElementOrFragment(node) { @@ -65820,7 +67892,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 +67912,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 71) { + if (node.kind === 72) { emitExpression(node); } else { @@ -65848,13 +67920,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 +67934,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 +67949,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); @@ -65920,6 +67992,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 +68140,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 +68197,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 +68232,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 +68263,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 131328); + emitList(node, modifiers, 262656); writeSpace(); } } @@ -66066,7 +68277,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 +68314,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 +68358,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 +68374,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 +68384,11 @@ var ts; writeSpace(); writePunctuation("|"); break; + case 32: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case 8: writeSpace(); writePunctuation("&"); @@ -66176,11 +68399,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 +68412,7 @@ var ts; } return; } - if (format & 7680) { + if (format & 15360) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { emitTrailingCommentsOfPosition(children.pos, true); @@ -66202,41 +68425,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 +68483,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 +68585,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 +68617,7 @@ var ts; return true; } if (format & 2) { - if (format & 32768) { + if (format & 65536) { return true; } var firstChild = children[0]; @@ -66448,10 +68656,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 +68681,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 +68704,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 +68716,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 +68724,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 +68763,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 +68846,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 +68891,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 +68956,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, true); } function generateNameForModuleOrEnum(node) { @@ -66775,23 +68983,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 +69031,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 +69719,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 +69748,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 +69758,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 +69766,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 +69777,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 +69789,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 +69805,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 +69839,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 +69865,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 +69944,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 +69960,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 +69999,7 @@ var ts; } } ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { if (names.length === 0) { return []; } @@ -67480,19 +70012,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 +70044,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 +70079,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 +70107,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 +70125,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 +70143,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 +70160,32 @@ 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 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 +70194,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 +70215,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 +70263,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 +70301,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 +70325,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 +70364,7 @@ var ts; } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; @@ -67804,7 +70374,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 +70394,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 +70441,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 +70458,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 +70482,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 +70528,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 +70554,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 +70573,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 +70603,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 +70618,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 +70675,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 +70729,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 +70805,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -68242,62 +70813,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 +70881,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 +70936,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 +70995,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 +71022,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 +71048,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 +71084,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 +71127,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 +71181,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 +71202,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 +71255,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 +71267,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 +71299,76 @@ 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) { + 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) { + return forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + if (!referencedProject || + toPath(options.configFilePath) === referenceProjectPath || + !ts.contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + return referencedProject; }); - return result; + } + 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); + }); + } + 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 +71377,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 +71393,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 +71412,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 +71456,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 +71465,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 +71478,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 +71497,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 +71577,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 +71636,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 +71654,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 +71669,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 +71682,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 +71754,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 +71832,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 +71849,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 +71895,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 +71910,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 +71961,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 +71986,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 +72012,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 +72022,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 +72138,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 +72195,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 +72241,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 +72276,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 +72314,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 +72328,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 +72341,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 +72409,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 +72500,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 +72513,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 +72646,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 +72676,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 +72690,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 +72709,7 @@ var ts; resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -70024,7 +72767,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -70040,13 +72783,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 +72797,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 +72810,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 +72870,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 +72907,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 +72922,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 +72944,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 +72972,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 +73024,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 +73071,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 +73139,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 +73174,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 +73219,100 @@ 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 (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++; } - 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]; + return count; } 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 +73370,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 +73387,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 +73408,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 +73456,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 +73515,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 +73579,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 +73626,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 +73655,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 +73674,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 +73686,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 +73714,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 +73728,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 +73747,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 +73763,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 +73798,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 +73814,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 +73870,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 +73904,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 +73930,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 +74039,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 +74049,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 +74092,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 +74116,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 +74126,7 @@ var ts; if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { resolutionCache.invalidateResolutionOfFile(path); } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); scheduleProgramUpdate(); } @@ -71348,6 +74163,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 +74212,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 +74225,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 +74291,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 +74306,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 +74327,750 @@ 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); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - 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; + 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 invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); + } + 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; + 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 }; 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); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + 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 +75105,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 +75113,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 +75260,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 +75284,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 +75352,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 +75367,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 +75389,49 @@ 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 wathc + var builder = ts.createSolutionBuilder(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)), 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 +75443,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..2e2de2b5623 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.2"; /** 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) { @@ -2628,6 +3070,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2678,6 +3121,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 +3154,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 +3193,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 +3299,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 +3317,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 +3347,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 +3416,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 +3428,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 +3460,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 +3480,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 +3741,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 +3774,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 +3871,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 +3886,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 +4038,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 +4255,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 +4590,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 +5206,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 +5245,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."), @@ -4850,14 +5306,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'."), @@ -5037,7 +5493,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 +5520,14 @@ 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."), 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 +5619,14 @@ 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}'."), 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 +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."), @@ -5363,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}'."), @@ -5461,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}"), @@ -5491,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."), @@ -5501,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."), @@ -5528,6 +6014,14 @@ 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."), 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 +6052,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."), @@ -5686,150 +6181,105 @@ 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"), }; })(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 :: @@ -6407,6 +6857,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6417,8 +6868,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 +6887,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6511,18 +6963,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 +7000,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 +7032,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 +7101,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 +7109,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 +7209,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 +7292,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 +7325,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 +7402,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 +7433,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 +7564,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 +7621,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 +7641,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 +7667,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 +7687,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 +7717,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 +7770,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 +7837,7 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 12 /* RegularExpressionLiteral */; + token = 13 /* RegularExpressionLiteral */; } return token; } @@ -7349,7 +7845,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 +7862,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 +7901,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 +7927,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 +7951,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,6 +8064,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7588,7 +8087,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7635,7 +8133,6 @@ var ts; getText: function () { return str; }, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -7644,7 +8141,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 +8169,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 +8276,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 +8342,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 +8350,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 +8488,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 +8506,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 +8546,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 +8599,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 +8631,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 +8652,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 +8670,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 +8695,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 +8707,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 +8735,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 +8745,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 +8783,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 +8798,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 +8847,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 +8861,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 +8870,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 +8924,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 +8937,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 +8949,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 +8978,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 +9028,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 +9086,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 +9112,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 +9154,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 +9167,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 +9180,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 +9199,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 +9211,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 +9228,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 +9236,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 +9259,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 +9296,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 +9318,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 +9331,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 +9360,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 +9384,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 +9420,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 +9438,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 +9447,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 +9468,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 +9480,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 +9514,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 +9526,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 +9536,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 +9596,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 +9646,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 +9655,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 +9683,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 +9709,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 +9739,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 +9796,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 +9844,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 +9859,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 +9888,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 +9926,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 +9957,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 +9966,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 +9980,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 +9989,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 +10006,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 +10020,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 +10032,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 +10052,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 +10068,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 +10098,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 +10113,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 +10128,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 +10143,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 +10166,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 +10201,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 +10214,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 +10265,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 +10297,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 +10341,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 +10381,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 +10421,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 +10439,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 +10450,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 +10467,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 +10501,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 +10517,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 +10540,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 +10561,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 +10589,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 +10605,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 +10626,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 +10637,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 +10656,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 +10665,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 +10677,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 +10704,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 +10744,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 +10762,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 +10939,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 +10997,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 +11080,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 +11106,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 +11239,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 +11253,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 +11312,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 +11327,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 +11350,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 +11374,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 +11390,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 +11399,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 +11433,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 +11451,7 @@ var ts; } } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -10943,7 +11569,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 +11578,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 +11639,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 +11647,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 +11697,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 +11707,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 +11720,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 +11742,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 +11884,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 +11996,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 +12095,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 +12173,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 +12304,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) { @@ -11769,13 +12439,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 +12575,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 +12585,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 +12615,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 +12766,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 +12812,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 +12875,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 +12903,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 +13043,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 +13077,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 +13769,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 +13779,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 146 /* FirstNode */; + return kind >= 148 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -13091,7 +13788,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 +13800,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 +13810,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 +13819,12 @@ 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 isStringTextContainingNode(node) { - return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; // Identifiers @@ -13140,17 +13837,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 +13860,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 +13869,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 +13900,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 +13915,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 +13937,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 +13969,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,37 +13982,38 @@ 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 */; + 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 */; } /** * Node test that determines whether a node is a valid type node. @@ -13328,8 +14026,8 @@ var ts; 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 +14038,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 +14047,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 +14064,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 +14087,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 +14100,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 +14110,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 +14137,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 +14153,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 +14193,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 +14208,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 +14229,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 +14245,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 +14267,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 +14281,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 +14305,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 +14438,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 +14451,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 +14555,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 +14589,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 +14641,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 +14672,6 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; - /* @internal */ function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -14000,7 +14696,6 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; - /* @internal */ function createCompilerDiagnosticFromMessageChain(chain) { return { file: undefined, @@ -14037,14 +14732,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 +14798,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 +14826,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 +14839,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 +15041,6 @@ var ts; return rootLength > 0 && rootLength === path.length; } ts.isDiskPathRoot = isDiskPathRoot; - /* @internal */ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath @@ -14414,8 +15118,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 +15339,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 +15406,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 +15633,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 +15811,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 +15989,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 +16100,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 +16152,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 +16182,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,357 +16190,358 @@ 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 */: + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -15725,17 +16550,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 298 /* JSDocReturnTag */: + case 300 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 281 /* JSDocTypeExpression */) { + node.typeExpression.kind === 283 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -15743,20 +16568,20 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 295 /* JSDocCallbackTag */: + case 297 /* JSDocCallbackTag */: return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 299 /* JSDocThisTag */: + case 301 /* JSDocThisTag */: return visitNode(cbNode, node.typeExpression); - case 296 /* JSDocEnumTag */: + case 298 /* JSDocEnumTag */: return visitNode(cbNode, node.typeExpression); - case 291 /* JSDocSignature */: + case 293 /* JSDocSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 290 /* JSDocTypeLiteral */: + case 292 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -15764,7 +16589,7 @@ var ts; } } return; - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -15774,7 +16599,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 +16768,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 +16807,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 +16826,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 +16963,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 +17168,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 +17224,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 +17288,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 +17309,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 +17320,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 +17330,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 +17351,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 +17372,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 +17396,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 +17425,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 +17435,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 +17472,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 +17513,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 +17530,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 +17559,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 +17609,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 +17779,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 +17801,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 +17811,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 +17883,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 +17940,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 +17950,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 +18007,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 +18019,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 +18050,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 +18086,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 +18118,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 +18143,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 +18164,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 +18182,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 +18260,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 +18307,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 +18329,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 +18359,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 +18372,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 +18385,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 +18413,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 +18432,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 +18476,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 +18486,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 +18497,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 +18522,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 +18554,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 +18649,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 +18732,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 +18779,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 +18824,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 +18841,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 +18864,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 +18894,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -18057,17 +18902,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 +18924,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 +18935,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 +18946,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 +19000,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 +19029,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 +19046,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 +19055,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 +19100,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 +19116,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 +19145,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 +19164,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 +19202,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 +19213,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 +19226,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 +19259,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 +19302,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 +19312,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 +19341,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 +19354,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 +19380,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 +19391,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 +19428,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 +19449,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 +19478,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 +19508,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 +19562,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 +19586,7 @@ var ts; */ if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); - return token() === 40 /* AsteriskAsteriskToken */ ? + return token() === 41 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } @@ -18757,10 +19603,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 +19631,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 +19670,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 +19702,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 +19757,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 +19772,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 +19783,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 +19842,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 +19866,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 +19885,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 +19901,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 +19918,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 +19947,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 +19964,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 +19994,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 +20005,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 +20042,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 +20116,7 @@ var ts; } indexedAccess.argumentExpression = argument; } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } @@ -19282,13 +20128,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 +20142,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 +20155,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 +20173,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 +20195,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 +20234,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 +20258,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 +20335,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 +20371,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 +20382,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 +20394,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 +20413,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 +20456,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 +20509,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 +20543,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 +20551,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 +20560,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 +20607,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 +20642,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 +20653,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 +20671,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 +20712,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 +20759,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 +20812,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 +20821,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 +20890,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 +20909,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 +20944,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 +20955,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 +20966,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 +20992,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 +21021,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 +21034,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 +21057,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 +21069,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 +21126,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 +21139,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 +21162,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 +21172,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 +21207,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 +21230,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 +21249,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 +21259,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 +21282,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 +21330,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 +21342,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 +21376,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 +21390,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 +21409,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 +21420,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 +21442,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 +21452,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 +21525,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 +21534,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 +21545,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 +21568,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 +21583,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 +21604,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 +21615,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 +21640,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 +21660,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 +21676,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 +21727,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 +21819,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 +21839,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 +21852,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 +21866,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 +21890,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 +21924,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 +22007,7 @@ var ts; } indent = 0; break; - case 57 /* AtToken */: + case 58 /* AtToken */: scanner.setTextPos(scanner.getTextPos() - 1); // falls through case 1 /* EndOfFileToken */: @@ -21184,9 +22026,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 +22036,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 +22056,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 +22076,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 +22116,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 +22132,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 +22155,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 +22234,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 +22251,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 +22269,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 +22283,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 +22333,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 +22357,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 +22371,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 +22396,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 +22433,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 +22450,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 +22580,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 +23160,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 +23220,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 +23237,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22427,6 +23251,49 @@ 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 + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22468,26 +23335,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 +23355,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 +23375,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 +23388,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 +23396,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 +23414,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 +23524,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22674,6 +23533,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22682,14 +23542,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 +23568,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22706,6 +23577,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22739,6 +23611,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22751,6 +23624,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 +23632,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 +23642,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 +23658,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 +23670,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 +23681,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 @@ -22887,30 +23766,12 @@ var ts; 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 +23830,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 +23850,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 +23896,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 +23904,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 +23932,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 +23960,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 +24051,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 +24101,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 +24121,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 +24129,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 +24165,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23303,9 +24208,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 +24233,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 +24388,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 +24530,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 +24578,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 +24612,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 +24635,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 +24675,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 +24794,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 +24942,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 +24960,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 +25011,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 +25030,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24027,17 +25043,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 +25155,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 +25182,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 +25213,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 +25427,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 +25452,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 +25470,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 +25496,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 +25507,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 +25649,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 +25705,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 +25720,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 +25737,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 +25869,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 +25894,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 +25906,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 +25920,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 +25943,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 +25990,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 +26012,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 +26136,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 +26170,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 +26182,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 +26257,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 +26316,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 +26335,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 +26346,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 +26425,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 +26442,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 +26473,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 +26519,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 +26568,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 +26592,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 +26630,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 +26642,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 +26719,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 +26728,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 +26858,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 +26871,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 +26948,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 +26979,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 +27018,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 +27165,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 +27190,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 +27202,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 +27300,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 +27329,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 +27356,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 +27379,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 +27423,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 +27455,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 +27468,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 +27517,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 +27547,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 +27633,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 +27667,7 @@ var ts; } } } - if (expr.expression.kind === 187 /* PropertyAccessExpression */ && + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } @@ -26465,32 +27681,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 +27741,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 +27780,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 +27848,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 +27882,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 +27910,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 +27930,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 +28026,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 +28050,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 +28093,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 +28111,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 +28122,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 +28139,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 +28150,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 +28160,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 +28187,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 +28198,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -27030,10 +28245,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 +28256,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 +28265,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 +28345,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 +28404,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 +28436,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 +28445,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 +28465,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 +28492,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 +28504,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 +28536,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 +28553,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 +28570,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 +28588,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 +28625,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 +28636,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 +28677,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 +28704,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 +28773,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 +28797,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 +28835,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 +28844,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 +28893,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 +29073,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 +29128,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 +29152,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 +29179,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 +29202,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 +29222,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 +29239,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 +29260,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 +29294,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 +29344,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 (ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } var init = !node ? undefined : ts.isVariableDeclaration(node) ? node.initializer : ts.isBinaryExpression(node) ? node.right : @@ -28103,7 +29360,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 +29402,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 +29444,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 +29460,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 +29480,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 +29498,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 +29539,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 +29573,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 +29615,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 +29652,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 +29666,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 +29730,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 +29795,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 +29823,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 +29848,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 +29894,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 +29905,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 +29917,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 +29927,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 +29947,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 +29958,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 +29972,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 +29984,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 +29999,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 +30012,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 +30031,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 +30047,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 +30063,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 +30080,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 +30109,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 +30130,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 +30141,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 +30165,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 +30176,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 +30185,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 +30266,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 +30337,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 +30436,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 +30558,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 +30574,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 +30672,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 +30715,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 +30747,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 +30757,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"); @@ -29655,10 +30938,6 @@ var ts; 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); @@ -29683,14 +30962,15 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, 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 +30978,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 +31032,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29775,24 +31056,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 +31105,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 +31128,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29846,6 +31148,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29857,7 +31160,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 +31170,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 +31196,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 +31309,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 +31446,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 +31507,10 @@ 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); + target = cloneSymbol(resolveSymbol(target)); } // 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 +31520,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 +31541,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 +31606,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 +31669,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 +31699,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 +31727,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 +31756,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 +31769,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 +31792,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 +31843,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 +31885,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 +31916,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 +31930,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 +31946,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 +31974,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 +31982,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 +32002,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 +32037,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 +32046,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 +32059,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; @@ -30742,8 +32079,8 @@ var ts; } 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 +32089,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 +32144,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 +32161,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 +32178,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 +32233,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 +32246,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 +32267,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 +32303,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 +32320,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 +32338,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 +32354,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 +32392,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 +32446,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 +32502,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 +32536,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 +32546,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 +32570,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 +32604,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 +32620,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 +32642,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 +32666,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 +32686,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 +32721,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 +32737,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,6 +32759,16 @@ var ts; return symbol && symbol.valueDeclaration; } } + 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) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31434,7 +32798,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.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31453,7 +32817,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 +32849,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 +32857,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 +32869,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 +32911,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 +32979,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 */) : @@ -31750,13 +33118,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 +33147,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 +33202,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 +33218,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 +33268,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 +33307,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 +33322,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 +33336,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 +33378,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 +33442,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 +33492,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); @@ -32148,6 +33529,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32164,15 +33548,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 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; } } @@ -32230,9 +33614,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 & 67108864 /* 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 +33646,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 +33745,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 +33765,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 +33792,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 +33819,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 +33843,60 @@ 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 */); + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } } else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.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) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + 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 +33910,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 +33931,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 +33963,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 +34003,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 +34016,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,11 +34068,11 @@ 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 */ ? @@ -32697,26 +34114,21 @@ var ts; 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) { @@ -32729,9 +34141,9 @@ 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 */); + var 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 +34194,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 +34207,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 +34218,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 +34237,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 +34259,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 +34271,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 +34282,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 +34300,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 & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32979,7 +34404,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 +34434,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,7 +34449,7 @@ 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; @@ -33116,6 +34548,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 */; } @@ -33169,12 +34604,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 +34619,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 +34636,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 +34645,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 +34672,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 +34712,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 +34740,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 +34795,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 +34820,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 +34869,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 +34879,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 +34894,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 +34929,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 +34982,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 +35005,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 +35015,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 +35043,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 +35059,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 +35073,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 +35095,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 +35110,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 +35126,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 +35161,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 +35178,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 +35193,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 +35205,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 +35241,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 +35255,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 +35307,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33875,9 +35316,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 +35330,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 +35339,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 +35353,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 +35393,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 +35416,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 +35438,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 +35446,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 +35491,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 +35524,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 +35546,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 +35564,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 +35591,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 +35621,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 +35635,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 +35643,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 +35675,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 +35686,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 +35715,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 +35724,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 +35788,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 +35812,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 +35848,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 +35857,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 +35886,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 +35929,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 +35939,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 +35979,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 +35998,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 @@ -34590,14 +36046,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); @@ -34633,7 +36089,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 +36098,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 +36130,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 +36147,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 +36171,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 +36185,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 +36207,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 +36222,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 +36234,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 +36269,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 +36313,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 +36355,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 +36371,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 +36420,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 +36463,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 +36486,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 +36631,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 +36740,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 +36760,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 +36794,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 +36840,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 +36876,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 +36899,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 +36937,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 +36953,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 +36971,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 +36981,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 +37000,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 +37015,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 +37029,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 +37041,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 +37064,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 +37077,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 +37094,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 +37122,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 +37139,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 +37150,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 +37159,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 +37183,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 +37193,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 +37207,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 +37226,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 +37264,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 +37284,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 +37312,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 +37322,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 +37344,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 +37352,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 +37375,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 +37460,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 +37520,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 +37608,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 +37646,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 +37700,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 +37739,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 +37764,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 +37802,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 +37815,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 +37825,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 +37839,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 +37883,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 +37906,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 +37970,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 +37987,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 +37997,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 +38011,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 +38037,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 +38047,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 +38067,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 +38113,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 +38130,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 +38144,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 +38171,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 +38179,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 +38210,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 +38234,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 +38307,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 +38340,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 +38367,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 +38395,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 +38424,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 +38433,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 +38470,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 +38485,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 +38498,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 +38556,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 +38599,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 +38610,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 +38621,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 +38652,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 +38681,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 +38744,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 +38766,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 +38801,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 +38811,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 +38849,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 +38867,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 +38886,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 +38901,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 +38914,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 +38943,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 +38970,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 +39027,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 +39037,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 +39063,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 +39078,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 +39087,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 +39098,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 +39114,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 +39131,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 +39169,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 +39185,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 +39209,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 +39218,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 +39243,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 +39253,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 +39276,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 +39285,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 +39305,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 +39324,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 +39345,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; + 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 +39409,7 @@ var ts; } return indexInfo.type; } - if (indexType.flags & 32768 /* Never */) { + if (indexType.flags & 131072 /* Never */) { return neverType; } if (isJSLiteralType(objectType)) { @@ -37882,15 +39435,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 +39453,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 +39496,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 +39517,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 +39530,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 +39540,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 +39556,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 +39587,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 +39609,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 +39620,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 +39659,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 +39691,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 +39714,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 +39757,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 +39787,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 +39801,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 +39834,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 +39849,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 +39899,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 +39914,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 +39923,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 +39963,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 +39975,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 +40007,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 +40022,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 +40040,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 +40189,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 +40203,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 +40252,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 +40290,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 +40300,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 +40332,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 +40341,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 +40380,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 +40424,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 +40469,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 +40548,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 +40592,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 +40605,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 +40623,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 +40638,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 +40656,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 +40687,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 +40787,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 +40806,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 +40817,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 +40863,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 +40896,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 +40921,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 +40952,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 +40983,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 +41009,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 +41025,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 +41039,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 +41117,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 +41162,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 +41208,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 +41251,7 @@ var ts; */ function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; + var relatedInfo; var maybeKeys; var sourceStack; var targetStack; @@ -39552,7 +41259,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 +41286,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 +41339,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 +41347,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 +41363,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 +41392,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 +41405,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 +41425,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 +41445,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 +41478,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 +41494,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 +41520,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 +41531,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 +41557,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 +41597,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 +41622,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 +41635,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 +41663,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 +41699,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 +41724,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 +41781,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 +41824,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 +41847,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 +41907,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 +41920,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 +41947,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 +41975,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 +42033,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 +42086,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 +42128,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 +42144,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 +42208,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 +42279,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 +42310,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 +42408,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 +42503,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 +42555,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 +42712,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; @@ -41022,7 +42824,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 +42845,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 +42869,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. @@ -41086,7 +42888,7 @@ var ts; // 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 +42898,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 +42957,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 +42980,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 +42998,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 +43013,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 +43031,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 +43074,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 +43084,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 +43172,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 +43206,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 +43242,80 @@ 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 */: 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 +43364,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 +43377,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 +43404,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 +43430,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 +43446,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 +43507,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 +43535,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 +43559,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 +43574,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 +43582,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 +43595,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 +43644,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 +43658,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 +43696,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 +43705,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 +43733,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 +43749,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 +43768,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 +43778,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 +43825,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 +43838,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 +43879,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 +43923,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 +43943,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 +43965,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 +43978,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 +43991,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 +44020,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 +44049,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 +44091,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 +44100,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 +44122,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 +44143,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 +44178,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 +44191,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 +44263,7 @@ var ts; } } } - if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -42302,16 +44276,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 +44312,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 +44328,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 +44395,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 +44407,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 +44415,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 +44440,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 +44462,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 +44480,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 +44520,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 +44542,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 +44575,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 +44628,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 +44669,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 +44687,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 +44711,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 +44730,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 +44752,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 +44762,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 +44835,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 +44872,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 +44885,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 +44913,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 +44936,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 +44953,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 +45085,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 +45107,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 +45128,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 +45136,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 +45167,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 +45184,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 +45217,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 +45268,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 +45393,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 +45406,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 +45448,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 +45465,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 +45492,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 +45513,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 +45531,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 +45552,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 +45579,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 +45597,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 +45618,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,7 +45652,7 @@ 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; } @@ -43551,7 +45681,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 +45690,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 +45700,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 +45711,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 +45720,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 +45730,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 +45757,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 +45804,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 +45817,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 +45885,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 +45926,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 +45977,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 +46052,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 +46073,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 +46088,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 +46120,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 +46143,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 +46171,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 +46192,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 +46207,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 +46215,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 +46237,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 +46248,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 +46264,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44067,7 +46279,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 +46293,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 +46321,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 +46355,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 +46367,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 +46388,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 +46449,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 +46457,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 +46472,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 +46516,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 +46577,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44319,10 +46586,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 +46605,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 +46622,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 +46663,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 +46729,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 +46786,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 +46810,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 +46856,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 +46874,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 +46910,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 +46929,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 +46938,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 +46977,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 +46989,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 +47002,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 +47011,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 +47072,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 +47086,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 +47121,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); } @@ -44916,13 +47149,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 +47165,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 +47184,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 +47195,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 +47221,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 +47238,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 +47248,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 +47285,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 +47294,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 +47305,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 +47323,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 +47331,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 +47358,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 +47377,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 +47404,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 +47414,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 +47423,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 +47438,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 +47476,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 +47498,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 +47539,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 +47572,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 +47596,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 +47609,63 @@ var ts; function getJsxElementChildrenPropertyName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType) { - if (!propsType) { - return undefined; - } - 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)); - } - 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; - } - } - } - } - 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); + function getUninstantiatedJsxSignaturesOfType(elementType) { // Resolve the signatures, preferring constructor var signatures = getSignaturesOfType(elementType, 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)); - } + } + if (signatures.length === 0 && elementType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(elementType.types, getUninstantiatedJsxSignaturesOfType)); + } + 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 +47689,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 +47722,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { + function checkJsxOpeningLikeElementOrOpeningFragment(node) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -45748,7 +47733,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 +47744,8 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren(node.parent); + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); } } /** @@ -45779,7 +47762,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 +47772,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 +47780,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 +47809,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 +47825,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 +47857,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 +47897,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 +47923,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 +47975,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,9 +47986,9 @@ 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)); @@ -46053,9 +48000,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 +48010,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 +48045,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 +48058,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 +48098,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 +48138,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); @@ -46254,16 +48207,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 +48243,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 +48273,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 +48297,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 +48309,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 +48328,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 +48355,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 +48363,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 +48396,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 +48433,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 +48460,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 +48518,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 +48529,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 +48538,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 +48558,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 +48594,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 +48646,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 +48687,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 +48713,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 +48857,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 +48880,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 +48912,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 +48928,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 +48975,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 +48999,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 +49045,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 +49138,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 +49149,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 +49188,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 +49227,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 +49261,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 +49277,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 +49306,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 +49366,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 +49385,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 +49442,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 +49470,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 +49485,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 +49510,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 +49530,58 @@ 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); + } + if (exprTypes.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes, node); + if (!intrinsicType) { + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, exprTypes.value, "JSX." + JsxNames.IntrinsicElements); + return resolveUntypedCall(node); + } + else { + var fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), intrinsicType, node.tagName, node.attributes); + return fakeSignature; + } + } + var signatures = getUninstantiatedJsxSignaturesOfType(apparentType); + if (exprTypes.flags & 4 /* String */ || 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 +49591,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 +49640,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 +49684,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 +49722,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 +49738,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 +49752,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 +49789,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 +49804,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 +49848,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 +49857,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 +49895,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 +49909,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 +49973,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 +49986,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 +50010,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 +50017,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 +50080,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 +50094,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 +50113,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 +50144,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 +50240,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 +50309,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 +50331,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 +50344,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 +50352,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 +50375,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 +50413,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 +50424,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 +50468,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48622,7 +50478,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 +50494,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 +50517,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 +50589,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 +50604,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 +50613,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 +50650,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 +50704,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 +50726,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 +50741,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 +50776,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 +50795,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 +50808,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 +50817,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 +50828,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 +50886,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 +50911,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 +50928,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 +50944,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 +50977,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 +51051,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 +51081,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 +51152,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 +51183,29 @@ 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, right); + if (isAssignmentDeclaration(declKind)) { 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 +51213,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _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 +51231,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 +51246,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 +51274,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49344,7 +51284,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 +51301,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 +51383,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 +51426,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 +51448,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 +51485,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 +51496,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 +51524,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 +51550,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 +51567,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 +51581,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 +51592,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 +51719,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 +51728,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 +51739,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 +51797,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 +51817,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 +51830,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 +51866,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 +51899,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 +51916,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 +51931,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 +52003,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 +52028,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 +52048,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 +52056,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -50137,7 +52083,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 +52108,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 +52138,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 +52163,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 +52173,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 +52197,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -50268,7 +52214,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 +52245,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 +52293,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 +52302,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 +52317,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 +52332,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 +52346,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 +52364,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 +52381,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 +52474,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 +52513,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 +52524,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 +52576,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 +52586,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 +52650,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 +52676,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 +52733,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 +52764,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 +52912,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 +52935,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 +52954,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 +52992,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 +53017,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 +53085,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 +53101,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 +53170,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 +53208,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 +53223,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 +53252,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 +53261,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 +53272,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); @@ -51340,42 +53297,42 @@ 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 */: + case 241 /* 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 */: + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: if (node.body) { 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 176 /* InferType */: checkUnusedTypeParameters(node, addDiagnostic); break; default: @@ -51396,11 +53353,11 @@ var ts; 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 */) { + 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; } @@ -51409,7 +53366,7 @@ var ts; addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 155 /* Constructor */: + 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 */)) { @@ -51417,8 +53374,8 @@ var ts; } } break; - case 160 /* IndexSignature */: - case 215 /* SemicolonClassElement */: + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: // Can't be private break; default: @@ -51430,9 +53387,9 @@ var ts; 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 (node.flags & 4194304 /* Ambient */ || node.kind !== 176 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) return; - if (node.kind === 174 /* InferType */) { + if (node.kind === 176 /* 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))); @@ -51447,7 +53404,7 @@ var ts; continue; var name = ts.idText(typeParameter.name); var parent = typeParameter.parent; - if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { if (seenParentsWithEveryUnused.tryAdd(parent)) { var range = ts.isJSDocTemplateTag(parent) // Whole @template tag @@ -51533,7 +53490,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 +53508,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 +53529,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 +53541,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 +53588,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 +53602,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 +53612,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 +53627,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 +53653,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 +53668,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 +53703,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 +53715,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 +53740,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 +53751,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 +53770,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 +53785,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 +53818,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 @@ -51884,28 +53841,28 @@ var ts; 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 (parent.initializer && property) { + checkPropertyAccessibility(parent, 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 +53881,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 +53902,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 +53924,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 +53970,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 +53989,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 +53997,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 +54036,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 +54069,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 +54089,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 +54102,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 +54157,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 +54179,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 +54210,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 +54275,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 +54312,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 +54424,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 +54440,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 +54449,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 +54475,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 +54504,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 +54516,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 +54545,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 +54652,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 +54682,7 @@ var ts; case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -52890,18 +54858,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); } } @@ -52944,7 +54915,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 +54934,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 +54960,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 +54999,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 +55049,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 +55081,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 +55091,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 +55115,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 +55220,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 +55304,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 +55344,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 +55367,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 +55405,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 +55431,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 +55481,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 +55508,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 +55526,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 +55534,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 +55558,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 +55589,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 +55627,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 +55651,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 +55687,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 +55707,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 +55715,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 +55736,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 +55750,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 +55784,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 +55825,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 +55843,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 +56070,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 +56137,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 +56150,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54252,13 +56231,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 +56249,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 +56301,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 +56319,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 +56341,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 +56356,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 +56371,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 +56388,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 +56397,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 +56406,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 +56434,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 +56450,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 +56463,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 +56485,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; @@ -54531,12 +56511,12 @@ var ts; 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 +56526,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 +56542,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 +56577,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 +56600,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 +56659,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 +56713,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 +56778,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 +56799,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 +56834,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 +56854,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 +56867,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 +56887,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 +56930,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 +56949,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 +56963,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 +56976,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 +57022,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 +57050,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 +57072,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 +57085,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 +57109,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 +57143,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 +57162,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 +57170,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 +57192,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 +57207,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 +57262,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55266,12 +57292,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 +57305,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 +57324,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 +57376,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 +57391,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 +57415,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 +57462,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 +57491,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 +57526,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 +57574,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 +57598,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 +57628,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 +57641,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 +57651,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 +57663,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 +57687,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 +57744,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 +57759,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 +57774,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 +57801,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 +57844,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 +57900,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 +57965,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 +58001,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 +58031,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 +58044,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 +58060,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 +58078,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 +58103,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 +58117,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 +58134,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 +58149,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 +58202,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 +58212,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 +58221,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 +58241,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 +58281,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 +58309,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 +58335,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 +58360,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 +58389,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 +58407,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 +58419,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 +58435,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 +58464,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 +58513,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 +58530,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 +58547,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 +58575,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 +58601,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 +58642,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 +58661,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 +58669,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 +58677,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 +58698,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 +58713,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 +58740,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 +58762,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 +58832,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 +58841,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 +58868,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 +58932,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 +58954,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 +58978,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 +59059,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 +59086,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 +59142,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 +59155,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 +59171,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 +59195,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 +59208,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 +59228,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 +59243,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 +59252,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 +59269,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 +59297,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 +59317,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 +59340,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 +59361,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 +59369,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 +59377,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 +59417,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 +59431,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 +59445,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 +59453,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 +59461,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 +59473,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 +59485,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 +59497,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 +59509,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 +59521,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 +59533,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 +59541,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 +59560,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 +59578,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 +59590,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 +59608,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 +59620,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 +59635,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 +59649,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 +59667,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 +59680,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 +59692,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 +59704,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 +59723,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 +59737,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 +59751,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 +59768,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 +59782,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 +59798,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 +59814,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 +59837,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 +59851,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 +59863,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 +59887,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 +59909,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 +59921,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 +59933,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 +59945,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 +59957,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 +59970,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 +59983,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 +60000,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 +60020,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 +60034,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 +60072,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 +60084,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 +60105,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 +60123,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 +60137,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 +60149,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 +60163,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 +60177,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 +60196,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 +60211,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 +60231,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 +60247,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 +60261,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 +60275,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 +60293,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 +60309,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 +60327,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 +60339,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 +60351,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 +60363,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 +60377,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 +60391,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 +60405,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 +60417,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 +60433,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 +60454,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 +60467,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 +60493,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 +60515,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 +60537,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 +60557,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 +60576,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 +60595,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 +60607,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 +60619,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 +60631,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 +60649,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 +60667,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 +60681,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 +60693,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 +60705,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 +60719,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 +60736,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 +60754,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 +60766,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 +60781,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 +60792,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 +60858,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 +60874,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 +60890,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 +60902,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 +60918,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 +60932,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 +60944,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 +60956,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 +60970,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 +60984,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 +60996,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 +61009,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 +61024,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 +61039,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 +61053,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 +61066,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 +61087,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 +61171,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 +61183,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 +61195,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 +61210,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 +61226,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 +61249,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 +61264,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 +61306,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 +61407,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 +61918,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 +61930,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 +61958,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 +61970,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 +61983,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 +62040,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 +62055,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 +62066,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 +62078,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 +62324,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 +62352,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 +62373,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 +62407,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 +62422,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 +62459,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 +62494,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 +62510,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 +62525,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 +62560,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 +62577,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 +62602,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 +62640,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 +62651,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 +62681,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 +62709,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 +62738,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 +62759,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 +62790,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 +62798,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 +62820,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 +62885,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 +62904,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 +63007,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 +63019,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 +63055,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 +63072,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 +63084,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 +63096,7 @@ var ts; : propertyName; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -60958,7 +63111,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 +63119,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 +63165,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 +63330,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 +63641,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 +63701,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 +63714,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 +63722,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 +63773,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 +63898,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 +63906,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 +64112,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 +64162,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 +64199,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.getPositionOfLineAndCharacter(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.getPositionOfLineAndCharacter(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 +64838,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 +64884,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 +64892,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 +64928,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 +64942,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 +64962,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 +65314,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 +65381,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 +65578,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 +65609,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 +65665,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 +65686,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 +65734,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 +65758,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 +65784,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 +65818,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 +65840,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 +65857,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 +65928,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 +65939,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 +65977,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 +66042,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 +66111,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 +66313,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 +66321,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 +66369,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 +66489,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 +66560,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 +66571,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 +66588,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 +66700,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 +66858,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 +66959,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 +66981,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 +66994,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 +67005,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 +67027,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 +67072,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 +67117,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 +67229,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 +67240,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 +67273,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 +67294,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 +67302,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 +67323,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 +67412,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 +67810,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 +67891,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 +68021,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 +68067,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 +68114,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 +68308,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 +68327,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 +68335,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 +68345,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 +68414,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 +68430,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 +68456,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 +68570,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 +68598,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 +68628,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 +68849,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 +68862,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 +68906,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66391,15 +68934,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 +68967,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 +68992,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 +69028,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 +69099,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 +69117,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 +69145,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 +69167,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 +69177,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 +69261,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 +69273,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 +69282,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 +69293,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 +69325,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 +69340,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 +69357,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 +69454,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 +69551,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 +69605,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 +69625,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 +69658,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 +69683,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 +69719,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 +69832,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 +69846,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 +69922,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 +70023,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 +70329,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 +70337,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 +70389,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 +70567,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 +70592,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 +70776,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 +70794,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 +70813,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 +70950,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 +71055,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 +71094,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 +71106,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 +71164,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 +71172,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 +71243,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 +71320,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 +71372,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 +71391,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 +71437,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 +71560,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 +71642,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 +71687,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 +71725,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 +71755,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 +71776,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 +71813,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 +71850,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 +71918,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 +71987,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 +72174,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 +72205,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 +72233,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 +72247,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 +72263,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 +72342,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 +72619,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 +72690,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 +72731,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 +72852,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 +73031,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 +73068,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 +73086,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 +73133,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 +73250,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 +73348,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 +73385,7 @@ var ts; function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { enabledSubstitutions |= 2 /* BlockScopedBindings */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } /** @@ -70550,14 +73395,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 +73443,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 +73459,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 +73528,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 +73568,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 +73593,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 +73620,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 +73679,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 +73954,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 +73973,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 +74011,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 +74038,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 +74199,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 +74239,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 +74268,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 +74280,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 +74312,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 +74323,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 +74367,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 +74398,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 +74587,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 +74656,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 +75114,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 +75127,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 +75257,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 +75289,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 +75439,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 +76355,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 +76374,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 +76431,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 +76462,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 +76688,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 +76713,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 +76731,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 +76780,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 +77226,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 +77281,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 +77466,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 +77483,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 +77545,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 +77571,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 +77639,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 +77721,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 +77745,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 +77947,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 +77972,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 +78050,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 +78112,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 +78296,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 +78360,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 +78422,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 +78605,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 +78824,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 +78889,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 +78905,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 +78922,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 +78970,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -76153,12 +79004,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 +79095,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 +79131,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 +79170,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 +79199,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 +79309,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 +79338,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 +79385,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 +79394,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 +79404,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 +79429,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 +79468,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 +79495,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 +79509,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 +79534,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 +79565,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 +79578,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 +79593,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 +79635,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 +79672,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 +79702,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76869,6 +79720,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 +79730,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) { @@ -76950,15 +79802,16 @@ var ts; } } 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 +79823,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 +79860,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 +79873,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 +79910,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 +79918,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 +79939,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 +79961,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 +79974,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 +79986,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 +79999,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 +80019,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 +80035,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 +80108,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 +80128,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 +80155,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 +80260,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 +80329,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 +80347,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 +80382,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 +80392,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 +80401,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 +80417,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 +80431,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 +80455,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 +80508,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 +80519,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 +80549,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 +80558,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 +80578,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 +80600,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 242 /* ModuleDeclaration */) { + if (input.kind === 244 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -77733,7 +80621,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 +80684,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 +80705,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 +80719,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 +80757,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 +80766,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 +80876,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 +80895,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 +80903,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 +81153,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 +81195,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 +81237,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 +81257,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 +81280,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 +81353,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 +81375,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 +81390,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 +81401,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 +81445,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 +81532,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 +81575,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 +81587,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 +81600,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 +81615,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 +81640,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 +81667,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 +81693,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 +81761,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 +82049,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 +82144,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 +82187,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79988,7 +82199,8 @@ var ts; // Literals/Pseudo-literals // // SyntaxKind.NumericLiteral - function emitNumericLiteral(node) { + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { emitLiteral(node); } // SyntaxKind.StringLiteral @@ -79998,9 +82210,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 +82230,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 +82241,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -80065,7 +82277,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 +82299,7 @@ var ts; emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); @@ -80097,7 +82309,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 +82320,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitMethodDeclaration(node) { @@ -80127,7 +82339,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 +82351,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitConstructSignature(node) { @@ -80151,7 +82363,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitIndexSignature(node) { @@ -80159,10 +82371,10 @@ var ts; emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitSemicolonClassElement() { - writeSemicolon(); + writeTrailingSemicolon(); } // // Types @@ -80189,22 +82401,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 +82437,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 +82447,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 +82516,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 +82567,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 +82590,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 +82599,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 +82612,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 +82635,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 +82650,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 +82679,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 +82700,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 +82740,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,23 +82767,23 @@ 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); } @@ -80619,36 +82831,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 +82879,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 +82902,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 +82949,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 +82982,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 +83024,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 +83044,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 +83092,7 @@ var ts; } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } function emitSignatureHead(node) { @@ -80923,7 +83144,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 +83156,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 +83183,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 +83196,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 +83213,7 @@ var ts; writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); @@ -81001,7 +83222,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 +83234,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 +83250,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 +83275,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 +83308,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 +83356,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 +83382,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 +83394,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 +83409,6 @@ var ts; writePunctuation(">"); } function emitJsxText(node) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { @@ -81199,7 +83419,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 +83439,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81230,13 +83450,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 +83466,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 +83481,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); @@ -81318,6 +83538,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 +83693,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 +83751,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 +83791,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 +83826,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 131328 /* Modifiers */); + emitList(node, modifiers, 262656 /* Modifiers */); writeSpace(); } } @@ -81478,7 +83840,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 +83877,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 +83921,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 +83937,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 +83947,11 @@ var ts; writeSpace(); writePunctuation("|"); break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case 8 /* AmpersandDelimited */: writeSpace(); writePunctuation("&"); @@ -81588,11 +83962,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 +83975,7 @@ var ts; } return; } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { // TODO: GH#18217 @@ -81616,23 +83990,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 +84015,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 +84035,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 +84064,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 +84074,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 +84100,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 +84176,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 +84212,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 +84251,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 +84276,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 +84300,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 +84312,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 +84320,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 +84365,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 +84448,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 +84511,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 +84590,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82272,23 +84633,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 +84690,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 +85479,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 +85512,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 +85522,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 +85530,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 +85542,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 +85554,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 +85570,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 +85604,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 +85631,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 +85719,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 +85735,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 +85774,7 @@ var ts; } } ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { if (names.length === 0) { return []; } @@ -83047,7 +85787,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 +85797,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 +85806,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 +85831,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 +85872,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 +85905,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 +85933,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 +85953,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 +85978,33 @@ 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 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 +86018,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 +86043,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 +86093,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 +86132,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 +86161,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 +86177,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 +86230,7 @@ var ts; } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; @@ -83455,7 +86241,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 +86267,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 +86277,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 +86326,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 +86352,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 +86379,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 +86444,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 +86472,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 +86494,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 +86527,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 +86542,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 +86605,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 +86671,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 +86762,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -83982,22 +86772,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 +86795,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 +86842,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 +86903,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 +86968,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 +86995,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 +87025,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 +87075,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 +87121,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 +87177,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 +87199,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 +87265,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 +87278,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 +87312,85 @@ 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) { + 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) { + return forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (!referencedProject || + toPath(options.configFilePath) === referenceProjectPath || + !ts.contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + return referencedProject; }); - return result; + } + 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); + }); + } + 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 +87400,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 +87418,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 +87444,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 +87490,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 +87499,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 +87519,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 +87539,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 +87621,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 +87682,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 +87700,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 +87717,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 +87730,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 +87743,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 +87813,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 +87892,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 +87909,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 +87959,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 +87976,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 +88034,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 +88065,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 +88075,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 +88104,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 +88115,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 +88259,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 +88329,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 +88388,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 +88442,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 +88492,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 +88509,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 +88528,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 +88618,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 +88650,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 +88696,7 @@ var ts; */ function removeSemanticDiagnosticsOf(state, path) { if (!state.semanticDiagnosticsFromOldState) { - return false; + return true; } state.semanticDiagnosticsFromOldState.delete(path); state.semanticDiagnosticsPerFile.delete(path); @@ -85765,7 +88743,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 +88756,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 +88937,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 +88969,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 +88986,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 +89014,7 @@ var ts; resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -86086,7 +89076,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -86102,15 +89092,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 +89111,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 +89124,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 +89161,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 +89189,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 +89239,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 +89258,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 +89282,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 +89311,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 +89366,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 +89416,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 +89493,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 +89536,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 +89603,117 @@ 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 (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++; } - 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]; + return count; } 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 +89777,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 +89794,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 +89815,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 +89847,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 +89873,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 +89943,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 +90011,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 +90019,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 +90065,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 +90101,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 +90120,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 +90135,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 +90166,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 +90180,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 +90199,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 +90224,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 +90259,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 +90275,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 +90334,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 +90344,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 +90373,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 +90400,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 +90522,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 +90537,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 +90583,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 +90609,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 +90620,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 +90661,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 +90701,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 +90723,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 +90741,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 +90812,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 +90827,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 +90848,818 @@ 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); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - 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; + 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 invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); + } + /** + * 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; + // 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 }; 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); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + 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 +91695,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 +91705,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 +91862,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; } @@ -88735,6 +91918,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 +92005,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 +92090,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 +92103,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 +92150,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 +92168,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 +92208,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 +92259,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 +92275,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 +92304,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 +92341,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,12 +92349,19 @@ 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) { @@ -89143,40 +92369,40 @@ var ts; } ts.isLabelName = isLabelName; 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 +92426,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 +92444,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 +92512,7 @@ var ts; return "" /* unknown */; } } - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; default: return "" /* unknown */; @@ -89299,12 +92528,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 +92598,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 +92642,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 +92718,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 +92853,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 +92871,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 +92880,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 +92942,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 +92974,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 +93034,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 +93044,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 +93123,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 +93146,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 +93160,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 +93169,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 +93179,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 +93194,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 +93213,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 +93237,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 +93245,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 +93257,21 @@ 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 */, + 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 +93307,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 +93383,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 +93449,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 +93472,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 +93498,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 +93507,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 +93658,6 @@ var ts; return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; - /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -90450,7 +93692,7 @@ var ts; ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { return !!location.parent && - (location.parent.kind === 251 /* ImportSpecifier */ || location.parent.kind === 255 /* ExportSpecifier */) && + (location.parent.kind === 253 /* ImportSpecifier */ || location.parent.kind === 257 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -90497,6 +93739,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 +93763,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 +93771,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 +93812,6 @@ var ts; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ - /* @internal */ function suppressLeadingAndTrailingTrivia(node) { suppressLeadingTrivia(node); suppressTrailingTrivia(node); @@ -90572,7 +93820,6 @@ var ts; /** * Sets EmitFlags to suppress leading trivia on the node. */ - /* @internal */ function suppressLeadingTrivia(node) { addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); } @@ -90580,7 +93827,6 @@ var ts; /** * Sets EmitFlags to suppress trailing trivia on the node. */ - /* @internal */ function suppressTrailingTrivia(node) { addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); } @@ -90594,7 +93840,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 +93853,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 +93906,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 +94010,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 +94052,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 +94119,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 +94141,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 +94181,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 +94238,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 +94265,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 +94301,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 +94345,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 +94363,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 +94382,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 +94407,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 +94485,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 +94619,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 +94705,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 +94721,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 +94753,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 +94763,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 +94784,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 +94799,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 +94864,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) { @@ -91599,21 +95125,22 @@ var ts; // 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); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, 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); + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, 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, 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 +95161,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 +95242,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 +95265,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 +95277,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 +95298,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 +95326,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 +95374,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 +95430,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 +95505,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 +95549,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 +95565,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 +95596,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 +95609,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 +95621,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 +95629,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 +95657,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 +95674,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 +95689,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 +95730,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 +95767,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 +95798,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 +95836,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 +95880,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 +95915,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 +95929,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 +95966,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 +96017,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 +96068,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 +96095,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 +96166,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 +96175,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 +96192,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 +96236,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 +96265,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 +96313,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 +96365,10 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 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,21 +96393,21 @@ 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); @@ -93054,7 +96417,7 @@ var ts; 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 */; + 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 @@ -93075,46 +96438,40 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } 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 +96486,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 +96562,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 +96580,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 +96641,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 +96661,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 +96702,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 +96731,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 +96766,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 +96795,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 +96826,17 @@ 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 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 */)) { return parent; } - else if (parent.kind === 265 /* JsxAttribute */) { + else if (parent.kind === 267 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93474,8 +96847,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 +96856,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 +96867,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 +96886,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 +96965,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 +96990,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 +97013,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 +97028,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 +97053,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 +97096,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 +97140,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 +97155,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 +97175,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 +97204,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 +97227,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 +97259,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 +97268,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 +97284,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 +97336,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 +97412,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 +97444,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 +97469,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 +97481,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 +97517,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 +97530,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 +97539,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 +97553,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 +97567,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 +97584,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 +97602,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 +97618,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 +97639,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 +97658,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 +97693,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 +97729,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 +97764,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 +97780,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 +97818,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 +97846,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 +97912,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 +97926,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 +97951,7 @@ var ts; directImports.push(direct); } break; - case 181 /* ImportType */: + case 183 /* ImportType */: directImports.push(direct); break; default: @@ -94626,7 +97968,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 +98023,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 +98045,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 +98108,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 +98137,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 +98185,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 +98200,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 +98232,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) @@ -94943,7 +98285,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95012,10 +98354,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,15 +98366,15 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent) ? { isNamedImport: false } : undefined; - case 251 /* ImportSpecifier */: + 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 */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return { isNamedImport: false }; default: @@ -95065,21 +98407,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 +98430,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 +98473,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 +98495,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); }); } - 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 +98511,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 +98546,65 @@ 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) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode)); + } + 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) { + 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)) { + if (kind === 3 /* SearchedLocalFoundProperty */) { + return { prefixText: name + ": " }; + } + else if (kind === 4 /* SearchedPropertyFoundLocal */) { + return { suffixText: ": " + name }; + } + else { + return isShorthandAssignment + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + ? { suffixText: ": " + name } + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : { prefixText: 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 +98619,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 +98636,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 +98654,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 +98662,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 +98750,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 +98784,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 +98797,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 +98810,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,7 +98847,7 @@ 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; @@ -95389,12 +98859,12 @@ var ts; 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 */) { + 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 +98884,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 */; @@ -95525,15 +98995,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. */ @@ -95636,19 +99106,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 +99118,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 +99128,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 +99157,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 +99178,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 +99260,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 +99287,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 +99338,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; } @@ -95934,7 +99393,7 @@ 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 exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); if (!exportInfo) return ts.Debug.fail(); @@ -95998,12 +99457,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 +99473,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 +99499,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 +99516,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 +99542,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 +99559,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 +99582,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 +99610,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 +99669,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 +99684,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 +99693,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 +99735,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 +99761,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 +99791,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 +99823,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 +99837,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 +99938,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 +99953,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 +99972,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 +99990,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 +100042,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 +100070,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 +100100,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 +100130,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 +100172,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 +100184,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 +100192,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 +100345,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 +100366,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 +100438,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 +100560,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 +100585,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 +100658,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97206,7 +100691,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97269,7 +100754,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 +100771,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 +100781,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 +100805,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 +100831,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 +100900,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 +100912,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 +100929,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 +101098,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 +101110,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 +101136,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 +101147,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 +101169,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 +101184,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 +101194,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 +101217,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 +101287,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 +101308,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 +101338,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 +101346,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 +101365,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 +101382,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 +101412,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 +101440,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 +101452,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 +101509,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 +101523,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 +101711,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 +101810,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 +101913,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 +102020,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 +102052,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 +102082,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 +102091,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 +102452,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 +102596,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 +102629,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 +102646,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 +102690,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 +102709,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 +102733,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 +102755,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 +102782,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 +102797,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 +102815,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 +102931,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 +102994,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 +103031,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 +103065,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 +103089,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 +103118,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 +103141,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 +103194,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 +103260,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 +103309,7 @@ var ts; if (child === node) { break; } - if (child.kind !== 26 /* CommaToken */) { + if (child.kind !== 27 /* CommaToken */) { argumentIndex++; } } @@ -99791,8 +103328,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 +103398,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 +103406,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 +103416,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 +103432,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* 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 +103449,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 +103495,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 +103505,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 +103524,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 +103599,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 +103626,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 +103672,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 +103700,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 +103710,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 +103743,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 +103764,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 +103847,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 +103884,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 +103935,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 +103964,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 +103982,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 +104003,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 +104021,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 +104038,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 +104058,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 +104090,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 +104098,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 +104106,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 +104155,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 +104163,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 +104189,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 +104219,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 +104267,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 +104278,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 +104316,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 +104341,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 +104362,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 +104372,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 +104395,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 +104406,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 +104432,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 +104481,7 @@ var ts; options.paths = undefined; options.rootDirs = undefined; options.declaration = undefined; + options.composite = undefined; options.declarationDir = undefined; options.out = undefined; options.outFile = undefined; @@ -101062,8 +104656,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 +104739,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 +104751,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 +104842,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 +104858,7 @@ var ts; } break; case 3 /* RescanTemplateToken */: - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { lastScanAction = 3 /* RescanTemplateToken */; return scanner.reScanTemplateToken(); } @@ -101337,7 +104931,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 +104943,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 +105235,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 +105285,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 +105326,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 +105359,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 +105401,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 +105473,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 +105522,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 +105582,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 +105676,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 +105707,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 +105765,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 +105888,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 +105917,7 @@ var ts; var previousParent; var previousRangeStartLine; var lastIndentedLine; - var indentationOnLastIndentedLine; + var indentationOnLastIndentedLine = -1 /* Unknown */; var edits = []; formattingScanner.advance(); if (formattingScanner.isOnToken()) { @@ -102338,7 +105931,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 +105976,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 +105997,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 +106024,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 +106056,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 +106159,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 +106195,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 +106224,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 +106270,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 +106288,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 +106492,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 +106595,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 +106739,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 +106761,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 +106799,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 +106832,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 +106893,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 +106910,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 +106941,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 +106950,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 +107039,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 +107088,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 +107175,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 +107307,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 = ""; @@ -103773,13 +107379,16 @@ var ts; if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } return 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); }; 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); @@ -103787,11 +107396,11 @@ var ts; }; 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 +107415,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 +107438,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 +107472,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 +107519,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 +107572,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 +107584,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 +107604,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: " " }); } }; @@ -104058,7 +107697,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 +107713,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 +107729,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 +107737,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 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 +107811,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 +107846,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 +107895,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 +107980,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 +107995,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 +108019,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 +108060,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 +108094,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 +108117,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 +108158,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 +108173,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; default: @@ -104519,7 +108184,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 +108198,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 +108220,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 +108237,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 +108389,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) { @@ -104791,9 +108482,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 +108494,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 +108509,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 +108550,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 +108590,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 +108601,754 @@ 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 isConstructor = declaration.kind === 157 /* Constructor */; + var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; + return callContexts && 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)) { + types.push.apply(types, inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken)); + } + 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.isNumber = true; + usageContext.isString = 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.isNumber = true; + usageContext.isString = 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.isNumber = true; + usageContext.isString = 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 unifyFromContext(inferences, checker, fallback) { + if (fallback === void 0) { fallback = checker.getAnyType(); } + if (!inferences.length) + return fallback; + var hasNonVacuousType = inferences.some(function (i) { return !(i.flags & (1 /* Any */ | 16384 /* Void */)); }); + var hasNonVacuousNonAnonymousType = inferences.some(function (i) { return !(i.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(i) & 16 /* Anonymous */); }); + var anons = inferences.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; }); + var good = []; + if (!hasNonVacuousNonAnonymousType && anons.length) { + good.push(unifyAnonymousTypes(anons, checker)); + } + good.push.apply(good, inferences.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */) && !(hasNonVacuousType && i.flags & (1 /* Any */ | 16384 /* Void */)); })); + 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()); + } + 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) { + return [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 +109373,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 +109410,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 +109433,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 +109441,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 +109469,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 +109482,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 +109503,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 +109522,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 +109633,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 +109647,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 +109661,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 +109687,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 +109710,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 +109720,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 +109754,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 +109770,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 +109797,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 +109813,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 +109826,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 +109974,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 +109981,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 +110041,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 +110070,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 +110090,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 +110152,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 +110161,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 +110187,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 +110204,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 +110262,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 +110286,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 +110307,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 +110318,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 +110329,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 +110401,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 +110673,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 +110744,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 +110767,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 +110792,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 +110826,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 +110874,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 +110890,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 +110913,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 +111122,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 +111156,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 +111182,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 +111201,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 +111301,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 +111311,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 +111344,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 +111363,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 +111387,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 +111407,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 +111423,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 +111435,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, @@ -106922,24 +111447,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 +111672,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 +111711,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 +111749,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 +111843,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 +111863,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 +111895,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 +111904,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 +111914,7 @@ var ts; break; } case fixIdInfer: - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { changeInferToUnknown(changes, sourceFile, token); } break; @@ -107290,7 +111925,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 +111935,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 +111952,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 +111961,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 +111970,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 +111991,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 +112009,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 +112083,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 +112094,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 +112144,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 +112168,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 +112188,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 +112205,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 +112274,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 +112296,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 +112319,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 +112390,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 +112440,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 +112484,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 +112513,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 +112528,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 +112537,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 +112548,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 +112580,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 +112691,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 +112699,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 +112720,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 +112745,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 +113069,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 +113122,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 +113142,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 +113169,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 +113201,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 +113219,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 +113248,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 +113268,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 +113289,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 +113338,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 +113362,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 +113470,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 +113531,7 @@ var ts; actions: constantActions }); } - return infos.length ? infos : undefined; + return infos.length ? infos : ts.emptyArray; } extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ @@ -109395,20 +113705,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 +113761,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 +113773,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 +113794,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 +113807,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 +113832,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 +113844,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 +113855,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 +113922,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 +113933,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 +114023,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 +114067,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 +114114,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 +114144,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 +114268,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 +114283,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 +114293,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 +114326,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 +114345,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 +114432,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 +114602,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 +114610,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 +114926,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 +114970,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 +114987,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 +114998,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); @@ -110729,7 +115039,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,7 +115062,7 @@ var ts; isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasReadonlyModifier(declaration), type: ts.getTypeAnnotationNode(declaration), - container: declaration.kind === 149 /* Parameter */ ? declaration.parent.parent : declaration.parent, + container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent, originalName: declaration.name, declaration: declaration, fieldName: fieldName, @@ -110809,7 +115119,7 @@ var ts; 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; + return (entry.kind !== 0 /* Span */ && 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; @@ -110834,7 +115144,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 +115206,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 +115298,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 +115334,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 +115417,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 +115438,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 +115450,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 +115463,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 +115575,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 +115593,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 +115603,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 +115614,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 +115624,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 +115685,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 +115699,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 +115766,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 +115795,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 +115814,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 +115836,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 +115878,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 +115914,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 +115987,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 +115999,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 +116045,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 +116057,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 +116189,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 +116235,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 +116390,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 +116413,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 +116448,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 +116472,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 +116481,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 +116794,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 +116824,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 +116863,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 +116875,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 +116888,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 +116913,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 +117003,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 +117070,15 @@ var ts; } function shouldGetType(sourceFile, node, position) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return !ts.isLabelName(node); - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: + 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 +117116,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 +117124,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 +117185,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 +117210,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 +117272,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 +117351,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 +117415,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: "" }; @@ -113331,7 +117674,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 +117689,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 +117739,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 +117819,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 +117968,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 +117984,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 +118021,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 +118043,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 +118073,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 +118085,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 +118126,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 +118149,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 +118193,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 +118215,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 +118234,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 +118260,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 +118276,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 +118291,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 +118305,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 +118329,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 +118350,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 +118448,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 +118458,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); }); }; } } @@ -114826,6 +119169,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 +119198,6 @@ var ts; : undefined; } server.findArgument = findArgument; - /*@internal*/ function nowString() { // E.g. "12:34:56.789" var d = new Date(); @@ -114868,13 +119211,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 +119254,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 +119286,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 +119371,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 +119500,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 +119519,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 +119581,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 +119699,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 +119806,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) { @@ -115699,7 +119947,7 @@ var ts; 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); @@ -115904,7 +120152,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 +120231,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 +120291,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 +120316,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, @@ -116159,6 +120411,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 +120472,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 +120495,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 +120555,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 +120686,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 +120717,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 +120775,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; }); @@ -116633,38 +120888,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 +120903,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 +120946,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 +120972,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) { @@ -116797,6 +121022,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 +121042,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 +121092,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 +121106,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 +121115,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 +121125,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 +121161,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 +121220,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 +121282,36 @@ 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.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 +121320,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 +121344,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 +121404,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 +121425,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 +121456,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 +121546,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 +121593,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 +121611,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 +121640,10 @@ var ts; this.projectToSizeMap = ts.createMap(); this.configFileExistenceInfoCache = ts.createMap(); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist = ts.createMap(); this.pendingProjectUpdates = ts.createMap(); this.seenProjects = ts.createMap(); + this.seenSurveyProjects = ts.createMap(); this.host = opts.host; this.logger = opts.logger; this.cancellationToken = opts.cancellationToken; @@ -117360,7 +121656,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 +121677,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 +121736,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 +121803,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 +121819,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 +121888,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 +121912,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 +121950,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 +121977,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 +122004,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 +122017,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 +122311,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 +122334,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 +122345,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 +122361,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,21 +122373,35 @@ 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), + projectId: this.host.createSHA256Hash(project.projectName), fileStats: server.countEachFileTypes(project.getScriptInfos()), compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), @@ -118110,8 +122420,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 +122431,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 +122548,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 +122634,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 +122657,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 +122703,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 +122783,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 +122805,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 +122817,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 +122841,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 +122859,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 +122883,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 +122903,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 +122950,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 +122960,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 +123001,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 +123048,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 +123160,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 +123255,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 +123325,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 +123366,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 +123377,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 +123390,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 +123403,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 +123584,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 +123602,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 +123615,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 +123629,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 +123673,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 +123699,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 +123709,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 +123725,7 @@ var ts; } }); } - return true; + return originalLocation; }); return toDo; } @@ -119287,10 +123735,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 +124044,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 +124084,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 +124099,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 +124152,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 +124166,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 +124203,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 +124401,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 +124473,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 +124606,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 +124635,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 +124669,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 +124878,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 +124891,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 +125103,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); } @@ -120708,8 +125221,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 +125256,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 +125329,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 +125389,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 +125415,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 +125437,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 }; } @@ -121840,13 +126361,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 +126471,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 +126601,7 @@ var ts; globalPlugins: globalPlugins, pluginProbeLocations: pluginProbeLocations, allowLocalPluginLoads: allowLocalPluginLoads, + typesMapLocation: typesMapLocation, }) || this; _this.eventPort = eventPort; if (_this.canUseEvents && _this.eventPort) { @@ -122190,13 +126721,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 +126948,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 +126976,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..ac36533a094 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.2"; /** 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[]; @@ -2056,32 +2057,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 +2156,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 +2207,7 @@ declare namespace ts { aliasTypeArguments?: ReadonlyArray; } interface LiteralType extends Type { - value: string | number; + value: string | number | PseudoBigInt; freshType: LiteralType; regularType: LiteralType; } @@ -2216,6 +2220,9 @@ declare namespace ts { interface NumberLiteralType extends LiteralType { value: number; } + interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } interface EnumType extends Type { } enum ObjectFlags { @@ -2234,6 +2241,7 @@ declare namespace ts { JsxAttributes = 4096, MarkerType = 8192, JSLiteral = 16384, + FreshLiteral = 32768, ClassOrInterface = 3 } interface ObjectType extends Type { @@ -2490,6 +2498,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2581,7 +2590,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2600,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 +2673,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 +2693,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 +2752,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 +2946,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; @@ -3117,7 +3134,7 @@ declare namespace ts { /** 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; @@ -3592,7 +3620,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 +3635,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 +3650,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 +4163,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 +4200,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 +4333,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 +4399,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 +4411,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4447,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 +4458,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 +4666,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 +4676,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 +4698,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 +4706,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 +4737,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 */ @@ -5046,9 +4901,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 +4976,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5191,24 +5055,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 +5131,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 +5266,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 +5380,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 +5438,8 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24 + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 } } declare namespace ts { @@ -5648,6 +5531,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 +5624,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 +5637,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 +5704,8 @@ declare namespace ts.server.protocol { GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", OrganizeImports = "organizeImports", - GetEditsForFileRename = "getEditsForFileRename" + GetEditsForFileRename = "getEditsForFileRename", + ConfigurePlugin = "configurePlugin" } /** * A TypeScript Server message @@ -5911,6 +5780,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 +6429,7 @@ declare namespace ts.server.protocol { /** * The file locations referencing the symbol. */ - refs: ReferencesResponseItem[]; + refs: ReadonlyArray; /** * The name of the symbol. */ @@ -6602,15 +6475,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 +6502,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 +6519,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 +6658,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 +7044,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 +7503,7 @@ declare namespace ts.server.protocol { */ interface DiagnosticEvent extends Event { body?: DiagnosticEventBody; + event: DiagnosticEventKind; } interface ConfigFileDiagnosticEventBody { /** @@ -7660,6 +7557,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 +7921,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 +8053,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 +8113,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 +8170,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 +8182,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 +8194,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 +8256,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 +8285,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 +8324,7 @@ declare namespace ts.server { compileOnSaveEnabled: boolean; excludedFiles: ReadonlyArray; private typeAcquisition; + updateGraph(): boolean; getExcludedFiles(): ReadonlyArray; getTypeAcquisition(): TypeAcquisition; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; @@ -8399,6 +8333,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 +8347,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: { @@ -8488,7 +8444,7 @@ declare namespace ts.server { 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 +8465,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 +8494,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 +8543,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 +8560,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 +8588,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 +8652,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 +8666,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 +8736,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 +8778,7 @@ declare namespace ts.server { globalPlugins?: ReadonlyArray; pluginProbeLocations?: ReadonlyArray; allowLocalPluginLoads?: boolean; + typesMapLocation?: string; } class Session implements EventSender { private readonly gcTimer; @@ -8837,6 +8801,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 +8846,7 @@ declare namespace ts.server { private getProjects; private getDefaultProject; private getRenameLocations; - private static mapRenameInfo; + private mapRenameInfo; private toSpanGroups; private getReferences; /** @@ -8944,6 +8909,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..0767cfedaad 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.2"; /** 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) { @@ -2615,6 +3066,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2665,6 +3117,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 +3150,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 +3189,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 +3295,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 +3313,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 +3343,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 +3412,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 +3424,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 +3456,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 +3476,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 +3737,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 +3770,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 +3867,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 +3882,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 +4034,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 +4251,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 +4586,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 +5202,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 +5241,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."), @@ -4837,14 +5302,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'."), @@ -5024,7 +5489,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 +5516,14 @@ 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."), 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 +5615,14 @@ 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}'."), 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 +5736,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 +5832,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 +5930,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 +5972,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 +5982,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 +6010,14 @@ 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."), 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 +6048,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."), @@ -5673,150 +6177,105 @@ 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"), }; })(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 :: @@ -6394,6 +6853,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6404,8 +6864,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 +6883,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6498,18 +6959,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 +6996,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 +7028,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 +7097,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 +7105,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 +7205,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 +7288,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 +7321,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 +7398,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 +7429,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 +7560,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 +7617,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 +7637,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 +7663,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 +7683,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 +7713,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 +7766,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 +7833,7 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 12 /* RegularExpressionLiteral */; + token = 13 /* RegularExpressionLiteral */; } return token; } @@ -7336,7 +7841,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 +7858,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 +7897,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 +7923,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 +7947,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,6 +8060,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7575,7 +8083,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7622,7 +8129,6 @@ var ts; getText: function () { return str; }, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -7631,7 +8137,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 +8165,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 +8272,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 +8338,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 +8346,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 +8484,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 +8502,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 +8542,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 +8595,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 +8627,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 +8648,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 +8666,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 +8691,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 +8703,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 +8731,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 +8741,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 +8779,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 +8794,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 +8843,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 +8857,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 +8866,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 +8920,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 +8933,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 +8945,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 +8974,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 +9024,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 +9082,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 +9108,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 +9150,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 +9163,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 +9176,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 +9195,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 +9207,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 +9224,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 +9232,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 +9255,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 +9292,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 +9314,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 +9327,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 +9356,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 +9380,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 +9416,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 +9434,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 +9443,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 +9464,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 +9476,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 +9510,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 +9522,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 +9532,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 +9592,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 +9642,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 +9651,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 +9679,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 +9705,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 +9735,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 +9792,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 +9840,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 +9855,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 +9884,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 +9922,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 +9953,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 +9962,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 +9976,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 +9985,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 +10002,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 +10016,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 +10028,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 +10048,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 +10064,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 +10094,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 +10109,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 +10124,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 +10139,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 +10162,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 +10197,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 +10210,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 +10261,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 +10293,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 +10337,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 +10377,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 +10417,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 +10435,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 +10446,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 +10463,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 +10497,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 +10513,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 +10536,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 +10557,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 +10585,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 +10601,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 +10622,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 +10633,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 +10652,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 +10661,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 +10673,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 +10700,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 +10740,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 +10758,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 +10935,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 +10993,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 +11076,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 +11102,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 +11235,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 +11249,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 +11308,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 +11323,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 +11346,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 +11370,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 +11386,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 +11395,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 +11429,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 +11447,7 @@ var ts; } } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -10930,7 +11565,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 +11574,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 +11635,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 +11643,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 +11693,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 +11703,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 +11716,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 +11738,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 +11880,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 +11992,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 +12091,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 +12169,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 +12300,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) { @@ -11756,13 +12435,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 +12571,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 +12581,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 +12611,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 +12762,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 +12808,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 +12871,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 +12899,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 +13039,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 +13073,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 +13765,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 +13775,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 146 /* FirstNode */; + return kind >= 148 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -13078,7 +13784,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 +13796,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 +13806,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 +13815,12 @@ 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 isStringTextContainingNode(node) { - return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; // Identifiers @@ -13127,17 +13833,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 +13856,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 +13865,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 +13896,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 +13911,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 +13933,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 +13965,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,37 +13978,38 @@ 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 */; + 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 */; } /** * Node test that determines whether a node is a valid type node. @@ -13315,8 +14022,8 @@ var ts; 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 +14034,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 +14043,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 +14060,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 +14083,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 +14096,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 +14106,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 +14133,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 +14149,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 +14189,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 +14204,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 +14225,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 +14241,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 +14263,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 +14277,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 +14301,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 +14434,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 +14447,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 +14551,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 +14585,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 +14637,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 +14668,6 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; - /* @internal */ function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -13987,7 +14692,6 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; - /* @internal */ function createCompilerDiagnosticFromMessageChain(chain) { return { file: undefined, @@ -14024,14 +14728,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 +14794,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 +14822,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 +14835,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 +15037,6 @@ var ts; return rootLength > 0 && rootLength === path.length; } ts.isDiskPathRoot = isDiskPathRoot; - /* @internal */ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath @@ -14401,8 +15114,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 +15335,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 +15402,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 +15629,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 +15807,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 +15985,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 +16096,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 +16148,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 +16178,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,357 +16186,358 @@ 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 */: + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -15712,17 +16546,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 298 /* JSDocReturnTag */: + case 300 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 281 /* JSDocTypeExpression */) { + node.typeExpression.kind === 283 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -15730,20 +16564,20 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 295 /* JSDocCallbackTag */: + case 297 /* JSDocCallbackTag */: return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 299 /* JSDocThisTag */: + case 301 /* JSDocThisTag */: return visitNode(cbNode, node.typeExpression); - case 296 /* JSDocEnumTag */: + case 298 /* JSDocEnumTag */: return visitNode(cbNode, node.typeExpression); - case 291 /* JSDocSignature */: + case 293 /* JSDocSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 290 /* JSDocTypeLiteral */: + case 292 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -15751,7 +16585,7 @@ var ts; } } return; - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -15761,7 +16595,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 +16764,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 +16803,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 +16822,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 +16959,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 +17164,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 +17220,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 +17284,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 +17305,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 +17316,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 +17326,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 +17347,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 +17368,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 +17392,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 +17421,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 +17431,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 +17468,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 +17509,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 +17526,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 +17555,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 +17605,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 +17775,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 +17797,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 +17807,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 +17879,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 +17936,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 +17946,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 +18003,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 +18015,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 +18046,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 +18082,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 +18114,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 +18139,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 +18160,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 +18178,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 +18256,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 +18303,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 +18325,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 +18355,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 +18368,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 +18381,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 +18409,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 +18428,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 +18472,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 +18482,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 +18493,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 +18518,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 +18550,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 +18645,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 +18728,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 +18775,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 +18820,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 +18837,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 +18860,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 +18890,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -18044,17 +18898,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 +18920,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 +18931,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 +18942,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 +18996,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 +19025,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 +19042,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 +19051,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 +19096,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 +19112,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 +19141,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 +19160,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 +19198,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 +19209,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 +19222,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 +19255,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 +19298,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 +19308,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 +19337,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 +19350,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 +19376,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 +19387,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 +19424,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 +19445,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 +19474,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 +19504,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 +19558,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 +19582,7 @@ var ts; */ if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); - return token() === 40 /* AsteriskAsteriskToken */ ? + return token() === 41 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } @@ -18744,10 +19599,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 +19627,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 +19666,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 +19698,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 +19753,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 +19768,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 +19779,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 +19838,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 +19862,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 +19881,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 +19897,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 +19914,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 +19943,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 +19960,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 +19990,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 +20001,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 +20038,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 +20112,7 @@ var ts; } indexedAccess.argumentExpression = argument; } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } @@ -19269,13 +20124,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 +20138,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 +20151,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 +20169,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 +20191,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 +20230,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 +20254,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 +20331,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 +20367,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 +20378,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 +20390,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 +20409,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 +20452,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 +20505,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 +20539,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 +20547,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 +20556,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 +20603,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 +20638,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 +20649,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 +20667,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 +20708,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 +20755,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 +20808,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 +20817,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 +20886,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 +20905,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 +20940,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 +20951,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 +20962,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 +20988,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 +21017,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 +21030,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 +21053,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 +21065,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 +21122,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 +21135,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 +21158,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 +21168,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 +21203,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 +21226,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 +21245,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 +21255,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 +21278,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 +21326,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 +21338,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 +21372,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 +21386,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 +21405,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 +21416,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 +21438,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 +21448,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 +21521,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 +21530,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 +21541,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 +21564,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 +21579,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 +21600,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 +21611,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 +21636,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 +21656,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 +21672,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 +21723,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 +21815,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 +21835,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 +21848,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 +21862,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 +21886,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 +21920,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 +22003,7 @@ var ts; } indent = 0; break; - case 57 /* AtToken */: + case 58 /* AtToken */: scanner.setTextPos(scanner.getTextPos() - 1); // falls through case 1 /* EndOfFileToken */: @@ -21171,9 +22022,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 +22032,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 +22052,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 +22072,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 +22112,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 +22128,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 +22151,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 +22230,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 +22247,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 +22265,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 +22279,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 +22329,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 +22353,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 +22367,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 +22392,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 +22429,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 +22446,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 +22576,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 +23156,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 +23216,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 +23233,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +23247,49 @@ 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 + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22455,26 +23331,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 +23351,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 +23371,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 +23384,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 +23392,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 +23410,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 +23520,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23529,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,14 +23538,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 +23564,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23573,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23607,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23620,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 +23628,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 +23638,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 +23654,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 +23666,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 +23677,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 @@ -22874,30 +23762,12 @@ var ts; 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 +23826,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 +23846,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 +23892,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 +23900,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 +23928,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 +23956,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 +24047,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 +24097,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 +24117,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 +24125,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 +24161,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +24204,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 +24229,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 +24384,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 +24526,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 +24574,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 +24608,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 +24631,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 +24671,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 +24790,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 +24938,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 +24956,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 +25007,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 +25026,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24014,17 +25039,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 +25151,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 +25178,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 +25209,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 +25423,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 +25448,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 +25466,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 +25492,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 +25503,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 +25645,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 +25701,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 +25716,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 +25733,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 +25865,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 +25890,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 +25902,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 +25916,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 +25939,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 +25986,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 +26008,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 +26132,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 +26166,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 +26178,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 +26253,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 +26312,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 +26331,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 +26342,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 +26421,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 +26438,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 +26469,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 +26515,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 +26564,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 +26588,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 +26626,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 +26638,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 +26715,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 +26724,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 +26854,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 +26867,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 +26944,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 +26975,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 +27014,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 +27161,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 +27186,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 +27198,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 +27296,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 +27325,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 +27352,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 +27375,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 +27419,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 +27451,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 +27464,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 +27513,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 +27543,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 +27629,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 +27663,7 @@ var ts; } } } - if (expr.expression.kind === 187 /* PropertyAccessExpression */ && + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } @@ -26452,32 +27677,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 +27737,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 +27776,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 +27844,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 +27878,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 +27906,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 +27926,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 +28022,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 +28046,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 +28089,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 +28107,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 +28118,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 +28135,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 +28146,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 +28156,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 +28183,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 +28194,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -27017,10 +28241,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 +28252,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 +28261,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 +28341,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 +28400,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 +28432,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 +28441,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 +28461,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 +28488,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 +28500,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 +28532,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 +28549,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 +28566,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 +28584,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 +28621,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 +28632,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 +28673,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 +28700,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 +28769,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 +28793,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 +28831,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 +28840,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 +28889,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 +29069,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 +29124,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 +29148,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 +29175,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 +29198,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 +29218,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 +29235,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 +29256,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 +29290,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 +29340,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 (ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } var init = !node ? undefined : ts.isVariableDeclaration(node) ? node.initializer : ts.isBinaryExpression(node) ? node.right : @@ -28090,7 +29356,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 +29398,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 +29440,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 +29456,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 +29476,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 +29494,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 +29535,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 +29569,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 +29611,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 +29648,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 +29662,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 +29726,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 +29791,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 +29819,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 +29844,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 +29890,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 +29901,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 +29913,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 +29923,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 +29943,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 +29954,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 +29968,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 +29980,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 +29995,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 +30008,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 +30027,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 +30043,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 +30059,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 +30076,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 +30105,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 +30126,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 +30137,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 +30161,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 +30172,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 +30181,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 +30262,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 +30333,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 +30432,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 +30554,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 +30570,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 +30668,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 +30711,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 +30743,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 +30753,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"); @@ -29642,10 +30934,6 @@ var ts; 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); @@ -29670,14 +30958,15 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, 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 +30974,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 +31028,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29762,24 +31052,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 +31101,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 +31124,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29833,6 +31144,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29844,7 +31156,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 +31166,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 +31192,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 +31305,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 +31442,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 +31503,10 @@ 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); + target = cloneSymbol(resolveSymbol(target)); } // 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 +31516,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 +31537,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 +31602,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 +31665,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 +31695,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 +31723,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 +31752,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 +31765,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 +31788,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 +31839,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 +31881,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 +31912,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 +31926,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 +31942,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 +31970,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 +31978,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 +31998,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 +32033,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 +32042,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 +32055,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; @@ -30729,8 +32075,8 @@ var ts; } 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 +32085,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 +32140,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 +32157,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 +32174,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 +32229,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 +32242,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 +32263,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 +32299,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 +32316,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 +32334,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 +32350,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 +32388,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 +32442,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 +32498,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 +32532,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 +32542,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 +32566,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 +32600,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 +32616,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 +32638,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 +32662,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 +32682,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 +32717,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 +32733,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,6 +32755,16 @@ var ts; return symbol && symbol.valueDeclaration; } } + 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) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31421,7 +32794,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.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32813,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 +32845,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 +32853,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 +32865,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 +32907,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 +32975,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 */) : @@ -31737,13 +33114,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 +33143,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 +33198,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 +33214,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 +33264,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 +33303,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 +33318,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 +33332,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 +33374,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 +33438,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 +33488,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); @@ -32135,6 +33525,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32151,15 +33544,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 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; } } @@ -32217,9 +33610,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 & 67108864 /* 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 +33642,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 +33741,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 +33761,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 +33788,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 +33815,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 +33839,60 @@ 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 */); + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } } else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.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) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + 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 +33906,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 +33927,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 +33959,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 +33999,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 +34012,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,11 +34064,11 @@ 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 */ ? @@ -32684,26 +34110,21 @@ var ts; 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) { @@ -32716,9 +34137,9 @@ 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 */); + var 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 +34190,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 +34203,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 +34214,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 +34233,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 +34255,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 +34267,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 +34278,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 +34296,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 & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32966,7 +34400,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 +34430,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,7 +34445,7 @@ 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; @@ -33103,6 +34544,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,12 +34600,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 +34615,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 +34632,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 +34641,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 +34668,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 +34708,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 +34736,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 +34791,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 +34816,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 +34865,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 +34875,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 +34890,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 +34925,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 +34978,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 +35001,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 +35011,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 +35039,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 +35055,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 +35069,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 +35091,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 +35106,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 +35122,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 +35157,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 +35174,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 +35189,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 +35201,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 +35237,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 +35251,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 +35303,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33862,9 +35312,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 +35326,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 +35335,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 +35349,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 +35389,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 +35412,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 +35434,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 +35442,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 +35487,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 +35520,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 +35542,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 +35560,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 +35587,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 +35617,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 +35631,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 +35639,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 +35671,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 +35682,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 +35711,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 +35720,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 +35784,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 +35808,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 +35844,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 +35853,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 +35882,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 +35925,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 +35935,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 +35975,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 +35994,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 @@ -34577,14 +36042,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); @@ -34620,7 +36085,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 +36094,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 +36126,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 +36143,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 +36167,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 +36181,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 +36203,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 +36218,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 +36230,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 +36265,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 +36309,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 +36351,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 +36367,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 +36416,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 +36459,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 +36482,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 +36627,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 +36736,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 +36756,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 +36790,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 +36836,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 +36872,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 +36895,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 +36933,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 +36949,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 +36967,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 +36977,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 +36996,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 +37011,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 +37025,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 +37037,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 +37060,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 +37073,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 +37090,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 +37118,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 +37135,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 +37146,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 +37155,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 +37179,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 +37189,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 +37203,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 +37222,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 +37260,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 +37280,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 +37308,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 +37318,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 +37340,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 +37348,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 +37371,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 +37456,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 +37516,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 +37604,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 +37642,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 +37696,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 +37735,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 +37760,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 +37798,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 +37811,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 +37821,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 +37835,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 +37879,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 +37902,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 +37966,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 +37983,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 +37993,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 +38007,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 +38033,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 +38043,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 +38063,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 +38109,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 +38126,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 +38140,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 +38167,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 +38175,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 +38206,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 +38230,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 +38303,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 +38336,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 +38363,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 +38391,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 +38420,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 +38429,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 +38466,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 +38481,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 +38494,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 +38552,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 +38595,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 +38606,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 +38617,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 +38648,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 +38677,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 +38740,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 +38762,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 +38797,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 +38807,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 +38845,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 +38863,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 +38882,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 +38897,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 +38910,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 +38939,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 +38966,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 +39023,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 +39033,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 +39059,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 +39074,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 +39083,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 +39094,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 +39110,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 +39127,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 +39165,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 +39181,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 +39205,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 +39214,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 +39239,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 +39249,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 +39272,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 +39281,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 +39301,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 +39320,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 +39341,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; + 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 +39405,7 @@ var ts; } return indexInfo.type; } - if (indexType.flags & 32768 /* Never */) { + if (indexType.flags & 131072 /* Never */) { return neverType; } if (isJSLiteralType(objectType)) { @@ -37869,15 +39431,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 +39449,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 +39492,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 +39513,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 +39526,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 +39536,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 +39552,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 +39583,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 +39605,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 +39616,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 +39655,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 +39687,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 +39710,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 +39753,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 +39783,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 +39797,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 +39830,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 +39845,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 +39895,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 +39910,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 +39919,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 +39959,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 +39971,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 +40003,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 +40018,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 +40036,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 +40185,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 +40199,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 +40248,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 +40286,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 +40296,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 +40328,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 +40337,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 +40376,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 +40420,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 +40465,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 +40544,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 +40588,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 +40601,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 +40619,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 +40634,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 +40652,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 +40683,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 +40783,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 +40802,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 +40813,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 +40859,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 +40892,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 +40917,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 +40948,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 +40979,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 +41005,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 +41021,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 +41035,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 +41113,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 +41158,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 +41204,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 +41247,7 @@ var ts; */ function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; + var relatedInfo; var maybeKeys; var sourceStack; var targetStack; @@ -39539,7 +41255,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 +41282,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 +41335,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 +41343,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 +41359,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 +41388,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 +41401,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 +41421,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 +41441,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 +41474,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 +41490,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 +41516,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 +41527,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 +41553,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 +41593,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 +41618,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 +41631,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 +41659,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 +41695,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 +41720,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 +41777,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 +41820,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 +41843,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 +41903,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 +41916,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 +41943,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 +41971,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 +42029,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 +42082,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 +42124,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 +42140,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 +42204,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 +42275,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 +42306,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 +42404,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 +42499,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 +42551,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 +42708,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; @@ -41009,7 +42820,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 +42841,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 +42865,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. @@ -41073,7 +42884,7 @@ var ts; // 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 +42894,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 +42953,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 +42976,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 +42994,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 +43009,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 +43027,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 +43070,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 +43080,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 +43168,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 +43202,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 +43238,80 @@ 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 */: 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 +43360,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 +43373,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 +43400,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 +43426,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 +43442,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 +43503,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 +43531,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 +43555,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 +43570,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 +43578,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 +43591,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 +43640,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 +43654,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 +43692,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 +43701,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 +43729,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 +43745,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 +43764,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 +43774,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 +43821,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 +43834,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 +43875,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 +43919,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 +43939,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 +43961,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 +43974,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 +43987,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 +44016,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 +44045,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 +44087,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 +44096,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 +44118,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 +44139,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 +44174,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 +44187,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 +44259,7 @@ var ts; } } } - if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -42289,16 +44272,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 +44308,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 +44324,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 +44391,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 +44403,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 +44411,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 +44436,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 +44458,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 +44476,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 +44516,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 +44538,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 +44571,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 +44624,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 +44665,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 +44683,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 +44707,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 +44726,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 +44748,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 +44758,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 +44831,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 +44868,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 +44881,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 +44909,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 +44932,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 +44949,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 +45081,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 +45103,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 +45124,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 +45132,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 +45163,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 +45180,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 +45213,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 +45264,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 +45389,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 +45402,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 +45444,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 +45461,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 +45488,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 +45509,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 +45527,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 +45548,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 +45575,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 +45593,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 +45614,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,7 +45648,7 @@ 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; } @@ -43538,7 +45677,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 +45686,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 +45696,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 +45707,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 +45716,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 +45726,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 +45753,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 +45800,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 +45813,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 +45881,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 +45922,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 +45973,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 +46048,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 +46069,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 +46084,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 +46116,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 +46139,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 +46167,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 +46188,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 +46203,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 +46211,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 +46233,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 +46244,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 +46260,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44054,7 +46275,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 +46289,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 +46317,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 +46351,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 +46363,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 +46384,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 +46445,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 +46453,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 +46468,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 +46512,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 +46573,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44306,10 +46582,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 +46601,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 +46618,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 +46659,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 +46725,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 +46782,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 +46806,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 +46852,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 +46870,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 +46906,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 +46925,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 +46934,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 +46973,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 +46985,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 +46998,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 +47007,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 +47068,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 +47082,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 +47117,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); } @@ -44903,13 +47145,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 +47161,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 +47180,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 +47191,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 +47217,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 +47234,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 +47244,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 +47281,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 +47290,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 +47301,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 +47319,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 +47327,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 +47354,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 +47373,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 +47400,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 +47410,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 +47419,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 +47434,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 +47472,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 +47494,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 +47535,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 +47568,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 +47592,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 +47605,63 @@ var ts; function getJsxElementChildrenPropertyName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType) { - if (!propsType) { - return undefined; - } - 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)); - } - 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; - } - } - } - } - 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); + function getUninstantiatedJsxSignaturesOfType(elementType) { // Resolve the signatures, preferring constructor var signatures = getSignaturesOfType(elementType, 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)); - } + } + if (signatures.length === 0 && elementType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(elementType.types, getUninstantiatedJsxSignaturesOfType)); + } + 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 +47685,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 +47718,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { + function checkJsxOpeningLikeElementOrOpeningFragment(node) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -45735,7 +47729,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 +47740,8 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren(node.parent); + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); } } /** @@ -45766,7 +47758,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 +47768,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 +47776,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 +47805,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 +47821,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 +47853,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 +47893,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 +47919,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 +47971,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,9 +47982,9 @@ 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)); @@ -46040,9 +47996,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 +48006,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 +48041,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 +48054,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 +48094,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 +48134,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); @@ -46241,16 +48203,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 +48239,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 +48269,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 +48293,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 +48305,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 +48324,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 +48351,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 +48359,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 +48392,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 +48429,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 +48456,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 +48514,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 +48525,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 +48534,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 +48554,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 +48590,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 +48642,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 +48683,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 +48709,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 +48853,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 +48876,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 +48908,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 +48924,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 +48971,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 +48995,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 +49041,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 +49134,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 +49145,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 +49184,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 +49223,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 +49257,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 +49273,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 +49302,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 +49362,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 +49381,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 +49438,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 +49466,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 +49481,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 +49506,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 +49526,58 @@ 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); + } + if (exprTypes.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes, node); + if (!intrinsicType) { + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, exprTypes.value, "JSX." + JsxNames.IntrinsicElements); + return resolveUntypedCall(node); + } + else { + var fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), intrinsicType, node.tagName, node.attributes); + return fakeSignature; + } + } + var signatures = getUninstantiatedJsxSignaturesOfType(apparentType); + if (exprTypes.flags & 4 /* String */ || 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 +49587,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 +49636,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 +49680,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 +49718,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 +49734,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 +49748,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 +49785,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 +49800,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 +49844,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 +49853,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 +49891,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 +49905,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 +49969,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 +49982,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 +50006,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 +50013,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 +50076,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 +50090,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 +50109,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 +50140,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 +50236,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 +50305,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 +50327,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 +50340,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 +50348,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 +50371,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 +50409,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 +50420,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 +50464,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48609,7 +50474,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 +50490,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 +50513,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 +50585,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 +50600,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 +50609,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 +50646,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 +50700,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 +50722,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 +50737,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 +50772,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 +50791,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 +50804,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 +50813,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 +50824,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 +50882,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 +50907,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 +50924,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 +50940,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 +50973,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 +51047,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 +51077,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 +51148,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 +51179,29 @@ 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, right); + if (isAssignmentDeclaration(declKind)) { 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 +51209,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _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 +51227,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 +51242,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 +51270,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +51280,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 +51297,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 +51379,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 +51422,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 +51444,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 +51481,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 +51492,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 +51520,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 +51546,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 +51563,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 +51577,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 +51588,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 +51715,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 +51724,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 +51735,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 +51793,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 +51813,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 +51826,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 +51862,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 +51895,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 +51912,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 +51927,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 +51999,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 +52024,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 +52044,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 +52052,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -50124,7 +52079,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 +52104,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 +52134,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 +52159,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 +52169,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 +52193,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -50255,7 +52210,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 +52241,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 +52289,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 +52298,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 +52313,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 +52328,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 +52342,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 +52360,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 +52377,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 +52470,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 +52509,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 +52520,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 +52572,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 +52582,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 +52646,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 +52672,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 +52729,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 +52760,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 +52908,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 +52931,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 +52950,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 +52988,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 +53013,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 +53081,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 +53097,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 +53166,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 +53204,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 +53219,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 +53248,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 +53257,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 +53268,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); @@ -51327,42 +53293,42 @@ 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 */: + case 241 /* 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 */: + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: if (node.body) { 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 176 /* InferType */: checkUnusedTypeParameters(node, addDiagnostic); break; default: @@ -51383,11 +53349,11 @@ var ts; 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 */) { + 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; } @@ -51396,7 +53362,7 @@ var ts; addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 155 /* Constructor */: + 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 */)) { @@ -51404,8 +53370,8 @@ var ts; } } break; - case 160 /* IndexSignature */: - case 215 /* SemicolonClassElement */: + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: // Can't be private break; default: @@ -51417,9 +53383,9 @@ var ts; 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 (node.flags & 4194304 /* Ambient */ || node.kind !== 176 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) return; - if (node.kind === 174 /* InferType */) { + if (node.kind === 176 /* 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))); @@ -51434,7 +53400,7 @@ var ts; continue; var name = ts.idText(typeParameter.name); var parent = typeParameter.parent; - if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { if (seenParentsWithEveryUnused.tryAdd(parent)) { var range = ts.isJSDocTemplateTag(parent) // Whole @template tag @@ -51520,7 +53486,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 +53504,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 +53525,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 +53537,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 +53584,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 +53598,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 +53608,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 +53623,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 +53649,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 +53664,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 +53699,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 +53711,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 +53736,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 +53747,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 +53766,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 +53781,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 +53814,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 @@ -51871,28 +53837,28 @@ var ts; 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 (parent.initializer && property) { + checkPropertyAccessibility(parent, 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 +53877,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 +53898,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 +53920,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 +53966,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 +53985,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 +53993,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 +54032,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 +54065,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 +54085,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 +54098,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 +54153,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 +54175,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 +54206,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 +54271,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 +54308,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 +54420,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 +54436,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 +54445,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 +54471,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 +54500,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 +54512,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 +54541,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 +54648,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 +54678,7 @@ var ts; case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -52877,18 +54854,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); } } @@ -52931,7 +54911,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 +54930,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 +54956,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 +54995,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 +55045,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 +55077,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 +55087,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 +55111,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 +55216,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 +55300,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 +55340,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 +55363,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 +55401,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 +55427,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 +55477,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 +55504,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 +55522,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 +55530,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 +55554,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 +55585,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 +55623,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 +55647,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 +55683,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 +55703,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 +55711,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 +55732,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 +55746,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 +55780,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 +55821,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 +55839,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 +56066,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 +56133,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 +56146,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54239,13 +56227,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 +56245,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 +56297,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 +56315,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 +56337,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 +56352,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 +56367,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 +56384,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 +56393,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 +56402,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 +56430,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 +56446,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 +56459,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 +56481,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; @@ -54518,12 +56507,12 @@ var ts; 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 +56522,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 +56538,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 +56573,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 +56596,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 +56655,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 +56709,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 +56774,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 +56795,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 +56830,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 +56850,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 +56863,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 +56883,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 +56926,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 +56945,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 +56959,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 +56972,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 +57018,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 +57046,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 +57068,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 +57081,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 +57105,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 +57139,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 +57158,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 +57166,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 +57188,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 +57203,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 +57258,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55253,12 +57288,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 +57301,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 +57320,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 +57372,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 +57387,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 +57411,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 +57458,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 +57487,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 +57522,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 +57570,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 +57594,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 +57624,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 +57637,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 +57647,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 +57659,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 +57683,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 +57740,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 +57755,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 +57770,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 +57797,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 +57840,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 +57896,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 +57961,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 +57997,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 +58027,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 +58040,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 +58056,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 +58074,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 +58099,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 +58113,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 +58130,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 +58145,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 +58198,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 +58208,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 +58217,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 +58237,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 +58277,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 +58305,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 +58331,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 +58356,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 +58385,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 +58403,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 +58415,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 +58431,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 +58460,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 +58509,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 +58526,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 +58543,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 +58571,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 +58597,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 +58638,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 +58657,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 +58665,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 +58673,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 +58694,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 +58709,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 +58736,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 +58758,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 +58828,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 +58837,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 +58864,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 +58928,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 +58950,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 +58974,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 +59055,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 +59082,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 +59138,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 +59151,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 +59167,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 +59191,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 +59204,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 +59224,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 +59239,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 +59248,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 +59265,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 +59293,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 +59313,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 +59336,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 +59357,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 +59365,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 +59373,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 +59413,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 +59427,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 +59441,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 +59449,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 +59457,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 +59469,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 +59481,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 +59493,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 +59505,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 +59517,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 +59529,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 +59537,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 +59556,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 +59574,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 +59586,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 +59604,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 +59616,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 +59631,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 +59645,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 +59663,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 +59676,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 +59688,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 +59700,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 +59719,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 +59733,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 +59747,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 +59764,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 +59778,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 +59794,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 +59810,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 +59833,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 +59847,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 +59859,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 +59883,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 +59905,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 +59917,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 +59929,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 +59941,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 +59953,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 +59966,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 +59979,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 +59996,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 +60016,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 +60030,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 +60068,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 +60080,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 +60101,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 +60119,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 +60133,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 +60145,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 +60159,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 +60173,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 +60192,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 +60207,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 +60227,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 +60243,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 +60257,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 +60271,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 +60289,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 +60305,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 +60323,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 +60335,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 +60347,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 +60359,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 +60373,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 +60387,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 +60401,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 +60413,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 +60429,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 +60450,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 +60463,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 +60489,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 +60511,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 +60533,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 +60553,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 +60572,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 +60591,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 +60603,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 +60615,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 +60627,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 +60645,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 +60663,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 +60677,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 +60689,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 +60701,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 +60715,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 +60732,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 +60750,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 +60762,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 +60777,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 +60788,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 +60854,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 +60870,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 +60886,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 +60898,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 +60914,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 +60928,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 +60940,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 +60952,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 +60966,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 +60980,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 +60992,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 +61005,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 +61020,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 +61035,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 +61049,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 +61062,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 +61083,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 +61167,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 +61179,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 +61191,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 +61206,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 +61222,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 +61245,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 +61260,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 +61302,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 +61403,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 +61914,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 +61926,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 +61954,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 +61966,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 +61979,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 +62036,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 +62051,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 +62062,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 +62074,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 +62320,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 +62348,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 +62369,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 +62403,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 +62418,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 +62455,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 +62490,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 +62506,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 +62521,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 +62556,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 +62573,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 +62598,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 +62636,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 +62647,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 +62677,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 +62705,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 +62734,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 +62755,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 +62786,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 +62794,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 +62816,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 +62881,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 +62900,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 +63003,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 +63015,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 +63051,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 +63068,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 +63080,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 +63092,7 @@ var ts; : propertyName; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -60945,7 +63107,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 +63115,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 +63161,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 +63326,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 +63637,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 +63697,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 +63710,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 +63718,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 +63769,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 +63894,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 +63902,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 +64108,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 +64158,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 +64195,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.getPositionOfLineAndCharacter(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.getPositionOfLineAndCharacter(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 +64834,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 +64880,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 +64888,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 +64924,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 +64938,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 +64958,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 +65310,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 +65377,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 +65574,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 +65605,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 +65661,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 +65682,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 +65730,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 +65754,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 +65780,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 +65814,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 +65836,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 +65853,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 +65924,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 +65935,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 +65973,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 +66038,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 +66107,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 +66309,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 +66317,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 +66365,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 +66485,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 +66556,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 +66567,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 +66584,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 +66696,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 +66854,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 +66955,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 +66977,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 +66990,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 +67001,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 +67023,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 +67068,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 +67113,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 +67225,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 +67236,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 +67269,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 +67290,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 +67298,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 +67319,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 +67408,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 +67806,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 +67887,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 +68017,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 +68063,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 +68110,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 +68304,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 +68323,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 +68331,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 +68341,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 +68410,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 +68426,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 +68452,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 +68566,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 +68594,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 +68624,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 +68845,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 +68858,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 +68902,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66378,15 +68930,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 +68963,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 +68988,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 +69024,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 +69095,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 +69113,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 +69141,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 +69163,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 +69173,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 +69257,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 +69269,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 +69278,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 +69289,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 +69321,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 +69336,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 +69353,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 +69450,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 +69547,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 +69601,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 +69621,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 +69654,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 +69679,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 +69715,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 +69828,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 +69842,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 +69918,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 +70019,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 +70325,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 +70333,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 +70385,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 +70563,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 +70588,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 +70772,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 +70790,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 +70809,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 +70946,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 +71051,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 +71090,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 +71102,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 +71160,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 +71168,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 +71239,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 +71316,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 +71368,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 +71387,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 +71433,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 +71556,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 +71638,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 +71683,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 +71721,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 +71751,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 +71772,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 +71809,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 +71846,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 +71914,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 +71983,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 +72170,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 +72201,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 +72229,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 +72243,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 +72259,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 +72338,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 +72615,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 +72686,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 +72727,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 +72848,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 +73027,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 +73064,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 +73082,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 +73129,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 +73246,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 +73344,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 +73381,7 @@ var ts; function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { enabledSubstitutions |= 2 /* BlockScopedBindings */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } /** @@ -70537,14 +73391,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 +73439,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 +73455,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 +73524,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 +73564,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 +73589,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 +73616,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 +73675,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 +73950,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 +73969,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 +74007,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 +74034,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 +74195,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 +74235,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 +74264,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 +74276,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 +74308,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 +74319,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 +74363,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 +74394,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 +74583,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 +74652,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 +75110,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 +75123,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 +75253,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 +75285,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 +75435,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 +76351,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 +76370,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 +76427,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 +76458,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 +76684,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 +76709,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 +76727,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 +76776,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 +77222,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 +77277,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 +77462,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 +77479,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 +77541,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 +77567,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 +77635,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 +77717,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 +77741,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 +77943,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 +77968,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 +78046,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 +78108,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 +78292,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 +78356,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 +78418,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 +78601,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 +78820,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 +78885,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 +78901,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 +78918,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 +78966,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -76140,12 +79000,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 +79091,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 +79127,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 +79166,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 +79195,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 +79305,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 +79334,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 +79381,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 +79390,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 +79400,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 +79425,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 +79464,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 +79491,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 +79505,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 +79530,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 +79561,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 +79574,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 +79589,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 +79631,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 +79668,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 +79698,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76856,6 +79716,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 +79726,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) { @@ -76937,15 +79798,16 @@ var ts; } } 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 +79819,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 +79856,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 +79869,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 +79906,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 +79914,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 +79935,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 +79957,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 +79970,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 +79982,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 +79995,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 +80015,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 +80031,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 +80104,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 +80124,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 +80151,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 +80256,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 +80325,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 +80343,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 +80378,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 +80388,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 +80397,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 +80413,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 +80427,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 +80451,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 +80504,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 +80515,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 +80545,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 +80554,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 +80574,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 +80596,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 242 /* ModuleDeclaration */) { + if (input.kind === 244 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -77720,7 +80617,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 +80680,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 +80701,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 +80715,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 +80753,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 +80762,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 +80872,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 +80891,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 +80899,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 +81149,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 +81191,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 +81233,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 +81253,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 +81276,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 +81349,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 +81371,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 +81386,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 +81397,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 +81441,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 +81528,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 +81571,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 +81583,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 +81596,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 +81611,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 +81636,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 +81663,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 +81689,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 +81757,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 +82045,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 +82140,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 +82183,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79975,7 +82195,8 @@ var ts; // Literals/Pseudo-literals // // SyntaxKind.NumericLiteral - function emitNumericLiteral(node) { + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { emitLiteral(node); } // SyntaxKind.StringLiteral @@ -79985,9 +82206,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 +82226,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 +82237,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -80052,7 +82273,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 +82295,7 @@ var ts; emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); @@ -80084,7 +82305,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 +82316,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitMethodDeclaration(node) { @@ -80114,7 +82335,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 +82347,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitConstructSignature(node) { @@ -80138,7 +82359,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitIndexSignature(node) { @@ -80146,10 +82367,10 @@ var ts; emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitSemicolonClassElement() { - writeSemicolon(); + writeTrailingSemicolon(); } // // Types @@ -80176,22 +82397,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 +82433,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 +82443,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 +82512,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 +82563,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 +82586,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 +82595,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 +82608,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 +82631,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 +82646,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 +82675,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 +82696,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 +82736,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,23 +82763,23 @@ 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); } @@ -80606,36 +82827,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 +82875,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 +82898,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 +82945,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 +82978,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 +83020,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 +83040,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 +83088,7 @@ var ts; } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } function emitSignatureHead(node) { @@ -80910,7 +83140,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 +83152,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 +83179,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 +83192,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 +83209,7 @@ var ts; writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); @@ -80988,7 +83218,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 +83230,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 +83246,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 +83271,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 +83304,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 +83352,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 +83378,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 +83390,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 +83405,6 @@ var ts; writePunctuation(">"); } function emitJsxText(node) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { @@ -81186,7 +83415,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 +83435,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81217,13 +83446,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 +83462,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 +83477,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); @@ -81305,6 +83534,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 +83689,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 +83747,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 +83787,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 +83822,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 131328 /* Modifiers */); + emitList(node, modifiers, 262656 /* Modifiers */); writeSpace(); } } @@ -81465,7 +83836,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 +83873,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 +83917,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 +83933,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 +83943,11 @@ var ts; writeSpace(); writePunctuation("|"); break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case 8 /* AmpersandDelimited */: writeSpace(); writePunctuation("&"); @@ -81575,11 +83958,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 +83971,7 @@ var ts; } return; } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { // TODO: GH#18217 @@ -81603,23 +83986,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 +84011,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 +84031,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 +84060,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 +84070,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 +84096,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 +84172,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 +84208,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 +84247,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 +84272,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 +84296,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 +84308,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 +84316,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 +84361,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 +84444,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 +84507,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 +84586,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82259,23 +84629,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 +84686,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 +85475,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 +85508,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 +85518,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 +85526,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 +85538,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 +85550,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 +85566,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 +85600,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 +85627,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 +85715,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 +85731,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 +85770,7 @@ var ts; } } ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { if (names.length === 0) { return []; } @@ -83034,7 +85783,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 +85793,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 +85802,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 +85827,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 +85868,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 +85901,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 +85929,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 +85949,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 +85974,33 @@ 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 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 +86014,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 +86039,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 +86089,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 +86128,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 +86157,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 +86173,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 +86226,7 @@ var ts; } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; @@ -83442,7 +86237,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 +86263,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 +86273,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 +86322,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 +86348,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 +86375,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 +86440,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 +86468,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 +86490,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 +86523,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 +86538,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 +86601,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 +86667,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 +86758,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -83969,22 +86768,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 +86791,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 +86838,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 +86899,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 +86964,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 +86991,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 +87021,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 +87071,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 +87117,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 +87173,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 +87195,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 +87261,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 +87274,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 +87308,85 @@ 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) { + 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) { + return forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (!referencedProject || + toPath(options.configFilePath) === referenceProjectPath || + !ts.contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + return referencedProject; }); - return result; + } + 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); + }); + } + 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 +87396,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 +87414,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 +87440,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 +87486,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 +87495,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 +87515,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 +87535,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 +87617,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 +87678,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 +87696,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 +87713,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 +87726,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 +87739,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 +87809,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 +87888,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 +87905,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 +87955,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 +87972,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 +88030,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 +88061,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 +88071,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 +88100,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 +88111,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 +88255,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 +88325,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 +88384,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 +88438,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 +88488,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 +88505,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 +88524,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 +88614,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 +88646,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 +88692,7 @@ var ts; */ function removeSemanticDiagnosticsOf(state, path) { if (!state.semanticDiagnosticsFromOldState) { - return false; + return true; } state.semanticDiagnosticsFromOldState.delete(path); state.semanticDiagnosticsPerFile.delete(path); @@ -85752,7 +88739,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 +88752,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 +88933,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 +88965,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 +88982,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 +89010,7 @@ var ts; resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -86073,7 +89072,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -86089,15 +89088,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 +89107,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 +89120,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 +89157,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 +89185,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 +89235,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 +89254,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 +89278,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 +89307,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 +89362,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 +89412,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 +89489,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 +89532,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 +89599,117 @@ 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 (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++; } - 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]; + return count; } 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 +89773,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 +89790,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 +89811,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 +89843,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 +89869,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 +89939,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 +90007,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 +90015,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 +90061,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 +90097,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 +90116,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 +90131,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 +90162,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 +90176,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 +90195,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 +90220,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 +90255,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 +90271,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 +90330,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 +90340,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 +90369,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 +90396,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 +90518,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 +90533,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 +90579,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 +90605,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 +90616,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 +90657,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 +90697,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 +90719,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 +90737,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 +90808,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 +90823,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 +90844,818 @@ 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); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - 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; + 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 invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); + } + /** + * 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; + // 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 }; 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); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + 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 +91691,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 +91703,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 +91848,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 +91877,6 @@ var ts; : undefined; } server.findArgument = findArgument; - /*@internal*/ function nowString() { // E.g. "12:34:56.789" var d = new Date(); @@ -88698,13 +91890,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 +91933,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 +91965,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 +92050,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 +92088,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 +92179,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; @@ -89104,6 +92228,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 +92315,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 +92400,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 +92413,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 +92460,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 +92478,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 +92518,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 +92569,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 +92585,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 +92614,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 +92651,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,12 +92659,19 @@ 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) { @@ -89512,40 +92679,40 @@ var ts; } ts.isLabelName = isLabelName; 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 +92736,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 +92754,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 +92822,7 @@ var ts; return "" /* unknown */; } } - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; default: return "" /* unknown */; @@ -89668,12 +92838,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 +92908,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 +92952,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 +93028,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 +93163,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 +93181,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 +93190,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 +93252,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 +93284,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 +93344,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 +93354,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 +93433,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 +93456,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 +93470,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 +93479,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 +93489,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 +93504,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 +93523,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 +93547,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 +93555,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 +93567,21 @@ 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 */, + 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 +93617,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 +93693,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 +93759,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 +93782,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 +93808,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 +93817,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 +93968,6 @@ var ts; return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; - /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -90819,7 +94002,7 @@ var ts; ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { return !!location.parent && - (location.parent.kind === 251 /* ImportSpecifier */ || location.parent.kind === 255 /* ExportSpecifier */) && + (location.parent.kind === 253 /* ImportSpecifier */ || location.parent.kind === 257 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -90866,6 +94049,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 +94073,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 +94081,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 +94096,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 +94122,6 @@ var ts; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ - /* @internal */ function suppressLeadingAndTrailingTrivia(node) { suppressLeadingTrivia(node); suppressTrailingTrivia(node); @@ -90941,7 +94130,6 @@ var ts; /** * Sets EmitFlags to suppress leading trivia on the node. */ - /* @internal */ function suppressLeadingTrivia(node) { addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); } @@ -90949,7 +94137,6 @@ var ts; /** * Sets EmitFlags to suppress trailing trivia on the node. */ - /* @internal */ function suppressTrailingTrivia(node) { addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); } @@ -90963,7 +94150,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 +94163,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 +94216,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 +94320,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 +94362,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 +94429,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 +94451,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 +94491,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 +94525,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 +94534,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 +94548,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 +94575,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 +94611,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 +94655,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 +94673,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 +94692,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 +94717,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 +94795,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 +94929,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 +95015,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 +95031,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 +95063,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 +95073,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 +95094,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 +95109,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 +95174,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) { @@ -91968,21 +95435,22 @@ var ts; // 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); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, 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); + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, 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, 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 +95471,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 +95552,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 +95608,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 +95636,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 +95684,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 +95740,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 +95815,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 +95859,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 +95875,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 +95906,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 +95919,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 +95931,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 +95939,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 +95967,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 +95984,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 +95999,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 +96040,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 +96077,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 +96108,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 +96146,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 +96190,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 +96225,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 +96239,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 +96276,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 +96327,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 +96357,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 +96378,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 +96405,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 +96476,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 +96485,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 +96502,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 +96546,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 +96575,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 +96623,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 +96675,10 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 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,21 +96703,21 @@ 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); @@ -93423,7 +96727,7 @@ var ts; 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 */; + 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 @@ -93444,46 +96748,40 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } 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 +96796,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 +96872,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 +96890,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 +96951,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 +96971,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 +97012,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 +97041,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 +97076,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 +97105,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 +97136,17 @@ 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 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 */)) { return parent; } - else if (parent.kind === 265 /* JsxAttribute */) { + else if (parent.kind === 267 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93843,8 +97157,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 +97166,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 +97177,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 +97196,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 +97275,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 +97300,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 +97323,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 +97338,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 +97363,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 +97406,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 +97450,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 +97465,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 +97485,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 +97514,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 +97537,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 +97569,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 +97578,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 +97594,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 +97646,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 +97722,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 +97754,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 +97779,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 +97791,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 +97827,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 +97840,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 +97849,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 +97863,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 +97877,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 +97894,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 +97912,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 +97928,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 +97949,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 +97968,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 +98003,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 +98039,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 +98074,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 +98090,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 +98128,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 +98156,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 +98222,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 +98236,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 +98261,7 @@ var ts; directImports.push(direct); } break; - case 181 /* ImportType */: + case 183 /* ImportType */: directImports.push(direct); break; default: @@ -94995,7 +98278,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 +98333,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 +98355,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 +98418,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 +98444,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 +98475,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 +98495,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 +98510,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 +98542,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) @@ -95312,7 +98595,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95381,10 +98664,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,15 +98676,15 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent) ? { isNamedImport: false } : undefined; - case 251 /* ImportSpecifier */: + 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 */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return { isNamedImport: false }; default: @@ -95434,21 +98717,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 +98740,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 +98783,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 +98805,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); }); } - 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 +98821,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 +98856,65 @@ 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) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode)); + } + 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) { + 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)) { + if (kind === 3 /* SearchedLocalFoundProperty */) { + return { prefixText: name + ": " }; + } + else if (kind === 4 /* SearchedPropertyFoundLocal */) { + return { suffixText: ": " + name }; + } + else { + return isShorthandAssignment + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + ? { suffixText: ": " + name } + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : { prefixText: 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 +98929,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 +98946,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 +98964,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 +98972,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 +99060,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 +99094,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 +99107,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 +99120,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,7 +99157,7 @@ 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; @@ -95758,12 +99169,12 @@ var ts; 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 */) { + 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 +99194,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 */; @@ -95894,15 +99305,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. */ @@ -96005,19 +99416,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 +99428,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 +99438,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 +99460,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 +99488,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 +99512,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 +99570,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 +99597,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 +99648,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; } @@ -96303,7 +99703,7 @@ 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 exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); if (!exportInfo) return ts.Debug.fail(); @@ -96367,12 +99767,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 +99783,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 +99809,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 +99826,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 +99852,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 +99869,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 +99892,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 +99920,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 +99979,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 +99994,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 +100003,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 +100045,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 +100071,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 +100101,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 +100133,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 +100147,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 +100185,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 +100248,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 +100263,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 +100282,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 +100300,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 +100352,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 +100380,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 +100410,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 +100440,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 +100482,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 +100494,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 +100502,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 +100655,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 +100676,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 +100748,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 +100870,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 +100895,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 +100968,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +101001,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +101064,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 +101081,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 +101091,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 +101115,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 +101141,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 +101167,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 +101177,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 +101192,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 +101210,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 +101222,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 +101239,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 +101408,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 +101420,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 +101446,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 +101457,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 +101479,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 +101494,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 +101504,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 +101527,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 +101597,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 +101618,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 +101648,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 +101656,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 +101675,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 +101692,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 +101722,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 +101750,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 +101762,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 +101819,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 +101833,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 +102021,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 +102120,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 +102223,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 +102330,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 +102362,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 +102392,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 +102401,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 +102698,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 +102762,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 +102906,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 +102939,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 +102956,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 +103000,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 +103019,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 +103043,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 +103065,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 +103092,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 +103107,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 +103125,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 +103241,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 +103304,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 +103341,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 +103375,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 +103399,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 +103428,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 +103451,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 +103504,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 +103570,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 +103619,7 @@ var ts; if (child === node) { break; } - if (child.kind !== 26 /* CommaToken */) { + if (child.kind !== 27 /* CommaToken */) { argumentIndex++; } } @@ -100160,8 +103638,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 +103708,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 +103716,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 +103726,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 +103742,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* 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 +103759,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 +103805,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 +103815,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 +103834,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 +103909,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 +103936,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 +103982,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 +104010,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 +104020,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 +104053,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 +104074,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 +104157,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 +104194,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 +104245,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 +104274,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 +104292,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 +104313,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 +104331,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 +104348,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 +104368,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 +104400,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 +104408,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 +104416,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 +104465,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 +104473,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 +104499,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 +104529,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 +104577,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 +104588,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 +104626,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 +104651,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 +104672,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 +104682,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 +104705,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 +104716,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 +104742,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 +104791,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 +104865,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 +104884,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; } @@ -101431,8 +104966,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 +105049,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 +105061,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 +105152,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 +105168,7 @@ var ts; } break; case 3 /* RescanTemplateToken */: - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { lastScanAction = 3 /* RescanTemplateToken */; return scanner.reScanTemplateToken(); } @@ -101706,7 +105241,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 +105253,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 +105545,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 +105595,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 +105636,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 +105669,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 +105711,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 +105783,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 +105832,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 +105892,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 +105986,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 +106017,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 +106075,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 +106198,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 +106227,7 @@ var ts; var previousParent; var previousRangeStartLine; var lastIndentedLine; - var indentationOnLastIndentedLine; + var indentationOnLastIndentedLine = -1 /* Unknown */; var edits = []; formattingScanner.advance(); if (formattingScanner.isOnToken()) { @@ -102707,7 +106241,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 +106286,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 +106307,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 +106334,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 +106366,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 +106469,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 +106505,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 +106534,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 +106580,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 +106598,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 +106802,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 +106905,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 +107049,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 +107071,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 +107109,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 +107142,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 +107203,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 +107220,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 +107251,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 +107260,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 +107349,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 +107398,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 +107485,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 +107617,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 = ""; @@ -104142,13 +107689,16 @@ var ts; if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } return 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); }; 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); @@ -104156,11 +107706,11 @@ var ts; }; 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 +107725,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 +107748,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 +107782,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 +107829,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 +107882,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 +107894,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 +107914,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: " " }); } }; @@ -104427,7 +108007,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 +108023,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 +108039,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 +108047,29 @@ 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 +108082,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 +108121,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 +108139,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 +108156,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 +108205,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 +108290,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 +108305,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 +108329,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 +108370,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 +108404,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 +108427,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 +108468,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 +108483,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; default: @@ -104888,7 +108494,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 +108508,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 +108530,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 +108547,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 +108699,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 +108792,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 +108804,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 +108819,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 +108860,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 +108900,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 +108911,754 @@ 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 isConstructor = declaration.kind === 157 /* Constructor */; + var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; + return callContexts && 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)) { + types.push.apply(types, inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken)); + } + 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.isNumber = true; + usageContext.isString = 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.isNumber = true; + usageContext.isString = 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.isNumber = true; + usageContext.isString = 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 unifyFromContext(inferences, checker, fallback) { + if (fallback === void 0) { fallback = checker.getAnyType(); } + if (!inferences.length) + return fallback; + var hasNonVacuousType = inferences.some(function (i) { return !(i.flags & (1 /* Any */ | 16384 /* Void */)); }); + var hasNonVacuousNonAnonymousType = inferences.some(function (i) { return !(i.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(i) & 16 /* Anonymous */); }); + var anons = inferences.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; }); + var good = []; + if (!hasNonVacuousNonAnonymousType && anons.length) { + good.push(unifyAnonymousTypes(anons, checker)); + } + good.push.apply(good, inferences.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */) && !(hasNonVacuousType && i.flags & (1 /* Any */ | 16384 /* Void */)); })); + 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()); + } + 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) { + return [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 +109683,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 +109720,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 +109743,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 +109751,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 +109779,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 +109792,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 +109813,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 +109832,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 +109943,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 +109957,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 +109971,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 +109997,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 +110020,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 +110030,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 +110064,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 +110080,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 +110107,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 +110123,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 +110136,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 +110284,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 +110291,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 +110351,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 +110380,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 +110400,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 +110462,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 +110471,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 +110497,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 +110514,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 +110572,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 +110596,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 +110617,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 +110628,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 +110639,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 +110711,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 +110983,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 +111054,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 +111077,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 +111102,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 +111136,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 +111184,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 +111200,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 +111223,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 +111432,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 +111466,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 +111492,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 +111511,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 +111540,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 +111567,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 +111611,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 +111621,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 +111654,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 +111673,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 +111697,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 +111717,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 +111733,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 +111745,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 +111757,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 +111982,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 +112021,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 +112059,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 +112153,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 +112173,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 +112205,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 +112214,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 +112224,7 @@ var ts; break; } case fixIdInfer: - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { changeInferToUnknown(changes, sourceFile, token); } break; @@ -107659,7 +112235,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 +112245,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 +112262,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 +112271,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 +112280,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 +112301,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 +112319,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 +112393,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 +112404,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 +112454,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 +112478,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 +112498,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 +112515,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 +112584,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 +112606,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 +112629,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 +112700,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 +112728,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 +112750,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 +112794,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 +112809,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 +112823,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 +112838,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 +112847,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 +112858,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 +112890,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 +113001,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 +113009,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 +113030,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 +113055,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 +113379,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 +113432,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 +113452,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 +113479,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 +113511,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 +113529,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 +113558,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 +113578,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 +113599,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 +113648,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 +113672,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 +113732,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 +113751,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 +113780,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 +113841,7 @@ var ts; actions: constantActions }); } - return infos.length ? infos : undefined; + return infos.length ? infos : ts.emptyArray; } extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ @@ -109764,20 +114015,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 +114071,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 +114083,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 +114104,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 +114117,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 +114142,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 +114154,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 +114165,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 +114232,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 +114243,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 +114333,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 +114377,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 +114424,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 +114454,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 +114578,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 +114593,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 +114603,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 +114636,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 +114655,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 +114742,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 +114912,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 +114920,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 +114983,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 +115023,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 +115236,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 +115280,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 +115297,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 +115308,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); @@ -111098,7 +115349,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,7 +115372,7 @@ var ts; isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasReadonlyModifier(declaration), type: ts.getTypeAnnotationNode(declaration), - container: declaration.kind === 149 /* Parameter */ ? declaration.parent.parent : declaration.parent, + container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent, originalName: declaration.name, declaration: declaration, fieldName: fieldName, @@ -111178,7 +115429,7 @@ var ts; 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; + return (entry.kind !== 0 /* Span */ && 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; @@ -111203,7 +115454,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 +115516,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 +115573,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 +115598,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 +115644,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 +115727,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 +115748,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 +115760,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 +115773,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 +115885,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 +115903,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 +115913,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 +115924,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 +115934,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 +115995,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 +116009,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 +116076,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 +116105,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 +116124,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 +116146,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 +116188,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 +116224,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 +116297,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 +116309,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 +116355,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 +116367,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 +116499,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 +116545,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 +116613,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 +116700,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 +116723,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 +116758,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 +116782,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 +116791,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 +117104,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 +117134,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 +117173,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 +117185,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 +117198,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 +117223,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 +117313,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 +117356,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 +117380,15 @@ var ts; } function shouldGetType(sourceFile, node, position) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return !ts.isLabelName(node); - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: + 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 +117426,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 +117434,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 +117495,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 +117520,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 +117582,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 +117661,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 +117725,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: "" }; @@ -113700,7 +117984,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 +117999,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 +118049,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 +118129,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 +118278,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 +118294,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 +118331,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 +118353,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 +118383,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 +118395,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 +118436,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 +118459,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 +118503,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 +118525,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 +118544,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 +118570,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 +118586,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 +118601,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 +118615,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 +118639,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 +118660,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 +118758,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 +118768,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); }); }; } } @@ -115231,30 +119515,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 +119644,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 +119790,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; @@ -115715,7 +119961,7 @@ var ts; 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); @@ -115941,7 +120187,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 +120276,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 +120338,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 +120366,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, @@ -116199,8 +120449,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 +120485,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 +120551,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 +120577,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 +120639,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 +120790,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 +120825,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 +120892,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; }); @@ -116757,38 +121010,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 +121018,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 +121038,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 +121088,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 +121124,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) { @@ -116949,13 +121168,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 +121198,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 +121254,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 +121264,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 +121273,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 +121293,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 +121330,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 +121380,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 +121391,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 +121402,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 +121474,18 @@ 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; /** 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 +121493,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 +121523,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 +121552,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 +121633,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 +121662,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 +121695,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 +121808,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 +121857,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 +121875,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 +121895,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 +121942,12 @@ var ts; */ this.configFileExistenceInfoCache = ts.createMap(); this.safelist = defaultTypeSafeList; - this.legacySafelist = {}; + this.legacySafelist = ts.createMap(); this.pendingProjectUpdates = ts.createMap(); /** 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 +121960,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 +121981,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 +122049,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 +122123,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 +122141,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 +122223,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 +122250,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 +122295,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 +122331,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 +122369,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 +122393,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 +122431,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 +122452,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 +122792,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 +122816,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 +122828,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 +122845,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,21 +122858,37 @@ 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), + projectId: this.host.createSHA256Hash(project.projectName), fileStats: server.countEachFileTypes(project.getScriptInfos()), compilerOptions: ts.convertCompilerOptionsForTelemetry(project.getCompilationSettings()), typeAcquisition: convertTypeAcquisition(project.getTypeAcquisition()), @@ -118586,8 +122907,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 +122918,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 +123055,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 +123072,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) { @@ -118810,7 +123171,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); } @@ -118836,6 +123197,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 +123222,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 +123239,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 +123252,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 +123335,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 +123361,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 +123374,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 +123404,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 +123422,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 +123458,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 +123466,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 +123477,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 +123494,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 +123573,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 +123583,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 +123628,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 +123698,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 +123735,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 +123821,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 +123851,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 +123869,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 +123896,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 +123912,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 +123927,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 +123954,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 +124005,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 +124055,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 +124068,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 +124084,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 +124102,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 +124304,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 +124322,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 +124337,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 +124351,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 +124396,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 +124424,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 +124434,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 +124450,7 @@ var ts; } }); } - return true; + return originalLocation; }); return toDo; } @@ -119976,10 +124460,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 +124774,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 +124814,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 +124829,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 +124884,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 +124898,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 +124937,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 +125141,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 +125220,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 +125357,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 +125368,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 +125387,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 +125421,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 +125429,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 +125440,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 +125644,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 +125658,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 +125871,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); } @@ -121441,8 +125989,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 +126025,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 +126102,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 +126162,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 +126189,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 +126213,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 +126242,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 +126593,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..83a5cab6a59 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.2"; /** 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[]; @@ -2056,32 +2057,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 +2156,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 +2207,7 @@ declare namespace ts { aliasTypeArguments?: ReadonlyArray; } interface LiteralType extends Type { - value: string | number; + value: string | number | PseudoBigInt; freshType: LiteralType; regularType: LiteralType; } @@ -2216,6 +2220,9 @@ declare namespace ts { interface NumberLiteralType extends LiteralType { value: number; } + interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } interface EnumType extends Type { } enum ObjectFlags { @@ -2234,6 +2241,7 @@ declare namespace ts { JsxAttributes = 4096, MarkerType = 8192, JSLiteral = 16384, + FreshLiteral = 32768, ClassOrInterface = 3 } interface ObjectType extends Type { @@ -2490,6 +2498,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2581,7 +2590,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2600,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 +2673,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 +2693,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 +2752,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 +2946,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; @@ -3117,7 +3134,7 @@ declare namespace ts { /** 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; @@ -3592,7 +3620,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 +3635,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 +3650,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 +4163,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 +4200,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 +4333,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 +4399,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 +4411,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4447,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 +4458,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 +4666,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 +4676,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 +4698,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 +4706,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 +4737,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 */ @@ -5046,9 +4901,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 +4976,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5191,24 +5055,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 +5131,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 +5266,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 +5380,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 +5438,8 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24 + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 } } declare namespace ts { @@ -5648,6 +5531,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..9b296e619a2 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.2"; /** 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) { @@ -2615,6 +3057,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2665,6 +3108,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 +3141,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 +3180,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 +3286,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 +3304,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 +3334,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 +3403,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 +3415,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 +3447,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 +3467,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 +3728,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 +3761,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 +3858,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 +3873,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 +4025,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 +4242,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 +4577,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 +5193,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 +5232,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."), @@ -4837,14 +5293,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'."), @@ -5024,7 +5480,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 +5507,14 @@ 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."), 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 +5606,14 @@ 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}'."), 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 +5727,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 +5823,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 +5921,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 +5963,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 +5973,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 +6001,14 @@ 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."), 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 +6039,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."), @@ -5673,150 +6168,105 @@ 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"), }; })(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 :: @@ -6394,6 +6844,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6404,8 +6855,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 +6874,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6498,18 +6950,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 +6987,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 +7019,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 +7088,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 +7096,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 +7196,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 +7279,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 +7312,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 +7389,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 +7420,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 +7551,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 +7608,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 +7628,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 +7654,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 +7674,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 +7704,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 +7757,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 +7824,7 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 12 /* RegularExpressionLiteral */; + token = 13 /* RegularExpressionLiteral */; } return token; } @@ -7336,7 +7832,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 +7849,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 +7888,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 +7914,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 +7938,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,6 +8051,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7575,7 +8074,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7622,7 +8120,6 @@ var ts; getText: function () { return str; }, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -7631,7 +8128,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 +8156,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 +8263,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 +8329,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 +8337,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 +8475,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 +8493,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 +8533,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 +8586,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 +8618,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 +8639,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 +8657,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 +8682,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 +8694,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 +8722,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 +8732,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 +8770,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 +8785,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 +8834,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 +8848,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 +8857,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 +8911,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 +8924,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 +8936,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 +8965,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 +9015,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 +9073,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 +9099,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 +9141,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 +9154,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 +9167,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 +9186,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 +9198,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 +9215,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 +9223,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 +9246,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 +9283,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 +9305,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 +9318,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 +9347,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 +9371,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 +9407,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 +9425,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 +9434,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 +9455,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 +9467,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 +9501,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 +9513,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 +9523,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 +9583,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 +9633,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 +9642,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 +9670,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 +9696,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 +9726,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 +9783,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 +9831,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 +9846,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 +9875,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 +9913,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 +9944,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 +9953,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 +9967,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 +9976,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 +9993,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 +10007,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 +10019,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 +10039,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 +10055,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 +10085,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 +10100,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 +10115,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 +10130,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 +10153,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 +10188,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 +10201,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 +10252,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 +10284,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 +10328,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 +10368,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 +10408,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 +10426,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 +10437,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 +10454,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 +10488,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 +10504,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 +10527,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 +10548,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 +10576,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 +10592,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 +10613,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 +10624,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 +10643,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 +10652,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 +10664,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 +10691,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 +10731,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 +10749,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 +10926,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 +10984,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 +11067,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 +11093,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 +11226,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 +11240,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 +11299,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 +11314,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 +11337,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 +11361,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 +11377,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 +11386,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 +11420,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 +11438,7 @@ var ts; } } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -10930,7 +11556,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 +11565,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 +11626,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 +11634,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 +11684,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 +11694,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 +11707,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 +11729,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 +11871,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 +11983,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 +12082,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 +12160,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 +12291,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) { @@ -11756,13 +12426,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 +12562,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 +12572,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 +12602,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 +12753,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 +12799,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 +12862,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 +12890,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 +13030,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 +13064,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 +13756,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 +13766,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 146 /* FirstNode */; + return kind >= 148 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -13078,7 +13775,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 +13787,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 +13797,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 +13806,12 @@ 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 isStringTextContainingNode(node) { - return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; // Identifiers @@ -13127,17 +13824,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 +13847,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 +13856,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 +13887,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 +13902,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 +13924,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 +13956,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,37 +13969,38 @@ 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 */; + 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 */; } /** * Node test that determines whether a node is a valid type node. @@ -13315,8 +14013,8 @@ var ts; 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 +14025,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 +14034,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 +14051,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 +14074,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 +14087,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 +14097,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 +14124,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 +14140,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 +14180,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 +14195,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 +14216,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 +14232,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 +14254,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 +14268,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 +14292,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 +14425,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 +14438,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 +14542,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 +14576,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 +14628,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 +14659,6 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; - /* @internal */ function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -13987,7 +14683,6 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; - /* @internal */ function createCompilerDiagnosticFromMessageChain(chain) { return { file: undefined, @@ -14024,14 +14719,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 +14785,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 +14813,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 +14826,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 +15028,6 @@ var ts; return rootLength > 0 && rootLength === path.length; } ts.isDiskPathRoot = isDiskPathRoot; - /* @internal */ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath @@ -14401,8 +15105,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 +15326,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 +15393,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 +15620,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 +15798,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 +15976,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 +16087,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 +16139,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 +16169,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,357 +16177,358 @@ 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 */: + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -15712,17 +16537,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 298 /* JSDocReturnTag */: + case 300 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 281 /* JSDocTypeExpression */) { + node.typeExpression.kind === 283 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -15730,20 +16555,20 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 295 /* JSDocCallbackTag */: + case 297 /* JSDocCallbackTag */: return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 299 /* JSDocThisTag */: + case 301 /* JSDocThisTag */: return visitNode(cbNode, node.typeExpression); - case 296 /* JSDocEnumTag */: + case 298 /* JSDocEnumTag */: return visitNode(cbNode, node.typeExpression); - case 291 /* JSDocSignature */: + case 293 /* JSDocSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 290 /* JSDocTypeLiteral */: + case 292 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -15751,7 +16576,7 @@ var ts; } } return; - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -15761,7 +16586,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 +16755,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 +16794,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 +16813,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 +16950,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 +17155,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 +17211,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 +17275,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 +17296,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 +17307,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 +17317,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 +17338,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 +17359,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 +17383,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 +17412,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 +17422,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 +17459,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 +17500,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 +17517,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 +17546,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 +17596,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 +17766,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 +17788,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 +17798,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 +17870,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 +17927,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 +17937,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 +17994,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 +18006,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 +18037,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 +18073,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 +18105,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 +18130,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 +18151,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 +18169,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 +18247,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 +18294,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 +18316,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 +18346,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 +18359,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 +18372,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 +18400,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 +18419,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 +18463,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 +18473,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 +18484,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 +18509,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 +18541,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 +18636,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 +18719,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 +18766,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 +18811,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 +18828,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 +18851,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 +18881,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -18044,17 +18889,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 +18911,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 +18922,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 +18933,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 +18987,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 +19016,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 +19033,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 +19042,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 +19087,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 +19103,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 +19132,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 +19151,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 +19189,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 +19200,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 +19213,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 +19246,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 +19289,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 +19299,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 +19328,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 +19341,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 +19367,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 +19378,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 +19415,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 +19436,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 +19465,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 +19495,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 +19549,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 +19573,7 @@ var ts; */ if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); - return token() === 40 /* AsteriskAsteriskToken */ ? + return token() === 41 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } @@ -18744,10 +19590,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 +19618,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 +19657,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 +19689,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 +19744,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 +19759,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 +19770,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 +19829,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 +19853,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 +19872,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 +19888,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 +19905,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 +19934,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 +19951,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 +19981,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 +19992,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 +20029,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 +20103,7 @@ var ts; } indexedAccess.argumentExpression = argument; } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } @@ -19269,13 +20115,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 +20129,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 +20142,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 +20160,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 +20182,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 +20221,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 +20245,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 +20322,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 +20358,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 +20369,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 +20381,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 +20400,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 +20443,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 +20496,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 +20530,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 +20538,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 +20547,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 +20594,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 +20629,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 +20640,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 +20658,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 +20699,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 +20746,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 +20799,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 +20808,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 +20877,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 +20896,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 +20931,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 +20942,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 +20953,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 +20979,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 +21008,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 +21021,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 +21044,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 +21056,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 +21113,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 +21126,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 +21149,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 +21159,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 +21194,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 +21217,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 +21236,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 +21246,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 +21269,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 +21317,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 +21329,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 +21363,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 +21377,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 +21396,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 +21407,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 +21429,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 +21439,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 +21512,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 +21521,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 +21532,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 +21555,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 +21570,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 +21591,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 +21602,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 +21627,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 +21647,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 +21663,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 +21714,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 +21806,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 +21826,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 +21839,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 +21853,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 +21877,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 +21911,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 +21994,7 @@ var ts; } indent = 0; break; - case 57 /* AtToken */: + case 58 /* AtToken */: scanner.setTextPos(scanner.getTextPos() - 1); // falls through case 1 /* EndOfFileToken */: @@ -21171,9 +22013,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 +22023,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 +22043,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 +22063,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 +22103,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 +22119,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 +22142,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 +22221,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 +22238,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 +22256,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 +22270,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 +22320,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 +22344,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 +22358,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 +22383,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 +22420,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 +22437,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 +22567,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 +23147,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 +23207,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 +23224,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +23238,49 @@ 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 + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22455,26 +23322,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 +23342,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 +23362,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 +23375,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 +23383,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 +23401,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 +23511,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23520,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,14 +23529,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 +23555,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23564,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23598,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23611,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 +23619,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 +23629,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 +23645,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 +23657,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 +23668,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 @@ -22874,30 +23753,12 @@ var ts; 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 +23817,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 +23837,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 +23883,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 +23891,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 +23919,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 +23947,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 +24038,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 +24088,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 +24108,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 +24116,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 +24152,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +24195,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 +24220,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 +24375,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 +24517,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 +24565,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 +24599,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 +24622,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 +24662,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 +24781,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 +24929,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 +24947,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 +24998,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 +25017,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24014,17 +25030,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 +25142,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 +25169,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 +25200,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 +25414,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 +25439,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 +25457,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 +25483,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 +25494,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 +25636,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 +25692,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 +25707,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 +25724,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 +25856,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 +25881,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 +25893,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 +25907,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 +25930,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 +25977,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 +25999,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 +26123,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 +26157,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 +26169,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 +26244,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 +26303,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 +26322,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 +26333,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 +26412,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 +26429,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 +26460,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 +26506,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 +26555,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 +26579,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 +26617,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 +26629,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 +26706,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 +26715,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 +26845,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 +26858,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 +26935,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 +26966,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 +27005,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 +27152,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 +27177,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 +27189,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 +27287,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 +27316,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 +27343,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 +27366,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 +27410,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 +27442,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 +27455,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 +27504,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 +27534,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 +27620,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 +27654,7 @@ var ts; } } } - if (expr.expression.kind === 187 /* PropertyAccessExpression */ && + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } @@ -26452,32 +27668,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 +27728,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 +27767,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 +27835,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 +27869,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 +27897,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 +27917,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 +28013,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 +28037,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 +28080,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 +28098,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 +28109,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 +28126,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 +28137,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 +28147,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 +28174,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 +28185,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -27017,10 +28232,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 +28243,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 +28252,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 +28332,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 +28391,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 +28423,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 +28432,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 +28452,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 +28479,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 +28491,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 +28523,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 +28540,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 +28557,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 +28575,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 +28612,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 +28623,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 +28664,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 +28691,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 +28760,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 +28784,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 +28822,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 +28831,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 +28880,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 +29060,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 +29115,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 +29139,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 +29166,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 +29189,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 +29209,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 +29226,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 +29247,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 +29281,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 +29331,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 (ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } var init = !node ? undefined : ts.isVariableDeclaration(node) ? node.initializer : ts.isBinaryExpression(node) ? node.right : @@ -28090,7 +29347,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 +29389,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 +29431,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 +29447,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 +29467,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 +29485,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 +29526,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 +29560,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 +29602,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 +29639,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 +29653,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 +29717,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 +29782,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 +29810,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 +29835,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 +29881,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 +29892,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 +29904,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 +29914,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 +29934,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 +29945,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 +29959,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 +29971,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 +29986,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 +29999,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 +30018,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 +30034,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 +30050,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 +30067,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 +30096,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 +30117,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 +30128,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 +30152,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 +30163,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 +30172,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 +30253,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 +30324,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 +30423,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 +30545,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 +30561,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 +30659,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 +30702,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 +30734,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 +30744,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"); @@ -29642,10 +30925,6 @@ var ts; 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); @@ -29670,14 +30949,15 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, 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 +30965,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 +31019,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29762,24 +31043,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 +31092,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 +31115,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29833,6 +31135,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29844,7 +31147,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 +31157,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 +31183,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 +31296,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 +31433,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 +31494,10 @@ 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); + target = cloneSymbol(resolveSymbol(target)); } // 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 +31507,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 +31528,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 +31593,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 +31656,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 +31686,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 +31714,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 +31743,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 +31756,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 +31779,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 +31830,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 +31872,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 +31903,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 +31917,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 +31933,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 +31961,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 +31969,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 +31989,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 +32024,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 +32033,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 +32046,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; @@ -30729,8 +32066,8 @@ var ts; } 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 +32076,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 +32131,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 +32148,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 +32165,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 +32220,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 +32233,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 +32254,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 +32290,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 +32307,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 +32325,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 +32341,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 +32379,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 +32433,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 +32489,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 +32523,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 +32533,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 +32557,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 +32591,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 +32607,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 +32629,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 +32653,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 +32673,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 +32708,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 +32724,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,6 +32746,16 @@ var ts; return symbol && symbol.valueDeclaration; } } + 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) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31421,7 +32785,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.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32804,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 +32836,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 +32844,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 +32856,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 +32898,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 +32966,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 */) : @@ -31737,13 +33105,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 +33134,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 +33189,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 +33205,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 +33255,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 +33294,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 +33309,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 +33323,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 +33365,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 +33429,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 +33479,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); @@ -32135,6 +33516,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32151,15 +33535,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 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; } } @@ -32217,9 +33601,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 & 67108864 /* 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 +33633,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 +33732,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 +33752,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 +33779,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 +33806,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 +33830,60 @@ 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 */); + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } } else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.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) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + 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 +33897,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 +33918,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 +33950,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 +33990,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 +34003,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,11 +34055,11 @@ 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 */ ? @@ -32684,26 +34101,21 @@ var ts; 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) { @@ -32716,9 +34128,9 @@ 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 */); + var 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 +34181,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 +34194,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 +34205,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 +34224,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 +34246,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 +34258,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 +34269,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 +34287,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 & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32966,7 +34391,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 +34421,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,7 +34436,7 @@ 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; @@ -33103,6 +34535,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,12 +34591,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 +34606,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 +34623,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 +34632,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 +34659,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 +34699,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 +34727,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 +34782,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 +34807,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 +34856,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 +34866,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 +34881,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 +34916,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 +34969,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 +34992,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 +35002,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 +35030,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 +35046,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 +35060,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 +35082,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 +35097,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 +35113,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 +35148,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 +35165,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 +35180,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 +35192,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 +35228,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 +35242,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 +35294,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33862,9 +35303,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 +35317,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 +35326,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 +35340,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 +35380,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 +35403,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 +35425,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 +35433,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 +35478,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 +35511,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 +35533,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 +35551,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 +35578,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 +35608,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 +35622,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 +35630,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 +35662,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 +35673,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 +35702,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 +35711,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 +35775,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 +35799,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 +35835,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 +35844,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 +35873,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 +35916,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 +35926,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 +35966,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 +35985,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 @@ -34577,14 +36033,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); @@ -34620,7 +36076,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 +36085,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 +36117,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 +36134,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 +36158,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 +36172,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 +36194,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 +36209,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 +36221,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 +36256,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 +36300,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 +36342,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 +36358,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 +36407,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 +36450,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 +36473,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 +36618,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 +36727,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 +36747,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 +36781,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 +36827,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 +36863,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 +36886,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 +36924,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 +36940,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 +36958,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 +36968,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 +36987,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 +37002,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 +37016,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 +37028,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 +37051,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 +37064,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 +37081,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 +37109,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 +37126,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 +37137,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 +37146,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 +37170,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 +37180,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 +37194,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 +37213,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 +37251,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 +37271,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 +37299,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 +37309,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 +37331,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 +37339,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 +37362,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 +37447,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 +37507,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 +37595,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 +37633,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 +37687,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 +37726,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 +37751,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 +37789,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 +37802,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 +37812,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 +37826,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 +37870,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 +37893,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 +37957,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 +37974,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 +37984,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 +37998,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 +38024,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 +38034,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 +38054,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 +38100,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 +38117,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 +38131,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 +38158,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 +38166,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 +38197,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 +38221,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 +38294,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 +38327,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 +38354,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 +38382,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 +38411,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 +38420,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 +38457,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 +38472,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 +38485,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 +38543,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 +38586,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 +38597,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 +38608,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 +38639,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 +38668,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 +38731,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 +38753,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 +38788,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 +38798,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 +38836,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 +38854,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 +38873,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 +38888,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 +38901,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 +38930,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 +38957,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 +39014,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 +39024,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 +39050,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 +39065,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 +39074,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 +39085,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 +39101,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 +39118,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 +39156,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 +39172,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 +39196,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 +39205,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 +39230,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 +39240,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 +39263,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 +39272,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 +39292,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 +39311,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 +39332,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; + 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 +39396,7 @@ var ts; } return indexInfo.type; } - if (indexType.flags & 32768 /* Never */) { + if (indexType.flags & 131072 /* Never */) { return neverType; } if (isJSLiteralType(objectType)) { @@ -37869,15 +39422,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 +39440,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 +39483,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 +39504,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 +39517,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 +39527,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 +39543,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 +39574,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 +39596,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 +39607,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 +39646,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 +39678,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 +39701,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 +39744,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 +39774,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 +39788,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 +39821,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 +39836,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 +39886,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 +39901,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 +39910,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 +39950,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 +39962,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 +39994,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 +40009,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 +40027,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 +40176,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 +40190,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 +40239,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 +40277,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 +40287,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 +40319,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 +40328,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 +40367,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 +40411,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 +40456,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 +40535,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 +40579,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 +40592,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 +40610,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 +40625,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 +40643,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 +40674,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 +40774,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 +40793,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 +40804,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 +40850,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 +40883,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 +40908,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 +40939,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 +40970,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 +40996,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 +41012,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 +41026,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 +41104,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 +41149,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 +41195,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 +41238,7 @@ var ts; */ function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; + var relatedInfo; var maybeKeys; var sourceStack; var targetStack; @@ -39539,7 +41246,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 +41273,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 +41326,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 +41334,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 +41350,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 +41379,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 +41392,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 +41412,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 +41432,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 +41465,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 +41481,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 +41507,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 +41518,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 +41544,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 +41584,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 +41609,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 +41622,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 +41650,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 +41686,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 +41711,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 +41768,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 +41811,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 +41834,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 +41894,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 +41907,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 +41934,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 +41962,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 +42020,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 +42073,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 +42115,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 +42131,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 +42195,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 +42266,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 +42297,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 +42395,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 +42490,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 +42542,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 +42699,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; @@ -41009,7 +42811,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 +42832,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 +42856,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. @@ -41073,7 +42875,7 @@ var ts; // 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 +42885,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 +42944,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 +42967,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 +42985,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 +43000,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 +43018,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 +43061,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 +43071,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 +43159,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 +43193,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 +43229,80 @@ 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 */: 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 +43351,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 +43364,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 +43391,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 +43417,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 +43433,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 +43494,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 +43522,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 +43546,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 +43561,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 +43569,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 +43582,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 +43631,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 +43645,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 +43683,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 +43692,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 +43720,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 +43736,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 +43755,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 +43765,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 +43812,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 +43825,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 +43866,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 +43910,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 +43930,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 +43952,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 +43965,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 +43978,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 +44007,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 +44036,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 +44078,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 +44087,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 +44109,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 +44130,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 +44165,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 +44178,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 +44250,7 @@ var ts; } } } - if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -42289,16 +44263,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 +44299,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 +44315,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 +44382,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 +44394,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 +44402,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 +44427,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 +44449,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 +44467,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 +44507,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 +44529,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 +44562,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 +44615,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 +44656,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 +44674,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 +44698,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 +44717,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 +44739,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 +44749,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 +44822,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 +44859,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 +44872,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 +44900,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 +44923,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 +44940,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 +45072,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 +45094,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 +45115,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 +45123,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 +45154,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 +45171,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 +45204,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 +45255,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 +45380,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 +45393,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 +45435,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 +45452,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 +45479,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 +45500,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 +45518,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 +45539,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 +45566,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 +45584,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 +45605,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,7 +45639,7 @@ 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; } @@ -43538,7 +45668,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 +45677,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 +45687,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 +45698,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 +45707,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 +45717,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 +45744,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 +45791,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 +45804,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 +45872,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 +45913,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 +45964,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 +46039,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 +46060,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 +46075,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 +46107,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 +46130,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 +46158,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 +46179,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 +46194,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 +46202,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 +46224,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 +46235,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 +46251,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44054,7 +46266,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 +46280,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 +46308,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 +46342,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 +46354,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 +46375,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 +46436,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 +46444,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 +46459,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 +46503,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 +46564,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44306,10 +46573,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 +46592,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 +46609,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 +46650,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 +46716,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 +46773,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 +46797,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 +46843,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 +46861,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 +46897,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 +46916,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 +46925,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 +46964,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 +46976,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 +46989,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 +46998,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 +47059,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 +47073,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 +47108,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); } @@ -44903,13 +47136,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 +47152,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 +47171,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 +47182,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 +47208,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 +47225,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 +47235,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 +47272,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 +47281,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 +47292,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 +47310,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 +47318,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 +47345,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 +47364,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 +47391,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 +47401,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 +47410,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 +47425,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 +47463,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 +47485,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 +47526,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 +47559,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 +47583,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 +47596,63 @@ var ts; function getJsxElementChildrenPropertyName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType) { - if (!propsType) { - return undefined; - } - 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)); - } - 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; - } - } - } - } - 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); + function getUninstantiatedJsxSignaturesOfType(elementType) { // Resolve the signatures, preferring constructor var signatures = getSignaturesOfType(elementType, 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)); - } + } + if (signatures.length === 0 && elementType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(elementType.types, getUninstantiatedJsxSignaturesOfType)); + } + 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 +47676,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 +47709,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { + function checkJsxOpeningLikeElementOrOpeningFragment(node) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -45735,7 +47720,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 +47731,8 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren(node.parent); + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); } } /** @@ -45766,7 +47749,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 +47759,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 +47767,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 +47796,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 +47812,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 +47844,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 +47884,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 +47910,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 +47962,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,9 +47973,9 @@ 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)); @@ -46040,9 +47987,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 +47997,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 +48032,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 +48045,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 +48085,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 +48125,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); @@ -46241,16 +48194,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 +48230,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 +48260,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 +48284,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 +48296,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 +48315,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 +48342,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 +48350,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 +48383,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 +48420,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 +48447,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 +48505,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 +48516,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 +48525,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 +48545,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 +48581,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 +48633,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 +48674,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 +48700,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 +48844,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 +48867,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 +48899,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 +48915,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 +48962,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 +48986,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 +49032,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 +49125,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 +49136,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 +49175,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 +49214,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 +49248,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 +49264,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 +49293,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 +49353,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 +49372,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 +49429,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 +49457,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 +49472,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 +49497,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 +49517,58 @@ 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); + } + if (exprTypes.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes, node); + if (!intrinsicType) { + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, exprTypes.value, "JSX." + JsxNames.IntrinsicElements); + return resolveUntypedCall(node); + } + else { + var fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), intrinsicType, node.tagName, node.attributes); + return fakeSignature; + } + } + var signatures = getUninstantiatedJsxSignaturesOfType(apparentType); + if (exprTypes.flags & 4 /* String */ || 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 +49578,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 +49627,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 +49671,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 +49709,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 +49725,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 +49739,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 +49776,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 +49791,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 +49835,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 +49844,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 +49882,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 +49896,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 +49960,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 +49973,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 +49997,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 +50004,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 +50067,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 +50081,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 +50100,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 +50131,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 +50227,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 +50296,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 +50318,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 +50331,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 +50339,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 +50362,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 +50400,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 +50411,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 +50455,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48609,7 +50465,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 +50481,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 +50504,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 +50576,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 +50591,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 +50600,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 +50637,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 +50691,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 +50713,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 +50728,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 +50763,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 +50782,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 +50795,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 +50804,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 +50815,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 +50873,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 +50898,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 +50915,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 +50931,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 +50964,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 +51038,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 +51068,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 +51139,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 +51170,29 @@ 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, right); + if (isAssignmentDeclaration(declKind)) { 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 +51200,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _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 +51218,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 +51233,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 +51261,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +51271,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 +51288,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 +51370,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 +51413,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 +51435,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 +51472,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 +51483,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 +51511,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 +51537,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 +51554,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 +51568,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 +51579,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 +51706,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 +51715,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 +51726,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 +51784,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 +51804,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 +51817,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 +51853,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 +51886,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 +51903,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 +51918,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 +51990,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 +52015,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 +52035,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 +52043,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -50124,7 +52070,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 +52095,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 +52125,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 +52150,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 +52160,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 +52184,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -50255,7 +52201,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 +52232,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 +52280,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 +52289,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 +52304,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 +52319,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 +52333,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 +52351,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 +52368,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 +52461,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 +52500,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 +52511,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 +52563,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 +52573,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 +52637,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 +52663,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 +52720,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 +52751,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 +52899,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 +52922,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 +52941,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 +52979,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 +53004,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 +53072,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 +53088,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 +53157,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 +53195,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 +53210,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 +53239,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 +53248,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 +53259,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); @@ -51327,42 +53284,42 @@ 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 */: + case 241 /* 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 */: + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: if (node.body) { 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 176 /* InferType */: checkUnusedTypeParameters(node, addDiagnostic); break; default: @@ -51383,11 +53340,11 @@ var ts; 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 */) { + 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; } @@ -51396,7 +53353,7 @@ var ts; addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 155 /* Constructor */: + 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 */)) { @@ -51404,8 +53361,8 @@ var ts; } } break; - case 160 /* IndexSignature */: - case 215 /* SemicolonClassElement */: + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: // Can't be private break; default: @@ -51417,9 +53374,9 @@ var ts; 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 (node.flags & 4194304 /* Ambient */ || node.kind !== 176 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) return; - if (node.kind === 174 /* InferType */) { + if (node.kind === 176 /* 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))); @@ -51434,7 +53391,7 @@ var ts; continue; var name = ts.idText(typeParameter.name); var parent = typeParameter.parent; - if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { if (seenParentsWithEveryUnused.tryAdd(parent)) { var range = ts.isJSDocTemplateTag(parent) // Whole @template tag @@ -51520,7 +53477,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 +53495,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 +53516,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 +53528,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 +53575,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 +53589,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 +53599,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 +53614,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 +53640,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 +53655,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 +53690,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 +53702,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 +53727,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 +53738,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 +53757,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 +53772,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 +53805,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 @@ -51871,28 +53828,28 @@ var ts; 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 (parent.initializer && property) { + checkPropertyAccessibility(parent, 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 +53868,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 +53889,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 +53911,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 +53957,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 +53976,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 +53984,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 +54023,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 +54056,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 +54076,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 +54089,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 +54144,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 +54166,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 +54197,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 +54262,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 +54299,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 +54411,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 +54427,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 +54436,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 +54462,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 +54491,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 +54503,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 +54532,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 +54639,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 +54669,7 @@ var ts; case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -52877,18 +54845,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); } } @@ -52931,7 +54902,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 +54921,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 +54947,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 +54986,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 +55036,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 +55068,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 +55078,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 +55102,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 +55207,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 +55291,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 +55331,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 +55354,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 +55392,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 +55418,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 +55468,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 +55495,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 +55513,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 +55521,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 +55545,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 +55576,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 +55614,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 +55638,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 +55674,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 +55694,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 +55702,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 +55723,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 +55737,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 +55771,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 +55812,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 +55830,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 +56057,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 +56124,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 +56137,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54239,13 +56218,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 +56236,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 +56288,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 +56306,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 +56328,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 +56343,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 +56358,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 +56375,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 +56384,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 +56393,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 +56421,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 +56437,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 +56450,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 +56472,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; @@ -54518,12 +56498,12 @@ var ts; 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 +56513,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 +56529,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 +56564,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 +56587,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 +56646,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 +56700,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 +56765,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 +56786,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 +56821,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 +56841,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 +56854,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 +56874,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 +56917,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 +56936,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 +56950,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 +56963,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 +57009,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 +57037,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 +57059,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 +57072,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 +57096,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 +57130,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 +57149,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 +57157,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 +57179,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 +57194,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 +57249,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55253,12 +57279,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 +57292,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 +57311,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 +57363,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 +57378,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 +57402,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 +57449,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 +57478,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 +57513,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 +57561,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 +57585,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 +57615,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 +57628,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 +57638,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 +57650,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 +57674,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 +57731,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 +57746,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 +57761,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 +57788,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 +57831,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 +57887,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 +57952,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 +57988,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 +58018,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 +58031,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 +58047,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 +58065,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 +58090,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 +58104,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 +58121,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 +58136,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 +58189,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 +58199,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 +58208,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 +58228,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 +58268,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 +58296,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 +58322,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 +58347,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 +58376,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 +58394,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 +58406,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 +58422,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 +58451,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 +58500,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 +58517,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 +58534,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 +58562,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 +58588,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 +58629,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 +58648,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 +58656,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 +58664,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 +58685,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 +58700,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 +58727,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 +58749,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 +58819,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 +58828,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 +58855,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 +58919,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 +58941,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 +58965,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 +59046,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 +59073,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 +59129,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 +59142,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 +59158,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 +59182,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 +59195,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 +59215,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 +59230,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 +59239,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 +59256,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 +59284,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 +59304,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 +59327,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 +59348,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 +59356,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 +59364,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 +59404,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 +59418,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 +59432,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 +59440,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 +59448,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 +59460,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 +59472,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 +59484,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 +59496,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 +59508,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 +59520,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 +59528,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 +59547,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 +59565,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 +59577,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 +59595,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 +59607,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 +59622,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 +59636,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 +59654,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 +59667,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 +59679,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 +59691,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 +59710,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 +59724,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 +59738,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 +59755,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 +59769,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 +59785,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 +59801,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 +59824,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 +59838,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 +59850,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 +59874,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 +59896,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 +59908,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 +59920,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 +59932,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 +59944,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 +59957,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 +59970,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 +59987,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 +60007,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 +60021,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 +60059,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 +60071,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 +60092,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 +60110,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 +60124,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 +60136,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 +60150,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 +60164,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 +60183,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 +60198,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 +60218,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 +60234,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 +60248,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 +60262,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 +60280,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 +60296,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 +60314,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 +60326,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 +60338,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 +60350,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 +60364,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 +60378,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 +60392,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 +60404,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 +60420,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 +60441,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 +60454,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 +60480,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 +60502,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 +60524,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 +60544,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 +60563,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 +60582,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 +60594,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 +60606,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 +60618,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 +60636,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 +60654,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 +60668,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 +60680,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 +60692,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 +60706,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 +60723,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 +60741,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 +60753,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 +60768,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 +60779,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 +60845,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 +60861,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 +60877,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 +60889,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 +60905,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 +60919,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 +60931,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 +60943,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 +60957,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 +60971,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 +60983,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 +60996,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 +61011,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 +61026,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 +61040,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 +61053,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 +61074,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 +61158,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 +61170,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 +61182,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 +61197,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 +61213,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 +61236,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 +61251,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 +61293,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 +61394,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 +61905,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 +61917,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 +61945,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 +61957,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 +61970,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 +62027,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 +62042,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 +62053,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 +62065,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 +62311,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 +62339,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 +62360,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 +62394,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 +62409,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 +62446,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 +62481,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 +62497,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 +62512,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 +62547,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 +62564,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 +62589,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 +62627,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 +62638,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 +62668,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 +62696,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 +62725,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 +62746,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 +62777,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 +62785,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 +62807,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 +62872,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 +62891,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 +62994,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 +63006,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 +63042,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 +63059,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 +63071,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 +63083,7 @@ var ts; : propertyName; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -60945,7 +63098,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 +63106,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 +63152,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 +63317,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 +63628,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 +63688,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 +63701,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 +63709,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 +63760,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 +63885,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 +63893,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 +64099,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 +64149,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 +64186,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.getPositionOfLineAndCharacter(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.getPositionOfLineAndCharacter(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 +64825,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 +64871,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 +64879,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 +64915,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 +64929,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 +64949,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 +65301,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 +65368,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 +65565,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 +65596,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 +65652,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 +65673,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 +65721,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 +65745,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 +65771,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 +65805,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 +65827,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 +65844,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 +65915,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 +65926,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 +65964,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 +66029,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 +66098,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 +66300,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 +66308,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 +66356,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 +66476,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 +66547,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 +66558,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 +66575,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 +66687,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 +66845,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 +66946,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 +66968,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 +66981,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 +66992,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 +67014,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 +67059,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 +67104,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 +67216,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 +67227,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 +67260,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 +67281,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 +67289,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 +67310,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 +67399,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 +67797,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 +67878,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 +68008,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 +68054,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 +68101,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 +68295,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 +68314,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 +68322,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 +68332,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 +68401,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 +68417,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 +68443,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 +68557,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 +68585,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 +68615,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 +68836,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 +68849,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 +68893,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66378,15 +68921,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 +68954,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 +68979,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 +69015,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 +69086,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 +69104,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 +69132,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 +69154,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 +69164,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 +69248,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 +69260,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 +69269,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 +69280,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 +69312,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 +69327,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 +69344,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 +69441,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 +69538,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 +69592,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 +69612,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 +69645,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 +69670,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 +69706,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 +69819,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 +69833,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 +69909,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 +70010,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 +70316,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 +70324,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 +70376,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 +70554,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 +70579,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 +70763,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 +70781,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 +70800,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 +70937,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 +71042,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 +71081,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 +71093,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 +71151,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 +71159,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 +71230,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 +71307,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 +71359,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 +71378,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 +71424,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 +71547,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 +71629,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 +71674,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 +71712,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 +71742,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 +71763,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 +71800,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 +71837,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 +71905,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 +71974,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 +72161,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 +72192,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 +72220,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 +72234,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 +72250,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 +72329,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 +72606,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 +72677,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 +72718,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 +72839,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 +73018,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 +73055,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 +73073,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 +73120,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 +73237,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 +73335,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 +73372,7 @@ var ts; function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { enabledSubstitutions |= 2 /* BlockScopedBindings */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } /** @@ -70537,14 +73382,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 +73430,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 +73446,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 +73515,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 +73555,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 +73580,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 +73607,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 +73666,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 +73941,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 +73960,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 +73998,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 +74025,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 +74186,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 +74226,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 +74255,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 +74267,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 +74299,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 +74310,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 +74354,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 +74385,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 +74574,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 +74643,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 +75101,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 +75114,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 +75244,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 +75276,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 +75426,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 +76342,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 +76361,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 +76418,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 +76449,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 +76675,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 +76700,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 +76718,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 +76767,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 +77213,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 +77268,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 +77453,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 +77470,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 +77532,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 +77558,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 +77626,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 +77708,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 +77732,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 +77934,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 +77959,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 +78037,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 +78099,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 +78283,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 +78347,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 +78409,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 +78592,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 +78811,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 +78876,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 +78892,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 +78909,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 +78957,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -76140,12 +78991,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 +79082,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 +79118,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 +79157,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 +79186,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 +79296,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 +79325,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 +79372,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 +79381,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 +79391,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 +79416,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 +79455,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 +79482,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 +79496,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 +79521,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 +79552,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 +79565,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 +79580,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 +79622,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 +79659,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 +79689,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76856,6 +79707,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 +79717,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) { @@ -76937,15 +79789,16 @@ var ts; } } 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 +79810,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 +79847,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 +79860,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 +79897,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 +79905,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 +79926,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 +79948,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 +79961,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 +79973,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 +79986,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 +80006,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 +80022,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 +80095,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 +80115,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 +80142,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 +80247,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 +80316,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 +80334,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 +80369,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 +80379,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 +80388,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 +80404,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 +80418,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 +80442,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 +80495,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 +80506,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 +80536,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 +80545,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 +80565,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 +80587,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 242 /* ModuleDeclaration */) { + if (input.kind === 244 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -77720,7 +80608,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 +80671,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 +80692,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 +80706,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 +80744,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 +80753,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 +80863,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 +80882,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 +80890,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 +81140,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 +81182,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 +81224,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 +81244,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 +81267,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 +81340,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 +81362,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 +81377,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 +81388,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 +81432,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 +81519,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 +81562,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 +81574,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 +81587,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 +81602,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 +81627,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 +81654,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 +81680,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 +81748,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 +82036,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 +82131,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 +82174,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79975,7 +82186,8 @@ var ts; // Literals/Pseudo-literals // // SyntaxKind.NumericLiteral - function emitNumericLiteral(node) { + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { emitLiteral(node); } // SyntaxKind.StringLiteral @@ -79985,9 +82197,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 +82217,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 +82228,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -80052,7 +82264,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 +82286,7 @@ var ts; emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); @@ -80084,7 +82296,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 +82307,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitMethodDeclaration(node) { @@ -80114,7 +82326,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 +82338,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitConstructSignature(node) { @@ -80138,7 +82350,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitIndexSignature(node) { @@ -80146,10 +82358,10 @@ var ts; emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitSemicolonClassElement() { - writeSemicolon(); + writeTrailingSemicolon(); } // // Types @@ -80176,22 +82388,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 +82424,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 +82434,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 +82503,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 +82554,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 +82577,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 +82586,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 +82599,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 +82622,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 +82637,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 +82666,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 +82687,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 +82727,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,23 +82754,23 @@ 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); } @@ -80606,36 +82818,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 +82866,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 +82889,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 +82936,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 +82969,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 +83011,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 +83031,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 +83079,7 @@ var ts; } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } function emitSignatureHead(node) { @@ -80910,7 +83131,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 +83143,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 +83170,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 +83183,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 +83200,7 @@ var ts; writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); @@ -80988,7 +83209,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 +83221,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 +83237,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 +83262,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 +83295,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 +83343,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 +83369,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 +83381,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 +83396,6 @@ var ts; writePunctuation(">"); } function emitJsxText(node) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { @@ -81186,7 +83406,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 +83426,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81217,13 +83437,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 +83453,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 +83468,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); @@ -81305,6 +83525,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 +83680,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 +83738,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 +83778,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 +83813,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 131328 /* Modifiers */); + emitList(node, modifiers, 262656 /* Modifiers */); writeSpace(); } } @@ -81465,7 +83827,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 +83864,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 +83908,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 +83924,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 +83934,11 @@ var ts; writeSpace(); writePunctuation("|"); break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case 8 /* AmpersandDelimited */: writeSpace(); writePunctuation("&"); @@ -81575,11 +83949,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 +83962,7 @@ var ts; } return; } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { // TODO: GH#18217 @@ -81603,23 +83977,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 +84002,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 +84022,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 +84051,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 +84061,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 +84087,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 +84163,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 +84199,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 +84238,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 +84263,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 +84287,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 +84299,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 +84307,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 +84352,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 +84435,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 +84498,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 +84577,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82259,23 +84620,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 +84677,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 +85466,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 +85499,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 +85509,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 +85517,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 +85529,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 +85541,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 +85557,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 +85591,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 +85618,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 +85706,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 +85722,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 +85761,7 @@ var ts; } } ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { if (names.length === 0) { return []; } @@ -83034,7 +85774,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 +85784,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 +85793,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 +85818,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 +85859,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 +85892,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 +85920,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 +85940,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 +85965,33 @@ 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 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 +86005,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 +86030,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 +86080,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 +86119,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 +86148,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 +86164,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 +86217,7 @@ var ts; } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; @@ -83442,7 +86228,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 +86254,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 +86264,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 +86313,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 +86339,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 +86366,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 +86431,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 +86459,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 +86481,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 +86514,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 +86529,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 +86592,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 +86658,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 +86749,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -83969,22 +86759,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 +86782,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 +86829,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 +86890,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 +86955,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 +86982,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 +87012,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 +87062,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 +87108,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 +87164,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 +87186,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 +87252,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 +87265,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 +87299,85 @@ 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) { + 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) { + return forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (!referencedProject || + toPath(options.configFilePath) === referenceProjectPath || + !ts.contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + return referencedProject; }); - return result; + } + 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); + }); + } + 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 +87387,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 +87405,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 +87431,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 +87477,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 +87486,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 +87506,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 +87526,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 +87608,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 +87669,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 +87687,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 +87704,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 +87717,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 +87730,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 +87800,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 +87879,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 +87896,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 +87946,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 +87963,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 +88021,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 +88052,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 +88062,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 +88091,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 +88102,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 +88246,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 +88316,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 +88375,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 +88429,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 +88479,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 +88496,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 +88515,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 +88605,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 +88637,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 +88683,7 @@ var ts; */ function removeSemanticDiagnosticsOf(state, path) { if (!state.semanticDiagnosticsFromOldState) { - return false; + return true; } state.semanticDiagnosticsFromOldState.delete(path); state.semanticDiagnosticsPerFile.delete(path); @@ -85752,7 +88730,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 +88743,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 +88924,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 +88956,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 +88973,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 +89001,7 @@ var ts; resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -86073,7 +89063,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -86089,15 +89079,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 +89098,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 +89111,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 +89148,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 +89176,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 +89226,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 +89245,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 +89269,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 +89298,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 +89353,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 +89403,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 +89480,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 +89523,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 +89590,117 @@ 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 (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++; } - 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]; + return count; } 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 +89764,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 +89781,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 +89802,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 +89834,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 +89860,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 +89930,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 +89998,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 +90006,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 +90052,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 +90088,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 +90107,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 +90122,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 +90153,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 +90167,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 +90186,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 +90211,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 +90246,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 +90262,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 +90321,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 +90331,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 +90360,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 +90387,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 +90509,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 +90524,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 +90570,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 +90596,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 +90607,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 +90648,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 +90688,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 +90710,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 +90728,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 +90799,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 +90814,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 +90835,818 @@ 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); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - 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; + 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 invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); + } + /** + * 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; + // 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 }; 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); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + 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 +91682,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 +91694,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 +91839,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 +91868,6 @@ var ts; : undefined; } server.findArgument = findArgument; - /*@internal*/ function nowString() { // E.g. "12:34:56.789" var d = new Date(); @@ -88698,13 +91881,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 +91924,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 +91956,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 +92041,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 +92079,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 +92170,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; @@ -89104,6 +92219,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 +92306,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 +92391,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 +92404,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 +92451,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 +92469,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 +92509,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 +92560,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 +92576,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 +92605,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 +92642,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,12 +92650,19 @@ 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) { @@ -89512,40 +92670,40 @@ var ts; } ts.isLabelName = isLabelName; 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 +92727,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 +92745,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 +92813,7 @@ var ts; return "" /* unknown */; } } - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; default: return "" /* unknown */; @@ -89668,12 +92829,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 +92899,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 +92943,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 +93019,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 +93154,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 +93172,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 +93181,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 +93243,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 +93275,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 +93335,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 +93345,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 +93424,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 +93447,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 +93461,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 +93470,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 +93480,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 +93495,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 +93514,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 +93538,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 +93546,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 +93558,21 @@ 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 */, + 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 +93608,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 +93684,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 +93750,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 +93773,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 +93799,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 +93808,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 +93959,6 @@ var ts; return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; - /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -90819,7 +93993,7 @@ var ts; ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { return !!location.parent && - (location.parent.kind === 251 /* ImportSpecifier */ || location.parent.kind === 255 /* ExportSpecifier */) && + (location.parent.kind === 253 /* ImportSpecifier */ || location.parent.kind === 257 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -90866,6 +94040,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 +94064,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 +94072,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 +94087,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 +94113,6 @@ var ts; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ - /* @internal */ function suppressLeadingAndTrailingTrivia(node) { suppressLeadingTrivia(node); suppressTrailingTrivia(node); @@ -90941,7 +94121,6 @@ var ts; /** * Sets EmitFlags to suppress leading trivia on the node. */ - /* @internal */ function suppressLeadingTrivia(node) { addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); } @@ -90949,7 +94128,6 @@ var ts; /** * Sets EmitFlags to suppress trailing trivia on the node. */ - /* @internal */ function suppressTrailingTrivia(node) { addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); } @@ -90963,7 +94141,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 +94154,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 +94207,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 +94311,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 +94353,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 +94420,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 +94442,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 +94482,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 +94516,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 +94525,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 +94539,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 +94566,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 +94602,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 +94646,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 +94664,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 +94683,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 +94708,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 +94786,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 +94920,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 +95006,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 +95022,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 +95054,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 +95064,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 +95085,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 +95100,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 +95165,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) { @@ -91968,21 +95426,22 @@ var ts; // 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); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, 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); + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, 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, 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 +95462,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 +95543,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 +95599,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 +95627,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 +95675,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 +95731,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 +95806,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 +95850,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 +95866,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 +95897,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 +95910,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 +95922,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 +95930,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 +95958,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 +95975,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 +95990,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 +96031,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 +96068,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 +96099,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 +96137,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 +96181,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 +96216,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 +96230,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 +96267,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 +96318,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 +96348,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 +96369,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 +96396,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 +96467,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 +96476,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 +96493,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 +96537,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 +96566,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 +96614,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 +96666,10 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 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,21 +96694,21 @@ 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); @@ -93423,7 +96718,7 @@ var ts; 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 */; + 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 @@ -93444,46 +96739,40 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } 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 +96787,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 +96863,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 +96881,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 +96942,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 +96962,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 +97003,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 +97032,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 +97067,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 +97096,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 +97127,17 @@ 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 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 */)) { return parent; } - else if (parent.kind === 265 /* JsxAttribute */) { + else if (parent.kind === 267 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93843,8 +97148,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 +97157,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 +97168,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 +97187,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 +97266,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 +97291,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 +97314,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 +97329,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 +97354,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 +97397,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 +97441,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 +97456,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 +97476,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 +97505,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 +97528,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 +97560,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 +97569,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 +97585,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 +97637,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 +97713,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 +97745,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 +97770,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 +97782,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 +97818,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 +97831,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 +97840,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 +97854,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 +97868,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 +97885,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 +97903,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 +97919,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 +97940,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 +97959,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 +97994,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 +98030,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 +98065,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 +98081,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 +98119,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 +98147,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 +98213,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 +98227,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 +98252,7 @@ var ts; directImports.push(direct); } break; - case 181 /* ImportType */: + case 183 /* ImportType */: directImports.push(direct); break; default: @@ -94995,7 +98269,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 +98324,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 +98346,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 +98409,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 +98435,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 +98466,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 +98486,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 +98501,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 +98533,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) @@ -95312,7 +98586,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95381,10 +98655,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,15 +98667,15 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent) ? { isNamedImport: false } : undefined; - case 251 /* ImportSpecifier */: + 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 */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return { isNamedImport: false }; default: @@ -95434,21 +98708,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 +98731,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 +98774,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 +98796,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); }); } - 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 +98812,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 +98847,65 @@ 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) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode)); + } + 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) { + 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)) { + if (kind === 3 /* SearchedLocalFoundProperty */) { + return { prefixText: name + ": " }; + } + else if (kind === 4 /* SearchedPropertyFoundLocal */) { + return { suffixText: ": " + name }; + } + else { + return isShorthandAssignment + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + ? { suffixText: ": " + name } + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : { prefixText: 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 +98920,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 +98937,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 +98955,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 +98963,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 +99051,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 +99085,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 +99098,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 +99111,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,7 +99148,7 @@ 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; @@ -95758,12 +99160,12 @@ var ts; 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 */) { + 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 +99185,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 */; @@ -95894,15 +99296,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. */ @@ -96005,19 +99407,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 +99419,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 +99429,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 +99451,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 +99479,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 +99503,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 +99561,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 +99588,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 +99639,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; } @@ -96303,7 +99694,7 @@ 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 exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); if (!exportInfo) return ts.Debug.fail(); @@ -96367,12 +99758,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 +99774,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 +99800,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 +99817,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 +99843,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 +99860,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 +99883,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 +99911,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 +99970,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 +99985,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 +99994,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 +100036,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 +100062,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 +100092,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 +100124,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 +100138,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 +100176,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 +100239,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 +100254,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 +100273,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 +100291,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 +100343,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 +100371,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 +100401,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 +100431,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 +100473,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 +100485,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 +100493,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 +100646,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 +100667,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 +100739,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 +100861,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 +100886,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 +100959,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +100992,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +101055,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 +101072,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 +101082,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 +101106,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 +101132,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 +101158,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 +101168,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 +101183,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 +101201,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 +101213,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 +101230,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 +101399,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 +101411,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 +101437,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 +101448,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 +101470,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 +101485,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 +101495,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 +101518,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 +101588,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 +101609,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 +101639,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 +101647,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 +101666,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 +101683,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 +101713,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 +101741,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 +101753,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 +101810,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 +101824,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 +102012,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 +102111,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 +102214,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 +102321,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 +102353,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 +102383,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 +102392,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 +102689,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 +102753,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 +102897,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 +102930,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 +102947,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 +102991,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 +103010,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 +103034,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 +103056,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 +103083,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 +103098,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 +103116,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 +103232,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 +103295,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 +103332,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 +103366,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 +103390,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 +103419,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 +103442,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 +103495,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 +103561,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 +103610,7 @@ var ts; if (child === node) { break; } - if (child.kind !== 26 /* CommaToken */) { + if (child.kind !== 27 /* CommaToken */) { argumentIndex++; } } @@ -100160,8 +103629,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 +103699,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 +103707,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 +103717,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 +103733,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* 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 +103750,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 +103796,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 +103806,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 +103825,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 +103900,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 +103927,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 +103973,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 +104001,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 +104011,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 +104044,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 +104065,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 +104148,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 +104185,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 +104236,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 +104265,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 +104283,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 +104304,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 +104322,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 +104339,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 +104359,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 +104391,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 +104399,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 +104407,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 +104456,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 +104464,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 +104490,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 +104520,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 +104568,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 +104579,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 +104617,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 +104642,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 +104663,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 +104673,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 +104696,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 +104707,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 +104733,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 +104782,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 +104856,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 +104875,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; } @@ -101431,8 +104957,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 +105040,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 +105052,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 +105143,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 +105159,7 @@ var ts; } break; case 3 /* RescanTemplateToken */: - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { lastScanAction = 3 /* RescanTemplateToken */; return scanner.reScanTemplateToken(); } @@ -101706,7 +105232,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 +105244,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 +105536,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 +105586,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 +105627,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 +105660,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 +105702,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 +105774,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 +105823,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 +105883,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 +105977,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 +106008,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 +106066,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 +106189,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 +106218,7 @@ var ts; var previousParent; var previousRangeStartLine; var lastIndentedLine; - var indentationOnLastIndentedLine; + var indentationOnLastIndentedLine = -1 /* Unknown */; var edits = []; formattingScanner.advance(); if (formattingScanner.isOnToken()) { @@ -102707,7 +106232,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 +106277,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 +106298,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 +106325,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 +106357,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 +106460,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 +106496,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 +106525,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 +106571,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 +106589,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 +106793,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 +106896,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 +107040,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 +107062,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 +107100,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 +107133,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 +107194,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 +107211,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 +107242,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 +107251,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 +107340,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 +107389,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 +107476,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 +107608,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 = ""; @@ -104142,13 +107680,16 @@ var ts; if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } return 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); }; 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); @@ -104156,11 +107697,11 @@ var ts; }; 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 +107716,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 +107739,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 +107773,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 +107820,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 +107873,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 +107885,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 +107905,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: " " }); } }; @@ -104427,7 +107998,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 +108014,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 +108030,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 +108038,29 @@ 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 +108073,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 +108112,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 +108130,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 +108147,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 +108196,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 +108281,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 +108296,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 +108320,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 +108361,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 +108395,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 +108418,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 +108459,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 +108474,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; default: @@ -104888,7 +108485,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 +108499,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 +108521,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 +108538,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 +108690,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 +108783,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 +108795,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 +108810,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 +108851,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 +108891,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 +108902,754 @@ 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 isConstructor = declaration.kind === 157 /* Constructor */; + var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; + return callContexts && 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)) { + types.push.apply(types, inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken)); + } + 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.isNumber = true; + usageContext.isString = 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.isNumber = true; + usageContext.isString = 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.isNumber = true; + usageContext.isString = 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 unifyFromContext(inferences, checker, fallback) { + if (fallback === void 0) { fallback = checker.getAnyType(); } + if (!inferences.length) + return fallback; + var hasNonVacuousType = inferences.some(function (i) { return !(i.flags & (1 /* Any */ | 16384 /* Void */)); }); + var hasNonVacuousNonAnonymousType = inferences.some(function (i) { return !(i.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(i) & 16 /* Anonymous */); }); + var anons = inferences.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; }); + var good = []; + if (!hasNonVacuousNonAnonymousType && anons.length) { + good.push(unifyAnonymousTypes(anons, checker)); + } + good.push.apply(good, inferences.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */) && !(hasNonVacuousType && i.flags & (1 /* Any */ | 16384 /* Void */)); })); + 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()); + } + 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) { + return [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 +109674,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 +109711,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 +109734,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 +109742,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 +109770,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 +109783,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 +109804,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 +109823,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 +109934,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 +109948,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 +109962,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 +109988,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 +110011,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 +110021,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 +110055,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 +110071,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 +110098,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 +110114,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 +110127,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 +110275,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 +110282,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 +110342,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 +110371,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 +110391,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 +110453,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 +110462,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 +110488,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 +110505,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 +110563,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 +110587,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 +110608,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 +110619,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 +110630,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 +110702,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 +110974,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 +111045,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 +111068,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 +111093,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 +111127,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 +111175,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 +111191,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 +111214,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 +111423,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 +111457,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 +111483,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 +111502,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 +111531,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 +111558,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 +111602,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 +111612,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 +111645,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 +111664,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 +111688,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 +111708,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 +111724,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 +111736,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 +111748,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 +111973,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 +112012,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 +112050,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 +112144,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 +112164,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 +112196,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 +112205,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 +112215,7 @@ var ts; break; } case fixIdInfer: - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { changeInferToUnknown(changes, sourceFile, token); } break; @@ -107659,7 +112226,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 +112236,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 +112253,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 +112262,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 +112271,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 +112292,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 +112310,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 +112384,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 +112395,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 +112445,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 +112469,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 +112489,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 +112506,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 +112575,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 +112597,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 +112620,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 +112691,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 +112719,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 +112741,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 +112785,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 +112800,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 +112814,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 +112829,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 +112838,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 +112849,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 +112881,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 +112992,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 +113000,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 +113021,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 +113046,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 +113370,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 +113423,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 +113443,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 +113470,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 +113502,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 +113520,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 +113549,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 +113569,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 +113590,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 +113639,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 +113663,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 +113723,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 +113742,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 +113771,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 +113832,7 @@ var ts; actions: constantActions }); } - return infos.length ? infos : undefined; + return infos.length ? infos : ts.emptyArray; } extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ @@ -109764,20 +114006,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 +114062,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 +114074,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 +114095,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 +114108,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 +114133,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 +114145,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 +114156,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 +114223,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 +114234,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 +114324,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 +114368,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 +114415,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 +114445,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 +114569,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 +114584,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 +114594,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 +114627,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 +114646,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 +114733,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 +114903,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 +114911,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 +114974,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 +115014,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 +115227,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 +115271,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 +115288,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 +115299,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); @@ -111098,7 +115340,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,7 +115363,7 @@ var ts; isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasReadonlyModifier(declaration), type: ts.getTypeAnnotationNode(declaration), - container: declaration.kind === 149 /* Parameter */ ? declaration.parent.parent : declaration.parent, + container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent, originalName: declaration.name, declaration: declaration, fieldName: fieldName, @@ -111178,7 +115420,7 @@ var ts; 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; + return (entry.kind !== 0 /* Span */ && 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; @@ -111203,7 +115445,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 +115507,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 +115564,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 +115589,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 +115635,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 +115718,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 +115739,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 +115751,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 +115764,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 +115876,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 +115894,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 +115904,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 +115915,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 +115925,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 +115986,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 +116000,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 +116067,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 +116096,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 +116115,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 +116137,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 +116179,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 +116215,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 +116288,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 +116300,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 +116346,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 +116358,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 +116490,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 +116536,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 +116604,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 +116691,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 +116714,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 +116749,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 +116773,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 +116782,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 +117095,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 +117125,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 +117164,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 +117176,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 +117189,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 +117214,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 +117304,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 +117347,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 +117371,15 @@ var ts; } function shouldGetType(sourceFile, node, position) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return !ts.isLabelName(node); - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: + 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 +117417,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 +117425,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 +117486,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 +117511,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 +117573,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 +117652,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 +117716,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: "" }; @@ -113700,7 +117975,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 +117990,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 +118040,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 +118120,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 +118269,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 +118285,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 +118322,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 +118344,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 +118374,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 +118386,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 +118427,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 +118450,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 +118494,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 +118516,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 +118535,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 +118561,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 +118577,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 +118592,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 +118606,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 +118630,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 +118651,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 +118749,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 +118759,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); }); }; } } diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 887e98b6f5d..8cf2dcddc09 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.2"; /** 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[]; @@ -2056,32 +2057,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 +2156,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 +2207,7 @@ declare namespace ts { aliasTypeArguments?: ReadonlyArray; } interface LiteralType extends Type { - value: string | number; + value: string | number | PseudoBigInt; freshType: LiteralType; regularType: LiteralType; } @@ -2216,6 +2220,9 @@ declare namespace ts { interface NumberLiteralType extends LiteralType { value: number; } + interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } interface EnumType extends Type { } enum ObjectFlags { @@ -2234,6 +2241,7 @@ declare namespace ts { JsxAttributes = 4096, MarkerType = 8192, JSLiteral = 16384, + FreshLiteral = 32768, ClassOrInterface = 3 } interface ObjectType extends Type { @@ -2490,6 +2498,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2581,7 +2590,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2592,14 +2600,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 +2673,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 +2693,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 +2752,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 +2946,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; @@ -3117,7 +3134,7 @@ declare namespace ts { /** 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; @@ -3592,7 +3620,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 +3635,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 +3650,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 +4163,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 +4200,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 +4333,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 +4399,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 +4411,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4412,8 +4447,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 +4458,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 +4666,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 +4676,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 +4698,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 +4706,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 +4737,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 */ @@ -5046,9 +4901,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 +4976,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5191,24 +5055,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 +5131,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 +5266,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 +5380,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 +5438,8 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24 + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 } } declare namespace ts { @@ -5648,6 +5531,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..9b296e619a2 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.2"; /** 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) { @@ -2615,6 +3057,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2665,6 +3108,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 +3141,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 +3180,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 +3286,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 +3304,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 +3334,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 +3403,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 +3415,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 +3447,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 +3467,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 +3728,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 +3761,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 +3858,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 +3873,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 +4025,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 +4242,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 +4577,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 +5193,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 +5232,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."), @@ -4837,14 +5293,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'."), @@ -5024,7 +5480,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 +5507,14 @@ 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."), 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 +5606,14 @@ 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}'."), 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 +5727,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 +5823,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 +5921,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 +5963,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 +5973,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 +6001,14 @@ 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."), 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 +6039,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."), @@ -5673,150 +6168,105 @@ 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"), }; })(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 :: @@ -6394,6 +6844,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6404,8 +6855,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 +6874,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6498,18 +6950,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 +6987,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 +7019,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 +7088,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 +7096,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 +7196,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 +7279,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 +7312,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 +7389,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 +7420,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 +7551,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 +7608,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 +7628,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 +7654,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 +7674,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 +7704,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 +7757,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 +7824,7 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 12 /* RegularExpressionLiteral */; + token = 13 /* RegularExpressionLiteral */; } return token; } @@ -7336,7 +7832,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 +7849,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 +7888,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 +7914,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 +7938,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,6 +8051,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7575,7 +8074,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7622,7 +8120,6 @@ var ts; getText: function () { return str; }, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -7631,7 +8128,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 +8156,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 +8263,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 +8329,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 +8337,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 +8475,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 +8493,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 +8533,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 +8586,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 +8618,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 +8639,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 +8657,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 +8682,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 +8694,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 +8722,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 +8732,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 +8770,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 +8785,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 +8834,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 +8848,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 +8857,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 +8911,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 +8924,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 +8936,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 +8965,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 +9015,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 +9073,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 +9099,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 +9141,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 +9154,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 +9167,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 +9186,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 +9198,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 +9215,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 +9223,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 +9246,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 +9283,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 +9305,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 +9318,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 +9347,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 +9371,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 +9407,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 +9425,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 +9434,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 +9455,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 +9467,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 +9501,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 +9513,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 +9523,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 +9583,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 +9633,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 +9642,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 +9670,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 +9696,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 +9726,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 +9783,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 +9831,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 +9846,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 +9875,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 +9913,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 +9944,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 +9953,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 +9967,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 +9976,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 +9993,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 +10007,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 +10019,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 +10039,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 +10055,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 +10085,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 +10100,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 +10115,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 +10130,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 +10153,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 +10188,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 +10201,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 +10252,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 +10284,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 +10328,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 +10368,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 +10408,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 +10426,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 +10437,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 +10454,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 +10488,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 +10504,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 +10527,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 +10548,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 +10576,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 +10592,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 +10613,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 +10624,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 +10643,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 +10652,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 +10664,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 +10691,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 +10731,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 +10749,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 +10926,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 +10984,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 +11067,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 +11093,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 +11226,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 +11240,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 +11299,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 +11314,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 +11337,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 +11361,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 +11377,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 +11386,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 +11420,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 +11438,7 @@ var ts; } } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -10930,7 +11556,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 +11565,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 +11626,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 +11634,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 +11684,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 +11694,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 +11707,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 +11729,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 +11871,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 +11983,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 +12082,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 +12160,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 +12291,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) { @@ -11756,13 +12426,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 +12562,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 +12572,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 +12602,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 +12753,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 +12799,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 +12862,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 +12890,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 +13030,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 +13064,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 +13756,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 +13766,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 146 /* FirstNode */; + return kind >= 148 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -13078,7 +13775,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 +13787,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 +13797,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 +13806,12 @@ 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 isStringTextContainingNode(node) { - return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; // Identifiers @@ -13127,17 +13824,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 +13847,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 +13856,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 +13887,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 +13902,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 +13924,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 +13956,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,37 +13969,38 @@ 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 */; + 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 */; } /** * Node test that determines whether a node is a valid type node. @@ -13315,8 +14013,8 @@ var ts; 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 +14025,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 +14034,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 +14051,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 +14074,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 +14087,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 +14097,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 +14124,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 +14140,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 +14180,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 +14195,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 +14216,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 +14232,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 +14254,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 +14268,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 +14292,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 +14425,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 +14438,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 +14542,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 +14576,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 +14628,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 +14659,6 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; - /* @internal */ function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -13987,7 +14683,6 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; - /* @internal */ function createCompilerDiagnosticFromMessageChain(chain) { return { file: undefined, @@ -14024,14 +14719,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 +14785,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 +14813,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 +14826,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 +15028,6 @@ var ts; return rootLength > 0 && rootLength === path.length; } ts.isDiskPathRoot = isDiskPathRoot; - /* @internal */ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath @@ -14401,8 +15105,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 +15326,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 +15393,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 +15620,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 +15798,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 +15976,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 +16087,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 +16139,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 +16169,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,357 +16177,358 @@ 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 */: + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -15712,17 +16537,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 298 /* JSDocReturnTag */: + case 300 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 281 /* JSDocTypeExpression */) { + node.typeExpression.kind === 283 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -15730,20 +16555,20 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 295 /* JSDocCallbackTag */: + case 297 /* JSDocCallbackTag */: return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 299 /* JSDocThisTag */: + case 301 /* JSDocThisTag */: return visitNode(cbNode, node.typeExpression); - case 296 /* JSDocEnumTag */: + case 298 /* JSDocEnumTag */: return visitNode(cbNode, node.typeExpression); - case 291 /* JSDocSignature */: + case 293 /* JSDocSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 290 /* JSDocTypeLiteral */: + case 292 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -15751,7 +16576,7 @@ var ts; } } return; - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -15761,7 +16586,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 +16755,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 +16794,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 +16813,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 +16950,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 +17155,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 +17211,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 +17275,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 +17296,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 +17307,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 +17317,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 +17338,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 +17359,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 +17383,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 +17412,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 +17422,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 +17459,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 +17500,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 +17517,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 +17546,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 +17596,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 +17766,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 +17788,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 +17798,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 +17870,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 +17927,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 +17937,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 +17994,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 +18006,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 +18037,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 +18073,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 +18105,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 +18130,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 +18151,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 +18169,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 +18247,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 +18294,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 +18316,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 +18346,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 +18359,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 +18372,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 +18400,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 +18419,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 +18463,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 +18473,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 +18484,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 +18509,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 +18541,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 +18636,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 +18719,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 +18766,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 +18811,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 +18828,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 +18851,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 +18881,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -18044,17 +18889,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 +18911,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 +18922,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 +18933,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 +18987,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 +19016,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 +19033,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 +19042,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 +19087,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 +19103,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 +19132,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 +19151,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 +19189,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 +19200,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 +19213,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 +19246,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 +19289,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 +19299,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 +19328,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 +19341,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 +19367,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 +19378,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 +19415,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 +19436,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 +19465,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 +19495,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 +19549,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 +19573,7 @@ var ts; */ if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); - return token() === 40 /* AsteriskAsteriskToken */ ? + return token() === 41 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } @@ -18744,10 +19590,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 +19618,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 +19657,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 +19689,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 +19744,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 +19759,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 +19770,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 +19829,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 +19853,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 +19872,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 +19888,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 +19905,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 +19934,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 +19951,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 +19981,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 +19992,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 +20029,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 +20103,7 @@ var ts; } indexedAccess.argumentExpression = argument; } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } @@ -19269,13 +20115,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 +20129,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 +20142,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 +20160,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 +20182,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 +20221,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 +20245,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 +20322,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 +20358,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 +20369,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 +20381,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 +20400,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 +20443,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 +20496,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 +20530,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 +20538,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 +20547,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 +20594,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 +20629,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 +20640,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 +20658,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 +20699,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 +20746,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 +20799,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 +20808,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 +20877,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 +20896,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 +20931,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 +20942,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 +20953,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 +20979,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 +21008,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 +21021,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 +21044,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 +21056,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 +21113,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 +21126,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 +21149,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 +21159,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 +21194,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 +21217,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 +21236,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 +21246,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 +21269,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 +21317,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 +21329,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 +21363,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 +21377,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 +21396,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 +21407,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 +21429,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 +21439,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 +21512,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 +21521,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 +21532,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 +21555,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 +21570,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 +21591,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 +21602,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 +21627,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 +21647,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 +21663,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 +21714,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 +21806,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 +21826,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 +21839,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 +21853,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 +21877,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 +21911,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 +21994,7 @@ var ts; } indent = 0; break; - case 57 /* AtToken */: + case 58 /* AtToken */: scanner.setTextPos(scanner.getTextPos() - 1); // falls through case 1 /* EndOfFileToken */: @@ -21171,9 +22013,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 +22023,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 +22043,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 +22063,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 +22103,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 +22119,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 +22142,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 +22221,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 +22238,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 +22256,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 +22270,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 +22320,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 +22344,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 +22358,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 +22383,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 +22420,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 +22437,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 +22567,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 +23147,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 +23207,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 +23224,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22414,6 +23238,49 @@ 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 + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22455,26 +23322,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 +23342,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 +23362,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 +23375,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 +23383,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 +23401,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 +23511,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22661,6 +23520,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22669,14 +23529,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 +23555,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22693,6 +23564,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22726,6 +23598,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22738,6 +23611,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 +23619,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 +23629,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 +23645,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 +23657,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 +23668,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 @@ -22874,30 +23753,12 @@ var ts; 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 +23817,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 +23837,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 +23883,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 +23891,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 +23919,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 +23947,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 +24038,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 +24088,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 +24108,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 +24116,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 +24152,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23290,9 +24195,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 +24220,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 +24375,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 +24517,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 +24565,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 +24599,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 +24622,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 +24662,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 +24781,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 +24929,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 +24947,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 +24998,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 +25017,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24014,17 +25030,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 +25142,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 +25169,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 +25200,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 +25414,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 +25439,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 +25457,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 +25483,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 +25494,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 +25636,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 +25692,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 +25707,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 +25724,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 +25856,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 +25881,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 +25893,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 +25907,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 +25930,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 +25977,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 +25999,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 +26123,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 +26157,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 +26169,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 +26244,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 +26303,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 +26322,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 +26333,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 +26412,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 +26429,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 +26460,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 +26506,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 +26555,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 +26579,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 +26617,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 +26629,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 +26706,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 +26715,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 +26845,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 +26858,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 +26935,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 +26966,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 +27005,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 +27152,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 +27177,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 +27189,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 +27287,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 +27316,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 +27343,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 +27366,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 +27410,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 +27442,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 +27455,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 +27504,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 +27534,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 +27620,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 +27654,7 @@ var ts; } } } - if (expr.expression.kind === 187 /* PropertyAccessExpression */ && + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } @@ -26452,32 +27668,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 +27728,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 +27767,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 +27835,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 +27869,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 +27897,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 +27917,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 +28013,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 +28037,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 +28080,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 +28098,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 +28109,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 +28126,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 +28137,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 +28147,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 +28174,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 +28185,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -27017,10 +28232,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 +28243,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 +28252,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 +28332,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 +28391,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 +28423,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 +28432,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 +28452,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 +28479,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 +28491,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 +28523,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 +28540,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 +28557,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 +28575,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 +28612,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 +28623,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 +28664,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 +28691,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 +28760,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 +28784,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 +28822,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 +28831,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 +28880,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 +29060,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 +29115,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 +29139,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 +29166,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 +29189,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 +29209,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 +29226,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 +29247,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 +29281,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 +29331,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 (ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } var init = !node ? undefined : ts.isVariableDeclaration(node) ? node.initializer : ts.isBinaryExpression(node) ? node.right : @@ -28090,7 +29347,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 +29389,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 +29431,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 +29447,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 +29467,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 +29485,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 +29526,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 +29560,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 +29602,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 +29639,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 +29653,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 +29717,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 +29782,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 +29810,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 +29835,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 +29881,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 +29892,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 +29904,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 +29914,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 +29934,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 +29945,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 +29959,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 +29971,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 +29986,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 +29999,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 +30018,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 +30034,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 +30050,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 +30067,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 +30096,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 +30117,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 +30128,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 +30152,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 +30163,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 +30172,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 +30253,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 +30324,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 +30423,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 +30545,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 +30561,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 +30659,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 +30702,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 +30734,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 +30744,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"); @@ -29642,10 +30925,6 @@ var ts; 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); @@ -29670,14 +30949,15 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, 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 +30965,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 +31019,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29762,24 +31043,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 +31092,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 +31115,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29833,6 +31135,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29844,7 +31147,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 +31157,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 +31183,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 +31296,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 +31433,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 +31494,10 @@ 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); + target = cloneSymbol(resolveSymbol(target)); } // 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 +31507,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 +31528,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 +31593,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 +31656,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 +31686,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 +31714,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 +31743,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 +31756,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 +31779,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 +31830,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 +31872,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 +31903,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 +31917,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 +31933,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 +31961,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 +31969,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 +31989,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 +32024,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 +32033,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 +32046,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; @@ -30729,8 +32066,8 @@ var ts; } 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 +32076,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 +32131,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 +32148,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 +32165,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 +32220,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 +32233,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 +32254,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 +32290,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 +32307,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 +32325,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 +32341,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 +32379,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 +32433,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 +32489,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 +32523,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 +32533,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 +32557,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 +32591,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 +32607,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 +32629,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 +32653,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 +32673,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 +32708,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 +32724,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,6 +32746,16 @@ var ts; return symbol && symbol.valueDeclaration; } } + 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) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31421,7 +32785,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.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31440,7 +32804,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 +32836,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 +32844,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 +32856,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 +32898,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 +32966,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 */) : @@ -31737,13 +33105,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 +33134,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 +33189,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 +33205,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 +33255,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 +33294,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 +33309,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 +33323,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 +33365,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 +33429,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 +33479,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); @@ -32135,6 +33516,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32151,15 +33535,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 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; } } @@ -32217,9 +33601,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 & 67108864 /* 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 +33633,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 +33732,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 +33752,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 +33779,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 +33806,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 +33830,60 @@ 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 */); + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } } else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.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) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + 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 +33897,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 +33918,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 +33950,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 +33990,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 +34003,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,11 +34055,11 @@ 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 */ ? @@ -32684,26 +34101,21 @@ var ts; 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) { @@ -32716,9 +34128,9 @@ 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 */); + var 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 +34181,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 +34194,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 +34205,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 +34224,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 +34246,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 +34258,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 +34269,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 +34287,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 & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32966,7 +34391,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 +34421,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,7 +34436,7 @@ 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; @@ -33103,6 +34535,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,12 +34591,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 +34606,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 +34623,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 +34632,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 +34659,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 +34699,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 +34727,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 +34782,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 +34807,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 +34856,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 +34866,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 +34881,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 +34916,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 +34969,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 +34992,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 +35002,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 +35030,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 +35046,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 +35060,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 +35082,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 +35097,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 +35113,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 +35148,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 +35165,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 +35180,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 +35192,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 +35228,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 +35242,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 +35294,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33862,9 +35303,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 +35317,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 +35326,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 +35340,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 +35380,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 +35403,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 +35425,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 +35433,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 +35478,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 +35511,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 +35533,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 +35551,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 +35578,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 +35608,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 +35622,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 +35630,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 +35662,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 +35673,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 +35702,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 +35711,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 +35775,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 +35799,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 +35835,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 +35844,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 +35873,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 +35916,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 +35926,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 +35966,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 +35985,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 @@ -34577,14 +36033,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); @@ -34620,7 +36076,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 +36085,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 +36117,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 +36134,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 +36158,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 +36172,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 +36194,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 +36209,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 +36221,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 +36256,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 +36300,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 +36342,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 +36358,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 +36407,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 +36450,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 +36473,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 +36618,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 +36727,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 +36747,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 +36781,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 +36827,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 +36863,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 +36886,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 +36924,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 +36940,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 +36958,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 +36968,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 +36987,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 +37002,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 +37016,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 +37028,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 +37051,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 +37064,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 +37081,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 +37109,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 +37126,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 +37137,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 +37146,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 +37170,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 +37180,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 +37194,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 +37213,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 +37251,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 +37271,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 +37299,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 +37309,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 +37331,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 +37339,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 +37362,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 +37447,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 +37507,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 +37595,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 +37633,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 +37687,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 +37726,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 +37751,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 +37789,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 +37802,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 +37812,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 +37826,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 +37870,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 +37893,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 +37957,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 +37974,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 +37984,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 +37998,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 +38024,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 +38034,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 +38054,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 +38100,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 +38117,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 +38131,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 +38158,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 +38166,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 +38197,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 +38221,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 +38294,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 +38327,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 +38354,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 +38382,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 +38411,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 +38420,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 +38457,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 +38472,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 +38485,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 +38543,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 +38586,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 +38597,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 +38608,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 +38639,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 +38668,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 +38731,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 +38753,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 +38788,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 +38798,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 +38836,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 +38854,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 +38873,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 +38888,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 +38901,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 +38930,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 +38957,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 +39014,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 +39024,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 +39050,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 +39065,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 +39074,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 +39085,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 +39101,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 +39118,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 +39156,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 +39172,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 +39196,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 +39205,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 +39230,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 +39240,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 +39263,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 +39272,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 +39292,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 +39311,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 +39332,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; + 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 +39396,7 @@ var ts; } return indexInfo.type; } - if (indexType.flags & 32768 /* Never */) { + if (indexType.flags & 131072 /* Never */) { return neverType; } if (isJSLiteralType(objectType)) { @@ -37869,15 +39422,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 +39440,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 +39483,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 +39504,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 +39517,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 +39527,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 +39543,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 +39574,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 +39596,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 +39607,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 +39646,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 +39678,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 +39701,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 +39744,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 +39774,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 +39788,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 +39821,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 +39836,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 +39886,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 +39901,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 +39910,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 +39950,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 +39962,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 +39994,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 +40009,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 +40027,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 +40176,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 +40190,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 +40239,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 +40277,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 +40287,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 +40319,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 +40328,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 +40367,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 +40411,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 +40456,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 +40535,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 +40579,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 +40592,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 +40610,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 +40625,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 +40643,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 +40674,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 +40774,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 +40793,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 +40804,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 +40850,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 +40883,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 +40908,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 +40939,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 +40970,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 +40996,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 +41012,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 +41026,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 +41104,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 +41149,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 +41195,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 +41238,7 @@ var ts; */ function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; + var relatedInfo; var maybeKeys; var sourceStack; var targetStack; @@ -39539,7 +41246,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 +41273,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 +41326,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 +41334,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 +41350,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 +41379,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 +41392,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 +41412,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 +41432,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 +41465,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 +41481,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 +41507,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 +41518,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 +41544,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 +41584,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 +41609,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 +41622,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 +41650,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 +41686,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 +41711,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 +41768,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 +41811,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 +41834,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 +41894,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 +41907,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 +41934,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 +41962,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 +42020,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 +42073,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 +42115,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 +42131,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 +42195,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 +42266,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 +42297,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 +42395,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 +42490,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 +42542,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 +42699,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; @@ -41009,7 +42811,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 +42832,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 +42856,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. @@ -41073,7 +42875,7 @@ var ts; // 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 +42885,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 +42944,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 +42967,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 +42985,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 +43000,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 +43018,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 +43061,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 +43071,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 +43159,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 +43193,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 +43229,80 @@ 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 */: 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 +43351,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 +43364,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 +43391,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 +43417,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 +43433,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 +43494,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 +43522,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 +43546,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 +43561,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 +43569,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 +43582,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 +43631,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 +43645,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 +43683,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 +43692,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 +43720,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 +43736,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 +43755,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 +43765,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 +43812,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 +43825,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 +43866,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 +43910,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 +43930,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 +43952,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 +43965,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 +43978,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 +44007,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 +44036,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 +44078,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 +44087,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 +44109,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 +44130,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 +44165,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 +44178,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 +44250,7 @@ var ts; } } } - if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -42289,16 +44263,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 +44299,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 +44315,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 +44382,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 +44394,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 +44402,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 +44427,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 +44449,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 +44467,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 +44507,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 +44529,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 +44562,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 +44615,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 +44656,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 +44674,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 +44698,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 +44717,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 +44739,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 +44749,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 +44822,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 +44859,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 +44872,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 +44900,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 +44923,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 +44940,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 +45072,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 +45094,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 +45115,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 +45123,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 +45154,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 +45171,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 +45204,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 +45255,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 +45380,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 +45393,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 +45435,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 +45452,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 +45479,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 +45500,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 +45518,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 +45539,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 +45566,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 +45584,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 +45605,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,7 +45639,7 @@ 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; } @@ -43538,7 +45668,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 +45677,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 +45687,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 +45698,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 +45707,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 +45717,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 +45744,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 +45791,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 +45804,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 +45872,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 +45913,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 +45964,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 +46039,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 +46060,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 +46075,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 +46107,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 +46130,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 +46158,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 +46179,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 +46194,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 +46202,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 +46224,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 +46235,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 +46251,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44054,7 +46266,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 +46280,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 +46308,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 +46342,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 +46354,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 +46375,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 +46436,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 +46444,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 +46459,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 +46503,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 +46564,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44306,10 +46573,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 +46592,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 +46609,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 +46650,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 +46716,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 +46773,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 +46797,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 +46843,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 +46861,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 +46897,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 +46916,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 +46925,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 +46964,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 +46976,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 +46989,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 +46998,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 +47059,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 +47073,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 +47108,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); } @@ -44903,13 +47136,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 +47152,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 +47171,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 +47182,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 +47208,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 +47225,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 +47235,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 +47272,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 +47281,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 +47292,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 +47310,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 +47318,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 +47345,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 +47364,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 +47391,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 +47401,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 +47410,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 +47425,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 +47463,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 +47485,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 +47526,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 +47559,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 +47583,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 +47596,63 @@ var ts; function getJsxElementChildrenPropertyName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType) { - if (!propsType) { - return undefined; - } - 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)); - } - 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; - } - } - } - } - 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); + function getUninstantiatedJsxSignaturesOfType(elementType) { // Resolve the signatures, preferring constructor var signatures = getSignaturesOfType(elementType, 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)); - } + } + if (signatures.length === 0 && elementType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(elementType.types, getUninstantiatedJsxSignaturesOfType)); + } + 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 +47676,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 +47709,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { + function checkJsxOpeningLikeElementOrOpeningFragment(node) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -45735,7 +47720,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 +47731,8 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren(node.parent); + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); } } /** @@ -45766,7 +47749,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 +47759,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 +47767,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 +47796,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 +47812,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 +47844,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 +47884,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 +47910,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 +47962,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,9 +47973,9 @@ 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)); @@ -46040,9 +47987,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 +47997,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 +48032,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 +48045,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 +48085,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 +48125,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); @@ -46241,16 +48194,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 +48230,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 +48260,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 +48284,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 +48296,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 +48315,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 +48342,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 +48350,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 +48383,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 +48420,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 +48447,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 +48505,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 +48516,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 +48525,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 +48545,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 +48581,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 +48633,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 +48674,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 +48700,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 +48844,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 +48867,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 +48899,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 +48915,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 +48962,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 +48986,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 +49032,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 +49125,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 +49136,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 +49175,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 +49214,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 +49248,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 +49264,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 +49293,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 +49353,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 +49372,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 +49429,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 +49457,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 +49472,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 +49497,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 +49517,58 @@ 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); + } + if (exprTypes.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes, node); + if (!intrinsicType) { + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, exprTypes.value, "JSX." + JsxNames.IntrinsicElements); + return resolveUntypedCall(node); + } + else { + var fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), intrinsicType, node.tagName, node.attributes); + return fakeSignature; + } + } + var signatures = getUninstantiatedJsxSignaturesOfType(apparentType); + if (exprTypes.flags & 4 /* String */ || 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 +49578,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 +49627,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 +49671,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 +49709,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 +49725,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 +49739,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 +49776,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 +49791,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 +49835,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 +49844,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 +49882,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 +49896,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 +49960,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 +49973,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 +49997,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 +50004,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 +50067,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 +50081,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 +50100,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 +50131,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 +50227,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 +50296,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 +50318,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 +50331,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 +50339,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 +50362,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 +50400,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 +50411,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 +50455,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48609,7 +50465,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 +50481,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 +50504,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 +50576,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 +50591,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 +50600,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 +50637,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 +50691,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 +50713,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 +50728,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 +50763,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 +50782,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 +50795,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 +50804,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 +50815,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 +50873,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 +50898,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 +50915,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 +50931,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 +50964,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 +51038,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 +51068,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 +51139,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 +51170,29 @@ 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, right); + if (isAssignmentDeclaration(declKind)) { 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 +51200,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _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 +51218,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 +51233,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 +51261,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49331,7 +51271,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 +51288,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 +51370,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 +51413,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 +51435,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 +51472,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 +51483,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 +51511,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 +51537,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 +51554,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 +51568,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 +51579,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 +51706,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 +51715,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 +51726,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 +51784,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 +51804,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 +51817,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 +51853,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 +51886,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 +51903,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 +51918,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 +51990,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 +52015,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 +52035,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 +52043,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -50124,7 +52070,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 +52095,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 +52125,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 +52150,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 +52160,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 +52184,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -50255,7 +52201,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 +52232,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 +52280,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 +52289,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 +52304,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 +52319,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 +52333,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 +52351,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 +52368,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 +52461,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 +52500,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 +52511,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 +52563,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 +52573,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 +52637,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 +52663,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 +52720,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 +52751,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 +52899,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 +52922,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 +52941,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 +52979,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 +53004,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 +53072,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 +53088,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 +53157,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 +53195,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 +53210,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 +53239,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 +53248,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 +53259,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); @@ -51327,42 +53284,42 @@ 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 */: + case 241 /* 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 */: + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: if (node.body) { 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 176 /* InferType */: checkUnusedTypeParameters(node, addDiagnostic); break; default: @@ -51383,11 +53340,11 @@ var ts; 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 */) { + 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; } @@ -51396,7 +53353,7 @@ var ts; addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 155 /* Constructor */: + 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 */)) { @@ -51404,8 +53361,8 @@ var ts; } } break; - case 160 /* IndexSignature */: - case 215 /* SemicolonClassElement */: + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: // Can't be private break; default: @@ -51417,9 +53374,9 @@ var ts; 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 (node.flags & 4194304 /* Ambient */ || node.kind !== 176 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) return; - if (node.kind === 174 /* InferType */) { + if (node.kind === 176 /* 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))); @@ -51434,7 +53391,7 @@ var ts; continue; var name = ts.idText(typeParameter.name); var parent = typeParameter.parent; - if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { if (seenParentsWithEveryUnused.tryAdd(parent)) { var range = ts.isJSDocTemplateTag(parent) // Whole @template tag @@ -51520,7 +53477,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 +53495,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 +53516,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 +53528,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 +53575,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 +53589,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 +53599,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 +53614,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 +53640,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 +53655,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 +53690,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 +53702,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 +53727,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 +53738,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 +53757,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 +53772,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 +53805,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 @@ -51871,28 +53828,28 @@ var ts; 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 (parent.initializer && property) { + checkPropertyAccessibility(parent, 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 +53868,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 +53889,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 +53911,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 +53957,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 +53976,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 +53984,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 +54023,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 +54056,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 +54076,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 +54089,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 +54144,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 +54166,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 +54197,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 +54262,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 +54299,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 +54411,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 +54427,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 +54436,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 +54462,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 +54491,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 +54503,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 +54532,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 +54639,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 +54669,7 @@ var ts; case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -52877,18 +54845,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); } } @@ -52931,7 +54902,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 +54921,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 +54947,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 +54986,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 +55036,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 +55068,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 +55078,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 +55102,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 +55207,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 +55291,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 +55331,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 +55354,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 +55392,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 +55418,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 +55468,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 +55495,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 +55513,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 +55521,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 +55545,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 +55576,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 +55614,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 +55638,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 +55674,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 +55694,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 +55702,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 +55723,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 +55737,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 +55771,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 +55812,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 +55830,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 +56057,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 +56124,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 +56137,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54239,13 +56218,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 +56236,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 +56288,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 +56306,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 +56328,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 +56343,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 +56358,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 +56375,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 +56384,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 +56393,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 +56421,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 +56437,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 +56450,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 +56472,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; @@ -54518,12 +56498,12 @@ var ts; 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 +56513,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 +56529,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 +56564,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 +56587,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 +56646,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 +56700,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 +56765,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 +56786,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 +56821,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 +56841,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 +56854,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 +56874,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 +56917,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 +56936,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 +56950,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 +56963,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 +57009,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 +57037,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 +57059,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 +57072,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 +57096,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 +57130,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 +57149,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 +57157,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 +57179,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 +57194,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 +57249,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55253,12 +57279,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 +57292,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 +57311,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 +57363,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 +57378,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 +57402,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 +57449,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 +57478,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 +57513,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 +57561,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 +57585,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 +57615,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 +57628,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 +57638,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 +57650,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 +57674,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 +57731,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 +57746,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 +57761,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 +57788,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 +57831,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 +57887,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 +57952,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 +57988,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 +58018,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 +58031,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 +58047,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 +58065,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 +58090,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 +58104,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 +58121,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 +58136,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 +58189,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 +58199,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 +58208,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 +58228,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 +58268,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 +58296,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 +58322,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 +58347,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 +58376,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 +58394,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 +58406,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 +58422,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 +58451,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 +58500,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 +58517,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 +58534,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 +58562,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 +58588,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 +58629,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 +58648,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 +58656,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 +58664,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 +58685,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 +58700,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 +58727,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 +58749,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 +58819,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 +58828,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 +58855,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 +58919,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 +58941,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 +58965,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 +59046,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 +59073,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 +59129,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 +59142,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 +59158,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 +59182,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 +59195,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 +59215,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 +59230,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 +59239,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 +59256,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 +59284,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 +59304,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 +59327,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 +59348,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 +59356,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 +59364,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 +59404,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 +59418,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 +59432,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 +59440,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 +59448,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 +59460,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 +59472,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 +59484,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 +59496,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 +59508,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 +59520,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 +59528,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 +59547,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 +59565,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 +59577,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 +59595,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 +59607,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 +59622,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 +59636,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 +59654,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 +59667,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 +59679,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 +59691,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 +59710,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 +59724,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 +59738,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 +59755,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 +59769,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 +59785,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 +59801,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 +59824,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 +59838,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 +59850,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 +59874,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 +59896,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 +59908,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 +59920,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 +59932,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 +59944,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 +59957,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 +59970,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 +59987,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 +60007,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 +60021,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 +60059,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 +60071,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 +60092,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 +60110,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 +60124,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 +60136,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 +60150,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 +60164,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 +60183,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 +60198,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 +60218,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 +60234,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 +60248,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 +60262,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 +60280,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 +60296,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 +60314,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 +60326,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 +60338,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 +60350,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 +60364,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 +60378,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 +60392,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 +60404,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 +60420,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 +60441,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 +60454,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 +60480,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 +60502,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 +60524,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 +60544,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 +60563,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 +60582,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 +60594,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 +60606,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 +60618,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 +60636,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 +60654,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 +60668,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 +60680,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 +60692,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 +60706,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 +60723,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 +60741,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 +60753,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 +60768,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 +60779,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 +60845,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 +60861,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 +60877,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 +60889,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 +60905,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 +60919,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 +60931,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 +60943,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 +60957,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 +60971,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 +60983,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 +60996,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 +61011,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 +61026,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 +61040,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 +61053,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 +61074,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 +61158,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 +61170,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 +61182,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 +61197,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 +61213,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 +61236,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 +61251,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 +61293,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 +61394,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 +61905,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 +61917,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 +61945,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 +61957,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 +61970,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 +62027,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 +62042,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 +62053,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 +62065,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 +62311,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 +62339,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 +62360,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 +62394,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 +62409,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 +62446,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 +62481,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 +62497,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 +62512,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 +62547,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 +62564,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 +62589,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 +62627,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 +62638,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 +62668,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 +62696,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 +62725,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 +62746,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 +62777,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 +62785,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 +62807,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 +62872,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 +62891,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 +62994,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 +63006,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 +63042,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 +63059,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 +63071,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 +63083,7 @@ var ts; : propertyName; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -60945,7 +63098,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 +63106,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 +63152,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 +63317,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 +63628,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 +63688,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 +63701,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 +63709,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 +63760,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 +63885,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 +63893,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 +64099,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 +64149,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 +64186,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.getPositionOfLineAndCharacter(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.getPositionOfLineAndCharacter(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 +64825,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 +64871,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 +64879,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 +64915,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 +64929,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 +64949,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 +65301,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 +65368,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 +65565,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 +65596,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 +65652,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 +65673,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 +65721,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 +65745,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 +65771,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 +65805,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 +65827,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 +65844,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 +65915,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 +65926,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 +65964,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 +66029,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 +66098,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 +66300,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 +66308,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 +66356,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 +66476,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 +66547,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 +66558,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 +66575,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 +66687,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 +66845,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 +66946,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 +66968,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 +66981,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 +66992,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 +67014,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 +67059,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 +67104,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 +67216,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 +67227,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 +67260,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 +67281,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 +67289,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 +67310,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 +67399,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 +67797,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 +67878,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 +68008,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 +68054,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 +68101,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 +68295,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 +68314,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 +68322,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 +68332,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 +68401,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 +68417,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 +68443,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 +68557,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 +68585,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 +68615,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 +68836,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 +68849,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 +68893,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66378,15 +68921,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 +68954,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 +68979,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 +69015,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 +69086,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 +69104,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 +69132,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 +69154,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 +69164,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 +69248,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 +69260,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 +69269,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 +69280,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 +69312,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 +69327,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 +69344,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 +69441,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 +69538,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 +69592,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 +69612,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 +69645,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 +69670,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 +69706,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 +69819,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 +69833,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 +69909,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 +70010,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 +70316,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 +70324,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 +70376,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 +70554,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 +70579,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 +70763,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 +70781,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 +70800,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 +70937,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 +71042,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 +71081,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 +71093,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 +71151,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 +71159,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 +71230,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 +71307,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 +71359,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 +71378,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 +71424,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 +71547,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 +71629,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 +71674,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 +71712,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 +71742,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 +71763,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 +71800,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 +71837,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 +71905,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 +71974,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 +72161,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 +72192,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 +72220,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 +72234,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 +72250,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 +72329,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 +72606,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 +72677,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 +72718,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 +72839,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 +73018,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 +73055,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 +73073,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 +73120,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 +73237,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 +73335,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 +73372,7 @@ var ts; function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { enabledSubstitutions |= 2 /* BlockScopedBindings */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } /** @@ -70537,14 +73382,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 +73430,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 +73446,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 +73515,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 +73555,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 +73580,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 +73607,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 +73666,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 +73941,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 +73960,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 +73998,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 +74025,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 +74186,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 +74226,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 +74255,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 +74267,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 +74299,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 +74310,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 +74354,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 +74385,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 +74574,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 +74643,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 +75101,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 +75114,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 +75244,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 +75276,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 +75426,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 +76342,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 +76361,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 +76418,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 +76449,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 +76675,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 +76700,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 +76718,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 +76767,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 +77213,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 +77268,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 +77453,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 +77470,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 +77532,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 +77558,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 +77626,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 +77708,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 +77732,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 +77934,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 +77959,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 +78037,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 +78099,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 +78283,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 +78347,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 +78409,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 +78592,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 +78811,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 +78876,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 +78892,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 +78909,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 +78957,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -76140,12 +78991,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 +79082,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 +79118,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 +79157,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 +79186,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 +79296,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 +79325,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 +79372,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 +79381,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 +79391,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 +79416,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 +79455,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 +79482,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 +79496,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 +79521,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 +79552,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 +79565,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 +79580,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 +79622,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 +79659,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 +79689,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76856,6 +79707,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 +79717,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) { @@ -76937,15 +79789,16 @@ var ts; } } 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 +79810,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 +79847,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 +79860,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 +79897,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 +79905,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 +79926,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 +79948,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 +79961,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 +79973,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 +79986,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 +80006,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 +80022,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 +80095,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 +80115,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 +80142,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 +80247,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 +80316,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 +80334,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 +80369,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 +80379,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 +80388,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 +80404,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 +80418,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 +80442,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 +80495,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 +80506,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 +80536,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 +80545,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 +80565,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 +80587,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 242 /* ModuleDeclaration */) { + if (input.kind === 244 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -77720,7 +80608,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 +80671,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 +80692,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 +80706,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 +80744,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 +80753,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 +80863,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 +80882,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 +80890,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 +81140,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 +81182,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 +81224,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 +81244,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 +81267,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 +81340,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 +81362,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 +81377,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 +81388,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 +81432,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 +81519,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 +81562,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 +81574,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 +81587,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 +81602,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 +81627,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 +81654,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 +81680,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 +81748,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 +82036,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 +82131,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 +82174,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79975,7 +82186,8 @@ var ts; // Literals/Pseudo-literals // // SyntaxKind.NumericLiteral - function emitNumericLiteral(node) { + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { emitLiteral(node); } // SyntaxKind.StringLiteral @@ -79985,9 +82197,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 +82217,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 +82228,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -80052,7 +82264,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 +82286,7 @@ var ts; emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); @@ -80084,7 +82296,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 +82307,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitMethodDeclaration(node) { @@ -80114,7 +82326,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 +82338,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitConstructSignature(node) { @@ -80138,7 +82350,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitIndexSignature(node) { @@ -80146,10 +82358,10 @@ var ts; emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitSemicolonClassElement() { - writeSemicolon(); + writeTrailingSemicolon(); } // // Types @@ -80176,22 +82388,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 +82424,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 +82434,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 +82503,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 +82554,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 +82577,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 +82586,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 +82599,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 +82622,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 +82637,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 +82666,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 +82687,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 +82727,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,23 +82754,23 @@ 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); } @@ -80606,36 +82818,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 +82866,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 +82889,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 +82936,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 +82969,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 +83011,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 +83031,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 +83079,7 @@ var ts; } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } function emitSignatureHead(node) { @@ -80910,7 +83131,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 +83143,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 +83170,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 +83183,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 +83200,7 @@ var ts; writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); @@ -80988,7 +83209,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 +83221,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 +83237,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 +83262,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 +83295,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 +83343,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 +83369,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 +83381,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 +83396,6 @@ var ts; writePunctuation(">"); } function emitJsxText(node) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { @@ -81186,7 +83406,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 +83426,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81217,13 +83437,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 +83453,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 +83468,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); @@ -81305,6 +83525,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 +83680,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 +83738,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 +83778,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 +83813,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 131328 /* Modifiers */); + emitList(node, modifiers, 262656 /* Modifiers */); writeSpace(); } } @@ -81465,7 +83827,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 +83864,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 +83908,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 +83924,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 +83934,11 @@ var ts; writeSpace(); writePunctuation("|"); break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case 8 /* AmpersandDelimited */: writeSpace(); writePunctuation("&"); @@ -81575,11 +83949,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 +83962,7 @@ var ts; } return; } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { // TODO: GH#18217 @@ -81603,23 +83977,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 +84002,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 +84022,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 +84051,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 +84061,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 +84087,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 +84163,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 +84199,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 +84238,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 +84263,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 +84287,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 +84299,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 +84307,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 +84352,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 +84435,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 +84498,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 +84577,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82259,23 +84620,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 +84677,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 +85466,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 +85499,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 +85509,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 +85517,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 +85529,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 +85541,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 +85557,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 +85591,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 +85618,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 +85706,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 +85722,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 +85761,7 @@ var ts; } } ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { if (names.length === 0) { return []; } @@ -83034,7 +85774,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 +85784,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 +85793,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 +85818,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 +85859,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 +85892,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 +85920,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 +85940,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 +85965,33 @@ 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 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 +86005,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 +86030,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 +86080,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 +86119,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 +86148,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 +86164,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 +86217,7 @@ var ts; } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; @@ -83442,7 +86228,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 +86254,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 +86264,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 +86313,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 +86339,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 +86366,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 +86431,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 +86459,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 +86481,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 +86514,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 +86529,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 +86592,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 +86658,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 +86749,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -83969,22 +86759,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 +86782,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 +86829,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 +86890,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 +86955,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 +86982,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 +87012,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 +87062,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 +87108,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 +87164,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 +87186,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 +87252,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 +87265,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 +87299,85 @@ 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) { + 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) { + return forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (!referencedProject || + toPath(options.configFilePath) === referenceProjectPath || + !ts.contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + return referencedProject; }); - return result; + } + 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); + }); + } + 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 +87387,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 +87405,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 +87431,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 +87477,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 +87486,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 +87506,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 +87526,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 +87608,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 +87669,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 +87687,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 +87704,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 +87717,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 +87730,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 +87800,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 +87879,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 +87896,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 +87946,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 +87963,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 +88021,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 +88052,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 +88062,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 +88091,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 +88102,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 +88246,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 +88316,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 +88375,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 +88429,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 +88479,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 +88496,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 +88515,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 +88605,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 +88637,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 +88683,7 @@ var ts; */ function removeSemanticDiagnosticsOf(state, path) { if (!state.semanticDiagnosticsFromOldState) { - return false; + return true; } state.semanticDiagnosticsFromOldState.delete(path); state.semanticDiagnosticsPerFile.delete(path); @@ -85752,7 +88730,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 +88743,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 +88924,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 +88956,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 +88973,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 +89001,7 @@ var ts; resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -86073,7 +89063,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -86089,15 +89079,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 +89098,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 +89111,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 +89148,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 +89176,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 +89226,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 +89245,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 +89269,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 +89298,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 +89353,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 +89403,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 +89480,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 +89523,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 +89590,117 @@ 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 (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++; } - 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]; + return count; } 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 +89764,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 +89781,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 +89802,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 +89834,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 +89860,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 +89930,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 +89998,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 +90006,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 +90052,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 +90088,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 +90107,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 +90122,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 +90153,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 +90167,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 +90186,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 +90211,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 +90246,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 +90262,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 +90321,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 +90331,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 +90360,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 +90387,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 +90509,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 +90524,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 +90570,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 +90596,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 +90607,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 +90648,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 +90688,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 +90710,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 +90728,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 +90799,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 +90814,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 +90835,818 @@ 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); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - 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; + 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 invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); + } + /** + * 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; + // 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 }; 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); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + 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 +91682,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 +91694,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 +91839,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 +91868,6 @@ var ts; : undefined; } server.findArgument = findArgument; - /*@internal*/ function nowString() { // E.g. "12:34:56.789" var d = new Date(); @@ -88698,13 +91881,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 +91924,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 +91956,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 +92041,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 +92079,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 +92170,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; @@ -89104,6 +92219,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 +92306,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 +92391,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 +92404,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 +92451,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 +92469,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 +92509,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 +92560,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 +92576,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 +92605,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 +92642,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,12 +92650,19 @@ 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) { @@ -89512,40 +92670,40 @@ var ts; } ts.isLabelName = isLabelName; 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 +92727,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 +92745,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 +92813,7 @@ var ts; return "" /* unknown */; } } - case 71 /* Identifier */: + case 72 /* Identifier */: return ts.isImportClause(node.parent) ? "alias" /* alias */ : "" /* unknown */; default: return "" /* unknown */; @@ -89668,12 +92829,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 +92899,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 +92943,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 +93019,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 +93154,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 +93172,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 +93181,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 +93243,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 +93275,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 +93335,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 +93345,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 +93424,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 +93447,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 +93461,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 +93470,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 +93480,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 +93495,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 +93514,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 +93538,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 +93546,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 +93558,21 @@ 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 */, + 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 +93608,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 +93684,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 +93750,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 +93773,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 +93799,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 +93808,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 +93959,6 @@ var ts; return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; - /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -90819,7 +93993,7 @@ var ts; ts.signatureToDisplayParts = signatureToDisplayParts; function isImportOrExportSpecifierName(location) { return !!location.parent && - (location.parent.kind === 251 /* ImportSpecifier */ || location.parent.kind === 255 /* ExportSpecifier */) && + (location.parent.kind === 253 /* ImportSpecifier */ || location.parent.kind === 257 /* ExportSpecifier */) && location.parent.propertyName === location; } ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; @@ -90866,6 +94040,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 +94064,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 +94072,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 +94087,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 +94113,6 @@ var ts; /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ - /* @internal */ function suppressLeadingAndTrailingTrivia(node) { suppressLeadingTrivia(node); suppressTrailingTrivia(node); @@ -90941,7 +94121,6 @@ var ts; /** * Sets EmitFlags to suppress leading trivia on the node. */ - /* @internal */ function suppressLeadingTrivia(node) { addEmitFlagsRecursively(node, 512 /* NoLeadingComments */, getFirstChild); } @@ -90949,7 +94128,6 @@ var ts; /** * Sets EmitFlags to suppress trailing trivia on the node. */ - /* @internal */ function suppressTrailingTrivia(node) { addEmitFlagsRecursively(node, 1024 /* NoTrailingComments */, ts.getLastChild); } @@ -90963,7 +94141,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 +94154,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 +94207,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 +94311,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 +94353,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 +94420,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 +94442,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 +94482,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 +94516,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 +94525,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 +94539,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 +94566,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 +94602,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 +94646,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 +94664,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 +94683,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 +94708,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 +94786,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 +94920,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 +95006,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 +95022,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 +95054,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 +95064,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 +95085,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 +95100,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 +95165,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) { @@ -91968,21 +95426,22 @@ var ts; // 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); } - function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, extensions, includeExtensions, compilerOptions, host, exclude) { + function getCompletionEntriesForDirectoryFragmentWithRootDirs(rootDirs, fragment, scriptPath, 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); + getCompletionEntriesForDirectoryFragment(fragment, baseDirectory, extensionOptions, 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, 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 +95462,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 +95543,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 +95599,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 +95627,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 +95675,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 +95731,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 +95806,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 +95850,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 +95866,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 +95897,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 +95910,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 +95922,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 +95930,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 +95958,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 +95975,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 +95990,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 +96031,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 +96068,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 +96099,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 +96137,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 +96181,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 +96216,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 +96230,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 +96267,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 +96318,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 +96348,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 +96369,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 +96396,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 +96467,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 +96476,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 +96493,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 +96537,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 +96566,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 +96614,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 +96666,10 @@ var ts; position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; isInSnippetScope = isSnippetScope(scopeNode); - var symbolMeanings = 67901928 /* Type */ | 67216319 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; + var symbolMeanings = 67897832 /* Type */ | 67220415 /* Value */ | 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,21 +96694,21 @@ 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); @@ -93423,7 +96718,7 @@ var ts; 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 */; + 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 @@ -93444,46 +96739,40 @@ var ts; } } // expressions are value space (which includes the value namespaces) - return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67216319 /* Value */); + return !!(ts.getCombinedLocalAndExportSymbolFlags(symbol) & 67220415 /* Value */); }); } 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 +96787,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 +96863,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 +96881,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 +96942,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 +96962,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 +97003,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 +97032,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 +97067,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 +97096,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 +97127,17 @@ 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 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 */)) { return parent; } - else if (parent.kind === 265 /* JsxAttribute */) { + else if (parent.kind === 267 /* JsxAttribute */) { // Currently we parse JsxOpeningLikeElement as: // JsxOpeningLikeElement // attributes: JsxAttributes @@ -93843,8 +97148,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 +97157,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 +97168,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 +97187,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 +97266,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 +97291,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 +97314,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 +97329,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 +97354,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 +97397,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 +97441,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 +97456,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 +97476,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 +97505,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 +97528,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 +97560,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 +97569,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 +97585,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 +97637,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 +97713,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 +97745,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 +97770,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 +97782,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 +97818,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 +97831,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 +97840,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 +97854,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 +97868,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 +97885,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 +97903,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 +97919,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 +97940,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 +97959,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 +97994,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 +98030,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 +98065,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 +98081,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 +98119,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 +98147,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 +98213,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 +98227,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 +98252,7 @@ var ts; directImports.push(direct); } break; - case 181 /* ImportType */: + case 183 /* ImportType */: directImports.push(direct); break; default: @@ -94995,7 +98269,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 +98324,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 +98346,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 +98409,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 +98435,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 +98466,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 +98486,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 +98501,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 +98533,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) @@ -95312,7 +98586,7 @@ var ts; } function getSpecialPropertyExport(node, useLhsSymbol) { var kind; - switch (ts.getSpecialPropertyAssignmentKind(node)) { + switch (ts.getAssignmentDeclarationKind(node)) { case 1 /* ExportsProperty */: kind = 0 /* Named */; break; @@ -95381,10 +98655,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,15 +98667,15 @@ var ts; function isNodeImport(node) { var parent = node.parent; switch (parent.kind) { - case 246 /* ImportEqualsDeclaration */: + case 248 /* ImportEqualsDeclaration */: return parent.name === node && isExternalModuleImportEquals(parent) ? { isNamedImport: false } : undefined; - case 251 /* ImportSpecifier */: + 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 */: + case 250 /* ImportClause */: + case 251 /* NamespaceImport */: ts.Debug.assert(parent.name === node); return { isNamedImport: false }; default: @@ -95434,21 +98708,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 +98731,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 +98774,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 +98796,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); }); } - 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 +98812,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 +98847,65 @@ 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) { + return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode)); + } + 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) { + 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)) { + if (kind === 3 /* SearchedLocalFoundProperty */) { + return { prefixText: name + ": " }; + } + else if (kind === 4 /* SearchedPropertyFoundLocal */) { + return { suffixText: ": " + name }; + } + else { + return isShorthandAssignment + // In `const o = { x }; o.x`, symbolAtLocation at `x` in `{ x }` is the property symbol. + ? { suffixText: ": " + name } + // For a binding element `const { x } = o;`, symbolAtLocation at `x` is the property symbol. + : { prefixText: 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 +98920,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 +98937,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 +98955,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 +98963,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 +99051,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 +99085,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 +99098,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 +99111,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,7 +99148,7 @@ 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; @@ -95758,12 +99160,12 @@ var ts; 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 */) { + 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 +99185,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 */; @@ -95894,15 +99296,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. */ @@ -96005,19 +99407,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 +99419,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 +99429,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 +99451,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 +99479,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 +99503,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 +99561,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 +99588,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 +99639,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; } @@ -96303,7 +99694,7 @@ 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 exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportInfo = FindAllReferences.getExportInfo(referenceSymbol, exportKind, state.checker); if (!exportInfo) return ts.Debug.fail(); @@ -96367,12 +99758,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 +99774,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 +99800,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 +99817,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 +99843,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 +99860,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 +99883,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 +99911,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 +99970,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 +99985,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 +99994,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 +100036,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 +100062,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 +100092,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 +100124,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 +100138,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 +100176,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 +100239,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 +100254,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 +100273,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 +100291,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 +100343,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 +100371,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 +100401,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 +100431,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 +100473,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 +100485,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 +100493,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 +100646,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 +100667,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 +100739,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 +100861,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 +100886,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 +100959,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97575,7 +100992,7 @@ var ts; kindModifiers: "", displayParts: [ts.textPart(name)], documentation: ts.emptyArray, - tags: ts.emptyArray, + tags: undefined, codeActions: undefined, }; } @@ -97638,7 +101055,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 +101072,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 +101082,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 +101106,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 +101132,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 +101158,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 +101168,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 +101183,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 +101201,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 +101213,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 +101230,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 +101399,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 +101411,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 +101437,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 +101448,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 +101470,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 +101485,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 +101495,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 +101518,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 +101588,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 +101609,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 +101639,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 +101647,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 +101666,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 +101683,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 +101713,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 +101741,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 +101753,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 +101810,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 +101824,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 +102012,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 +102111,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 +102214,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 +102321,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 +102353,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 +102383,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 +102392,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 +102689,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 +102753,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 +102897,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 +102930,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 +102947,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 +102991,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 +103010,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 +103034,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 +103056,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 +103083,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 +103098,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 +103116,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 +103232,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 +103295,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 +103332,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 +103366,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 +103390,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 +103419,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 +103442,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 +103495,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 +103561,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 +103610,7 @@ var ts; if (child === node) { break; } - if (child.kind !== 26 /* CommaToken */) { + if (child.kind !== 27 /* CommaToken */) { argumentIndex++; } } @@ -100160,8 +103629,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 +103699,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 +103707,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 +103717,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 +103733,13 @@ var ts; function getExpressionFromInvocation(invocation) { return invocation.kind === 0 /* Call */ ? ts.getInvokedExpression(invocation.node) : invocation.called; } + function getEnclosingDeclarationFromInvocation(invocation) { + return invocation.kind === 0 /* Call */ ? invocation.node : invocation.kind === 1 /* TypeArgs */ ? invocation.called : invocation.node; + } var signatureHelpNodeBuilderFlags = 8192 /* OmitParameterModifiers */ | 3112960 /* 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 +103750,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 +103796,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 +103806,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 +103825,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 +103900,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 +103927,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 +103973,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 +104001,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 +104011,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 +104044,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 +104065,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 +104148,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 +104185,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 +104236,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 +104265,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 +104283,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 +104304,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 +104322,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 +104339,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 +104359,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 +104391,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 +104399,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 +104407,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 +104456,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 +104464,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 +104490,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 +104520,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 +104568,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 +104579,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 +104617,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 +104642,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 +104663,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 +104673,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 +104696,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 +104707,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 +104733,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 +104782,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 +104856,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 +104875,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; } @@ -101431,8 +104957,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 +105040,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 +105052,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 +105143,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 +105159,7 @@ var ts; } break; case 3 /* RescanTemplateToken */: - if (token === 18 /* CloseBraceToken */) { + if (token === 19 /* CloseBraceToken */) { lastScanAction = 3 /* RescanTemplateToken */; return scanner.reScanTemplateToken(); } @@ -101706,7 +105232,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 +105244,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 +105536,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 +105586,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 +105627,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 +105660,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 +105702,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 +105774,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 +105823,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 +105883,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 +105977,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 +106008,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 +106066,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 +106189,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 +106218,7 @@ var ts; var previousParent; var previousRangeStartLine; var lastIndentedLine; - var indentationOnLastIndentedLine; + var indentationOnLastIndentedLine = -1 /* Unknown */; var edits = []; formattingScanner.advance(); if (formattingScanner.isOnToken()) { @@ -102707,7 +106232,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 +106277,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 +106298,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 +106325,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 +106357,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 +106460,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 +106496,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 +106525,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 +106571,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 +106589,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 +106793,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 +106896,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 +107040,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 +107062,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 +107100,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 +107133,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 +107194,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 +107211,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 +107242,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 +107251,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 +107340,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 +107389,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 +107476,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 +107608,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 = ""; @@ -104142,13 +107680,16 @@ var ts; if (options === void 0) { options = textChanges_3.useNonAdjustedPositions; } return 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); }; 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); @@ -104156,11 +107697,11 @@ var ts; }; 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 +107716,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 +107739,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 +107773,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 +107820,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 +107873,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 +107885,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 +107905,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: " " }); } }; @@ -104427,7 +107998,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 +108014,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 +108030,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 +108038,29 @@ 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 +108073,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 +108112,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 +108130,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 +108147,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 +108196,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 +108281,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 +108296,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 +108320,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 +108361,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 +108395,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 +108418,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 +108459,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 +108474,7 @@ var ts; deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } break; - case 249 /* NamespaceImport */: + case 251 /* NamespaceImport */: deleteImportBinding(changes, sourceFile, node); break; default: @@ -104888,7 +108485,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 +108499,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 +108521,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 +108538,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 +108690,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 +108783,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 +108795,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 +108810,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 +108851,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 +108891,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 +108902,754 @@ 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 isConstructor = declaration.kind === 157 /* Constructor */; + var callContexts = isConstructor ? usageContext.constructContexts : usageContext.callContexts; + return callContexts && 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)) { + types.push.apply(types, inferTypesFromReferences(getReferences(parameter.name, program, cancellationToken), checker, cancellationToken)); + } + 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.isNumber = true; + usageContext.isString = 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.isNumber = true; + usageContext.isString = 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.isNumber = true; + usageContext.isString = 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 unifyFromContext(inferences, checker, fallback) { + if (fallback === void 0) { fallback = checker.getAnyType(); } + if (!inferences.length) + return fallback; + var hasNonVacuousType = inferences.some(function (i) { return !(i.flags & (1 /* Any */ | 16384 /* Void */)); }); + var hasNonVacuousNonAnonymousType = inferences.some(function (i) { return !(i.flags & (98304 /* Nullable */ | 1 /* Any */ | 16384 /* Void */)) && !(checker.getObjectFlags(i) & 16 /* Anonymous */); }); + var anons = inferences.filter(function (i) { return checker.getObjectFlags(i) & 16 /* Anonymous */; }); + var good = []; + if (!hasNonVacuousNonAnonymousType && anons.length) { + good.push(unifyAnonymousTypes(anons, checker)); + } + good.push.apply(good, inferences.filter(function (i) { return !(checker.getObjectFlags(i) & 16 /* Anonymous */) && !(hasNonVacuousType && i.flags & (1 /* Any */ | 16384 /* Void */)); })); + 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()); + } + 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) { + return [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 +109674,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 +109711,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 +109734,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 +109742,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 +109770,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 +109783,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 +109804,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 +109823,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 +109934,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 +109948,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 +109962,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 +109988,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 +110011,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 +110021,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 +110055,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 +110071,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 +110098,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 +110114,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 +110127,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 +110275,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 +110282,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 +110342,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 +110371,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 +110391,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 +110453,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 +110462,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 +110488,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 +110505,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 +110563,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 +110587,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 +110608,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 +110619,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 +110630,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 +110702,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 +110974,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 +111045,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 +111068,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 +111093,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 +111127,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 +111175,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 +111191,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 +111214,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 +111423,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 +111457,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 +111483,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 +111502,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 +111531,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 +111558,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 +111602,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 +111612,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 +111645,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 +111664,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 +111688,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 +111708,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 +111724,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 +111736,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 +111748,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 +111973,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 +112012,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 +112050,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 +112144,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 +112164,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 +112196,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 +112205,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 +112215,7 @@ var ts; break; } case fixIdInfer: - if (token.kind === 126 /* InferKeyword */) { + if (token.kind === 127 /* InferKeyword */) { changeInferToUnknown(changes, sourceFile, token); } break; @@ -107659,7 +112226,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 +112236,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 +112253,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 +112262,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 +112271,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 +112292,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 +112310,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 +112384,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 +112395,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 +112445,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 +112469,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 +112489,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 +112506,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 +112575,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 +112597,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 +112620,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 +112691,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 +112719,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 +112741,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 +112785,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 +112800,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 +112814,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 +112829,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 +112838,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 +112849,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 +112881,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 +112992,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 +113000,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 +113021,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 +113046,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 +113370,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 +113423,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 +113443,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 +113470,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 +113502,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 +113520,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 +113549,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 +113569,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 +113590,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 +113639,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 +113663,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 +113723,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 +113742,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 +113771,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 +113832,7 @@ var ts; actions: constantActions }); } - return infos.length ? infos : undefined; + return infos.length ? infos : ts.emptyArray; } extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ @@ -109764,20 +114006,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 +114062,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 +114074,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 +114095,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 +114108,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 +114133,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 +114145,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 +114156,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 +114223,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 +114234,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 +114324,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 +114368,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 +114415,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 +114445,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 +114569,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 +114584,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 +114594,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 +114627,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 +114646,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 +114733,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 +114903,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 +114911,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 +114974,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 +115014,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 +115227,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 +115271,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 +115288,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 +115299,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); @@ -111098,7 +115340,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,7 +115363,7 @@ var ts; isStatic: ts.hasStaticModifier(declaration), isReadonly: ts.hasReadonlyModifier(declaration), type: ts.getTypeAnnotationNode(declaration), - container: declaration.kind === 149 /* Parameter */ ? declaration.parent.parent : declaration.parent, + container: declaration.kind === 151 /* Parameter */ ? declaration.parent.parent : declaration.parent, originalName: declaration.name, declaration: declaration, fieldName: fieldName, @@ -111178,7 +115420,7 @@ var ts; 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; + return (entry.kind !== 0 /* Span */ && 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; @@ -111203,7 +115445,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 +115507,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 +115564,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 +115589,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 +115635,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 +115718,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 +115739,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 +115751,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 +115764,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 +115876,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 +115894,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 +115904,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 +115915,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 +115925,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 +115986,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 +116000,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 +116067,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 +116096,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 +116115,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 +116137,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 +116179,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 +116215,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 +116288,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 +116300,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 +116346,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 +116358,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 +116490,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 +116536,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 +116604,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 +116691,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 +116714,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 +116749,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 +116773,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 +116782,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 +117095,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 +117125,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 +117164,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 +117176,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 +117189,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 +117214,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 +117304,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 +117347,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 +117371,15 @@ var ts; } function shouldGetType(sourceFile, node, position) { switch (node.kind) { - case 71 /* Identifier */: + case 72 /* Identifier */: return !ts.isLabelName(node); - case 187 /* PropertyAccessExpression */: - case 146 /* QualifiedName */: + 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 +117417,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 +117425,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 +117486,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 +117511,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 +117573,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 +117652,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 +117716,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: "" }; @@ -113700,7 +117975,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 +117990,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 +118040,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 +118120,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 +118269,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 +118285,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 +118322,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 +118344,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 +118374,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 +118386,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 +118427,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 +118450,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 +118494,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 +118516,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 +118535,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 +118561,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 +118577,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 +118592,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 +118606,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 +118630,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 +118651,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 +118749,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 +118759,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); }); }; } } diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index dd81fe55ced..f29014039b1 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.2"; /** 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) { @@ -2628,6 +3070,7 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName"; NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType"; + /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 67108864] = "DoNotIncludeSymbolChain"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; @@ -2678,6 +3121,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 +3154,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 +3193,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 +3299,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 +3317,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 +3347,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 +3416,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 +3428,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 +3460,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 +3480,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 +3741,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 +3774,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 +3871,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 +3886,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 +4038,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 +4255,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 +4590,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 +5206,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 +5245,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."), @@ -4850,14 +5306,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'."), @@ -5037,7 +5493,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 +5520,14 @@ 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."), 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 +5619,14 @@ 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}'."), 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 +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."), @@ -5363,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}'."), @@ -5461,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}"), @@ -5491,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."), @@ -5501,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."), @@ -5528,6 +6014,14 @@ 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."), 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 +6052,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."), @@ -5686,150 +6181,105 @@ 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"), }; })(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 :: @@ -6407,6 +6857,7 @@ var ts; var token; var tokenValue; var tokenFlags; + var inJSDocType = 0; setText(text, start, length); return { getStartPos: function () { return startPos; }, @@ -6417,8 +6868,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 +6887,7 @@ var ts; setLanguageVariant: setLanguageVariant, setOnError: setOnError, setTextPos: setTextPos, + setInJSDocType: setInJSDocType, tryScan: tryScan, lookAhead: lookAhead, scanRange: scanRange, @@ -6511,18 +6963,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 +7000,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 +7032,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 +7101,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 +7109,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 +7209,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 +7292,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 +7325,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 +7402,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 +7433,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 +7564,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 +7621,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 +7641,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 +7667,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 +7687,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 +7717,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 +7770,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 +7837,7 @@ var ts; } pos = p; tokenValue = text.substring(tokenPos, pos); - token = 12 /* RegularExpressionLiteral */; + token = 13 /* RegularExpressionLiteral */; } return token; } @@ -7349,7 +7845,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 +7862,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 +7901,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 +7927,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 +7951,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,6 +8064,9 @@ var ts; tokenValue = undefined; tokenFlags = 0; } + function setInJSDocType(inType) { + inJSDocType += inType ? 1 : -1; + } } ts.createScanner = createScanner; })(ts || (ts = {})); @@ -7588,7 +8087,6 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7635,7 +8133,6 @@ var ts; getText: function () { return str; }, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -7644,7 +8141,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 +8169,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 +8276,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 +8342,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 +8350,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 +8488,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 +8506,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 +8546,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 +8599,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 +8631,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 +8652,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 +8670,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 +8695,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 +8707,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 +8735,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 +8745,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 +8783,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 +8798,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 +8847,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 +8861,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 +8870,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 +8924,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 +8937,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 +8949,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 +8978,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 +9028,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 +9086,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 +9112,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 +9154,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 +9167,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 +9180,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 +9199,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 +9211,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 +9228,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 +9236,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 +9259,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 +9296,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 +9318,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 +9331,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 +9360,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 +9384,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 +9420,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 +9438,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 +9447,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 +9468,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 +9480,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 +9514,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 +9526,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 +9536,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 +9596,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 +9646,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 +9655,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 +9683,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 +9709,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 +9739,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 +9796,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 +9844,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 +9859,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 +9888,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 +9926,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 +9957,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 +9966,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 +9980,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 +9989,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 +10006,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 +10020,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 +10032,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 +10052,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 +10068,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 +10098,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 +10113,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 +10128,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 +10143,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 +10166,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 +10201,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 +10214,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 +10265,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 +10297,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 +10341,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 +10381,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 +10421,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 +10439,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 +10450,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 +10467,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 +10501,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 +10517,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 +10540,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 +10561,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 +10589,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 +10605,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 +10626,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 +10637,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 +10656,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 +10665,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 +10677,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 +10704,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 +10744,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 +10762,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 +10939,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 +10997,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 +11080,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 +11106,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 +11239,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 +11253,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 +11312,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 +11327,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 +11350,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 +11374,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 +11390,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 +11399,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 +11433,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 +11451,7 @@ var ts; } } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -10943,7 +11569,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 +11578,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 +11639,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 +11647,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 +11697,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 +11707,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 +11720,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 +11742,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 +11884,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 +11996,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 +12095,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 +12173,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 +12304,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) { @@ -11769,13 +12439,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 +12575,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 +12585,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 +12615,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 +12766,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 +12812,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 +12875,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 +12903,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 +13043,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 +13077,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 +13769,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 +13779,7 @@ var ts; ts.isNode = isNode; /* @internal */ function isNodeKind(kind) { - return kind >= 146 /* FirstNode */; + return kind >= 148 /* FirstNode */; } ts.isNodeKind = isNodeKind; /** @@ -13091,7 +13788,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 +13800,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 +13810,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 +13819,12 @@ 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 isStringTextContainingNode(node) { - return node.kind === 9 /* StringLiteral */ || isTemplateLiteralKind(node.kind); + return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind); } ts.isStringTextContainingNode = isStringTextContainingNode; // Identifiers @@ -13140,17 +13837,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 +13860,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 +13869,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 +13900,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 +13915,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 +13937,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 +13969,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,37 +13982,38 @@ 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 */; + 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 */; } /** * Node test that determines whether a node is a valid type node. @@ -13328,8 +14026,8 @@ var ts; 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 +14038,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 +14047,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 +14064,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 +14087,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 +14100,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 +14110,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 +14137,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 +14153,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 +14193,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 +14208,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 +14229,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 +14245,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 +14267,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 +14281,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 +14305,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 +14438,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 +14451,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 +14555,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 +14589,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 +14641,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 +14672,6 @@ var ts; }; } ts.createFileDiagnostic = createFileDiagnostic; - /* @internal */ function formatMessage(_dummy, message) { var text = getLocaleSpecificMessage(message); if (arguments.length > 2) { @@ -14000,7 +14696,6 @@ var ts; }; } ts.createCompilerDiagnostic = createCompilerDiagnostic; - /* @internal */ function createCompilerDiagnosticFromMessageChain(chain) { return { file: undefined, @@ -14037,14 +14732,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 +14798,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 +14826,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 +14839,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 +15041,6 @@ var ts; return rootLength > 0 && rootLength === path.length; } ts.isDiskPathRoot = isDiskPathRoot; - /* @internal */ function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { return !isRootedDiskPath(absoluteOrRelativePath) ? absoluteOrRelativePath @@ -14414,8 +15118,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 +15339,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 +15406,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 +15633,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 +15811,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 +15989,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 +16100,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 +16152,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 +16182,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,357 +16190,358 @@ 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 */: + case 299 /* JSDocParameterTag */: + case 305 /* JSDocPropertyTag */: if (node.isNameFirst) { return visitNode(cbNode, node.name) || visitNode(cbNode, node.typeExpression); @@ -15725,17 +16550,17 @@ var ts; return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.name); } - case 298 /* JSDocReturnTag */: + case 300 /* JSDocReturnTag */: return visitNode(cbNode, node.typeExpression); - case 300 /* JSDocTypeTag */: + case 302 /* JSDocTypeTag */: return visitNode(cbNode, node.typeExpression); - case 293 /* JSDocAugmentsTag */: + case 295 /* JSDocAugmentsTag */: return visitNode(cbNode, node.class); - case 301 /* JSDocTemplateTag */: + case 303 /* JSDocTemplateTag */: return visitNode(cbNode, node.constraint) || visitNodes(cbNode, cbNodes, node.typeParameters); - case 302 /* JSDocTypedefTag */: + case 304 /* JSDocTypedefTag */: if (node.typeExpression && - node.typeExpression.kind === 281 /* JSDocTypeExpression */) { + node.typeExpression.kind === 283 /* JSDocTypeExpression */) { return visitNode(cbNode, node.typeExpression) || visitNode(cbNode, node.fullName); } @@ -15743,20 +16568,20 @@ var ts; return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); } - case 295 /* JSDocCallbackTag */: + case 297 /* JSDocCallbackTag */: return visitNode(cbNode, node.fullName) || visitNode(cbNode, node.typeExpression); - case 299 /* JSDocThisTag */: + case 301 /* JSDocThisTag */: return visitNode(cbNode, node.typeExpression); - case 296 /* JSDocEnumTag */: + case 298 /* JSDocEnumTag */: return visitNode(cbNode, node.typeExpression); - case 291 /* JSDocSignature */: + case 293 /* JSDocSignature */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || ts.forEach(node.typeParameters, cbNode) || ts.forEach(node.parameters, cbNode) || visitNode(cbNode, node.type); - case 290 /* JSDocTypeLiteral */: + case 292 /* JSDocTypeLiteral */: if (node.jsDocPropertyTags) { for (var _i = 0, _a = node.jsDocPropertyTags; _i < _a.length; _i++) { var tag = _a[_i]; @@ -15764,7 +16589,7 @@ var ts; } } return; - case 306 /* PartiallyEmittedExpression */: + case 308 /* PartiallyEmittedExpression */: return visitNode(cbNode, node.expression); } } @@ -15774,7 +16599,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 +16768,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 +16807,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 +16826,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 +16963,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 +17168,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 +17224,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 +17288,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 +17309,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 +17320,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 +17330,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 +17351,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 +17372,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 +17396,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 +17425,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 +17435,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 +17472,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 +17513,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 +17530,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 +17559,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 +17609,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 +17779,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 +17801,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 +17811,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 +17883,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 +17940,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 +17950,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 +18007,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 +18019,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 +18050,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 +18086,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 +18118,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 +18143,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 +18164,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 +18182,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 +18260,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 +18307,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 +18329,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 +18359,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 +18372,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 +18385,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 +18413,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 +18432,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 +18476,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 +18486,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 +18497,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 +18522,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 +18554,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 +18649,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 +18732,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 +18779,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 +18824,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 +18841,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 +18864,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 +18894,7 @@ var ts; } function isUnambiguouslyStartOfFunctionType() { nextToken(); - if (token() === 20 /* CloseParenToken */ || token() === 24 /* DotDotDotToken */) { + if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) { // ( ) // ( ... return true; @@ -18057,17 +18902,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 +18924,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 +18935,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 +18946,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 +19000,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 +19029,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 +19046,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 +19055,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 +19100,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 +19116,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 +19145,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 +19164,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 +19202,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 +19213,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 +19226,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 +19259,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 +19302,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 +19312,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 +19341,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 +19354,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 +19380,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 +19391,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 +19428,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 +19449,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 +19478,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 +19508,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 +19562,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 +19586,7 @@ var ts; */ if (isUpdateExpression()) { var updateExpression = parseUpdateExpression(); - return token() === 40 /* AsteriskAsteriskToken */ ? + return token() === 41 /* AsteriskAsteriskToken */ ? parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression) : updateExpression; } @@ -18757,10 +19603,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 +19631,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 +19670,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 +19702,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 +19757,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 +19772,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 +19783,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 +19842,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 +19866,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 +19885,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 +19901,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 +19918,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 +19947,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 +19964,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 +19994,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 +20005,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 +20042,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 +20116,7 @@ var ts; } indexedAccess.argumentExpression = argument; } - parseExpected(22 /* CloseBracketToken */); + parseExpected(23 /* CloseBracketToken */); expression = finishNode(indexedAccess); continue; } @@ -19282,13 +20128,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 +20142,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 +20155,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 +20173,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 +20195,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 +20234,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 +20258,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 +20335,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 +20371,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 +20382,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 +20394,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 +20413,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 +20456,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 +20509,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 +20543,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 +20551,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 +20560,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 +20607,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 +20642,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 +20653,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 +20671,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 +20712,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 +20759,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 +20812,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 +20821,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 +20890,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 +20909,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 +20944,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 +20955,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 +20966,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 +20992,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 +21021,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 +21034,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 +21057,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 +21069,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 +21126,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 +21139,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 +21162,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 +21172,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 +21207,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 +21230,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 +21249,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 +21259,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 +21282,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 +21330,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 +21342,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 +21376,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 +21390,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 +21409,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 +21420,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 +21442,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 +21452,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 +21525,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 +21534,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 +21545,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 +21568,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 +21583,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 +21604,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 +21615,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 +21640,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 +21660,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 +21676,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 +21727,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 +21819,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 +21839,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 +21852,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 +21866,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 +21890,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 +21924,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 +22007,7 @@ var ts; } indent = 0; break; - case 57 /* AtToken */: + case 58 /* AtToken */: scanner.setTextPos(scanner.getTextPos() - 1); // falls through case 1 /* EndOfFileToken */: @@ -21184,9 +22026,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 +22036,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 +22056,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 +22076,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 +22116,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 +22132,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 +22155,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 +22234,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 +22251,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 +22269,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 +22283,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 +22333,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 +22357,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 +22371,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 +22396,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 +22433,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 +22450,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 +22580,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 +23160,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 +23220,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 +23237,7 @@ var ts; /* @internal */ ts.libMap = ts.createMapFromEntries(libEntries); /* @internal */ - ts.optionDeclarations = [ - // CommandLine only options + ts.commonOptionsWithBuild = [ { name: "help", shortName: "h", @@ -22427,6 +23251,49 @@ 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 + }, + ]; + /* @internal */ + ts.optionDeclarations = ts.commonOptionsWithBuild.concat([ { name: "all", type: "boolean", @@ -22468,26 +23335,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 +23355,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 +23375,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 +23388,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 +23396,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 +23414,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 +23524,7 @@ var ts; { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22674,6 +23533,7 @@ var ts; { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22682,14 +23542,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 +23568,7 @@ var ts; { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22706,6 +23577,7 @@ var ts; { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Strict_Type_Checking_Options, @@ -22739,6 +23611,7 @@ var ts; { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: ts.Diagnostics.Additional_Checks, @@ -22751,6 +23624,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 +23632,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 +23642,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 +23658,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 +23670,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 +23681,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 @@ -22887,30 +23766,12 @@ var ts; 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 +23830,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 +23850,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 +23896,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 +23904,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 +23932,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 +23960,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 +24051,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 +24101,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 +24121,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 +24129,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 +24165,7 @@ var ts; } } else { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, s)); + errors.push(ts.createCompilerDiagnostic(unknownOptionDiagnostic, s)); } } else { @@ -23303,9 +24208,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 +24233,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 +24388,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 +24530,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 +24578,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 +24612,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 +24635,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 +24675,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 +24794,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 +24942,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 +24960,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 +25011,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 +25030,6 @@ var ts; }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -24027,17 +25043,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 +25155,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 +25182,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 +25213,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 +25427,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 +25452,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 +25470,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 +25496,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 +25507,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 +25649,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 +25705,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 +25720,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 +25737,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 +25869,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 +25894,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 +25906,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 +25920,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 +25943,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 +25990,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 +26012,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 +26136,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 +26170,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 +26182,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 +26257,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 +26316,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 +26335,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 +26346,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 +26425,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 +26442,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 +26473,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 +26519,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 +26568,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 +26592,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 +26630,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 +26642,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 +26719,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 +26728,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 +26858,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 +26871,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 +26948,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 +26979,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 +27018,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 +27165,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 +27190,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 +27202,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 +27300,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 +27329,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 +27356,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 +27379,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 +27423,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 +27455,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 +27468,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 +27517,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 +27547,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 +27633,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 +27667,7 @@ var ts; } } } - if (expr.expression.kind === 187 /* PropertyAccessExpression */ && + if (expr.expression.kind === 189 /* PropertyAccessExpression */ && isNarrowableReference(expr.expression.expression)) { return true; } @@ -26465,32 +27681,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 +27741,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 +27780,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 +27848,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 +27882,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 +27910,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 +27930,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 +28026,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 +28050,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 +28093,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 +28111,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 +28122,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 +28139,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 +28150,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 +28160,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 +28187,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 +28198,7 @@ var ts; } function bindDeleteExpressionFlow(node) { bindEachChild(node); - if (node.expression.kind === 187 /* PropertyAccessExpression */) { + if (node.expression.kind === 189 /* PropertyAccessExpression */) { bindAssignmentTargetFlow(node.expression); } } @@ -27030,10 +28245,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 +28256,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 +28265,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 +28345,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 +28404,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 +28436,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 +28445,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 +28465,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 +28492,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 +28504,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 +28536,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 +28553,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 +28570,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 +28588,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 +28625,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 +28636,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 +28677,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 +28704,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 +28773,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 +28797,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 +28835,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 +28844,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 +28893,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 +29073,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 +29128,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 +29152,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 +29179,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 +29202,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 +29222,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 +29239,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 +29260,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 +29294,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 +29344,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 (ts.isCallExpression(node)) { + return !!ts.getAssignedExpandoInitializer(node); + } var init = !node ? undefined : ts.isVariableDeclaration(node) ? node.initializer : ts.isBinaryExpression(node) ? node.right : @@ -28103,7 +29360,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 +29402,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 +29444,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 +29460,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 +29480,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 +29498,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 +29539,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 +29573,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 +29615,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 +29652,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 +29666,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 +29730,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 +29795,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 +29823,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 +29848,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 +29894,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 +29905,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 +29917,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 +29927,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 +29947,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 +29958,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 +29972,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 +29984,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 +29999,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 +30012,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 +30031,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 +30047,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 +30063,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 +30080,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 +30109,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 +30130,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 +30141,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 +30165,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 +30176,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 +30185,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 +30266,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 +30337,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 +30436,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 +30558,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 +30574,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 +30672,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 +30715,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 +30747,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 +30757,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"); @@ -29655,10 +30938,6 @@ var ts; 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); @@ -29683,14 +30962,15 @@ var ts; createPromiseType: createPromiseType, createArrayType: createArrayType, 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 +30978,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 +31032,8 @@ var ts; finally { cancellationToken = undefined; } - } + }, + getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias, }; function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, isForSignatureHelp) { var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression); @@ -29775,24 +31056,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 +31105,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 +31128,8 @@ var ts; var patternAmbientModules; var globalObjectType; var globalFunctionType; + var globalCallableFunctionType; + var globalNewableFunctionType; var globalArrayType; var globalReadonlyArrayType; var globalStringType; @@ -29846,6 +31148,7 @@ var ts; var deferredGlobalESSymbolType; var deferredGlobalTypedPropertyDescriptorType; var deferredGlobalPromiseType; + var deferredGlobalPromiseLikeType; var deferredGlobalPromiseConstructorSymbol; var deferredGlobalPromiseConstructorLikeType; var deferredGlobalIterableType; @@ -29857,7 +31160,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 +31170,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 +31196,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 +31309,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 +31446,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 +31507,10 @@ 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); + target = cloneSymbol(resolveSymbol(target)); } // 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 +31520,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 +31541,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 +31606,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 +31669,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 +31699,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 +31727,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 +31756,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 +31769,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 +31792,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 +31843,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 +31885,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 +31916,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 +31930,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 +31946,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 +31974,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 +31982,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 +32002,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 +32037,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 +32046,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 +32059,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; @@ -30742,8 +32079,8 @@ var ts; } 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 +32089,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 +32144,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 +32161,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 +32178,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 +32233,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 +32246,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 +32267,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 +32303,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 +32320,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 +32338,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 +32354,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 +32392,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 +32446,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 +32502,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 +32536,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 +32546,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 +32570,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 +32604,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 +32620,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 +32642,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 +32666,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 +32686,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 +32721,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 +32737,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,6 +32759,16 @@ var ts; return symbol && symbol.valueDeclaration; } } + 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) { return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ts.Diagnostics.Cannot_find_module_0); } @@ -31434,7 +32798,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.extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -31453,7 +32817,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 +32849,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 +32857,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 +32869,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 +32911,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 +32979,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 */) : @@ -31750,13 +33118,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 +33147,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 +33202,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 +33218,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 +33268,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 +33307,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 +33322,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 +33336,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 +33378,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 +33442,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 +33492,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); @@ -32148,6 +33529,9 @@ var ts; if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) { nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */; } + if (flags & 16 /* DoNotIncludeSymbolChain */) { + nodeFlags |= 67108864 /* DoNotIncludeSymbolChain */; + } var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); function symbolToStringWorker(writer) { @@ -32164,15 +33548,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 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; } } @@ -32230,9 +33614,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 & 67108864 /* 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 +33646,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 +33745,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 +33765,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 +33792,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 +33819,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 +33843,60 @@ 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 */); + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); } } else { // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead // of types allows us to catch circular references to instantiations of the same anonymous type - if (!context.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) { + context.approximateLength += 3; + if (!(context.flags & 1 /* NoTruncation */)) { + return ts.createTypeReferenceNode(ts.createIdentifier("..."), /*typeArguments*/ undefined); + } + return ts.createKeywordTypeNode(120 /* AnyKeyword */); + } + 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 +33910,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 +33931,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 +33963,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 +34003,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 +34016,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,11 +34068,11 @@ 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 */ ? @@ -32697,26 +34114,21 @@ var ts; 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) { @@ -32729,9 +34141,9 @@ 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 */); + var 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 +34194,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 +34207,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 +34218,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 +34237,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 +34259,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 +34271,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 +34282,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 +34300,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 & 67108864 /* DoNotIncludeSymbolChain */)) { chain = ts.Debug.assertDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true)); ts.Debug.assert(chain && chain.length > 0); } @@ -32979,7 +34404,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 +34434,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,7 +34449,7 @@ 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; @@ -33116,6 +34548,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 */; } @@ -33169,12 +34604,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 +34619,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 +34636,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 +34645,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 +34672,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 +34712,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 +34740,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 +34795,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 +34820,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 +34869,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 +34879,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 +34894,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 +34929,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 +34982,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 +35005,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 +35015,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 +35043,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 +35059,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 +35073,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 +35095,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 +35110,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 +35126,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 +35161,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 +35178,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 +35193,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 +35205,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 +35241,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 +35255,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 +35307,7 @@ var ts; return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -33875,9 +35316,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 +35330,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 +35339,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 +35353,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 +35393,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 +35416,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 +35438,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 +35446,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 +35491,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 +35524,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 +35546,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 +35564,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 +35591,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 +35621,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 +35635,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 +35643,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 +35675,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 +35686,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 +35715,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 +35724,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 +35788,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 +35812,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 +35848,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 +35857,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 +35886,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 +35929,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 +35939,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 +35979,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 +35998,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 @@ -34590,14 +36046,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); @@ -34633,7 +36089,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 +36098,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 +36130,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 +36147,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 +36171,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 +36185,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 +36207,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 +36222,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 +36234,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 +36269,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 +36313,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 +36355,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 +36371,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 +36420,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 +36463,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 +36486,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 +36631,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 +36740,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 +36760,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 +36794,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 +36840,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 +36876,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 +36899,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 +36937,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 +36953,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 +36971,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 +36981,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 +37000,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 +37015,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 +37029,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 +37041,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 +37064,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 +37077,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 +37094,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 +37122,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 +37139,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 +37150,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 +37159,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 +37183,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 +37193,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 +37207,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 +37226,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 +37264,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 +37284,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 +37312,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 +37322,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 +37344,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 +37352,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 +37375,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 +37460,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 +37520,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 +37608,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 +37646,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 +37700,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 +37739,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 +37764,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 +37802,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 +37815,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 +37825,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 +37839,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 +37883,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 +37906,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 +37970,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 +37987,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 +37997,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 +38011,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 +38037,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 +38047,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 +38067,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 +38113,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 +38130,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 +38144,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 +38171,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 +38179,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 +38210,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 +38234,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 +38307,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 +38340,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 +38367,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 +38395,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 +38424,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 +38433,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 +38470,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 +38485,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 +38498,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 +38556,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 +38599,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 +38610,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 +38621,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 +38652,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 +38681,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 +38744,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 +38766,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 +38801,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 +38811,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 +38849,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 +38867,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 +38886,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 +38901,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 +38914,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 +38943,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 +38970,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 +39027,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 +39037,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 +39063,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 +39078,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 +39087,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 +39098,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 +39114,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 +39131,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 +39169,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 +39185,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 +39209,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 +39218,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 +39243,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 +39253,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 +39276,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 +39285,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 +39305,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 +39324,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 +39345,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; + 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 +39409,7 @@ var ts; } return indexInfo.type; } - if (indexType.flags & 32768 /* Never */) { + if (indexType.flags & 131072 /* Never */) { return neverType; } if (isJSLiteralType(objectType)) { @@ -37882,15 +39435,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 +39453,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 +39496,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 +39517,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 +39530,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 +39540,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 +39556,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 +39587,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 +39609,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 +39620,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 +39659,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 +39691,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 +39714,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 +39757,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 +39787,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 +39801,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 +39834,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 +39849,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 +39899,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 +39914,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 +39923,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 +39963,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 +39975,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 +40007,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 +40022,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 +40040,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 +40189,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 +40203,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 +40252,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 +40290,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 +40300,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 +40332,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 +40341,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 +40380,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 +40424,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 +40469,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 +40548,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 +40592,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 +40605,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 +40623,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 +40638,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 +40656,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 +40687,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 +40787,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 +40806,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 +40817,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 +40863,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 +40896,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 +40921,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 +40952,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 +40983,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 +41009,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 +41025,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 +41039,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 +41117,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 +41162,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 +41208,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 +41251,7 @@ var ts; */ function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) { var errorInfo; + var relatedInfo; var maybeKeys; var sourceStack; var targetStack; @@ -39552,7 +41259,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 +41286,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 +41339,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 +41347,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 +41363,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 +41392,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 +41405,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 +41425,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 +41445,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 +41478,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 +41494,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 +41520,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 +41531,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 +41557,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 +41597,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 +41622,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 +41635,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 +41663,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 +41699,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 +41724,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 +41781,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 +41824,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 +41847,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 +41907,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 +41920,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 +41947,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 +41975,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 +42033,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 +42086,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 +42128,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 +42144,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 +42208,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 +42279,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 +42310,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 +42408,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 +42503,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 +42555,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 +42712,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; @@ -41022,7 +42824,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 +42845,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 +42869,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. @@ -41086,7 +42888,7 @@ var ts; // 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 +42898,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 +42957,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 +42980,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 +42998,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 +43013,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 +43031,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 +43074,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 +43084,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 +43172,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 +43206,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 +43242,80 @@ 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 */: 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 +43364,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 +43377,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 +43404,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 +43430,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 +43446,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 +43507,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 +43535,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 +43559,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 +43574,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 +43582,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 +43595,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 +43644,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 +43658,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 +43696,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 +43705,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 +43733,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 +43749,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 +43768,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 +43778,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 +43825,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 +43838,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 +43879,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 +43923,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 +43943,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 +43965,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 +43978,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 +43991,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 +44020,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 +44049,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 +44091,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 +44100,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 +44122,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 +44143,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 +44178,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 +44191,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 +44263,7 @@ var ts; } } } - if (callExpression.expression.kind === 187 /* PropertyAccessExpression */ && + if (callExpression.expression.kind === 189 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, callExpression.expression.expression)) { return true; } @@ -42302,16 +44276,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 +44312,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 +44328,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 +44395,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 +44407,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 +44415,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 +44440,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 +44462,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 +44480,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 +44520,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 +44542,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 +44575,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 +44628,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 +44669,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 +44687,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 +44711,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 +44730,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 +44752,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 +44762,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 +44835,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 +44872,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 +44885,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 +44913,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 +44936,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 +44953,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 +45085,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 +45107,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 +45128,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 +45136,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 +45167,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 +45184,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 +45217,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 +45268,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 +45393,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 +45406,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 +45448,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 +45465,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 +45492,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 +45513,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 +45531,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 +45552,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 +45579,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 +45597,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 +45618,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,7 +45652,7 @@ 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; } @@ -43551,7 +45681,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 +45690,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 +45700,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 +45711,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 +45720,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 +45730,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 +45757,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 +45804,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 +45817,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 +45885,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 +45926,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 +45977,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 +46052,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 +46073,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 +46088,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 +46120,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 +46143,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 +46171,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 +46192,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 +46207,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 +46215,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 +46237,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 +46248,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 +46264,7 @@ var ts; } } } - var inJs = ts.isInJavaScriptFile(func); + var inJs = ts.isInJSFile(func); if (noImplicitThis || inJs) { var containingLiteral = getContainingObjectLiteral(func); if (containingLiteral) { @@ -44067,7 +46279,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 +46293,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 +46321,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 +46355,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 +46367,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 +46388,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 +46449,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 +46457,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 +46472,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 +46516,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 +46577,8 @@ var ts; return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) || + getIndexTypeOfContextualType(t, 0 /* String */); } return undefined; }, /*noReductions*/ true); @@ -44319,10 +46586,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 +46605,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 +46622,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 +46663,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 +46729,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 +46786,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 +46810,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 +46856,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 +46874,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 +46910,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 +46929,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 +46938,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 +46977,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 +46989,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 +47002,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 +47011,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 +47072,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 +47086,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 +47121,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); } @@ -44916,13 +47149,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 +47165,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 +47184,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 +47195,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 +47221,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 +47238,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 +47248,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 +47285,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 +47294,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 +47305,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 +47323,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 +47331,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 +47358,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 +47377,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 +47404,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 +47414,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 +47423,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 +47438,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 +47476,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 +47498,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 +47539,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 +47572,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 +47596,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 +47609,63 @@ var ts; function getJsxElementChildrenPropertyName(jsxNamespace) { return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace); } - function getApparentTypeOfJsxPropsType(propsType) { - if (!propsType) { - return undefined; - } - 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)); - } - 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; - } - } - } - } - 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); + function getUninstantiatedJsxSignaturesOfType(elementType) { // Resolve the signatures, preferring constructor var signatures = getSignaturesOfType(elementType, 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)); - } + } + if (signatures.length === 0 && elementType.flags & 1048576 /* Union */) { + // If each member has some combination of new/call signatures; make a union signature list for those + signatures = getUnionSignatures(ts.map(elementType.types, getUninstantiatedJsxSignaturesOfType)); + } + 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 +47689,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 +47722,7 @@ var ts; } } } - function checkJsxOpeningLikeElementOrOpeningFragment(node, checkMode) { + function checkJsxOpeningLikeElementOrOpeningFragment(node) { var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { checkGrammarJsxElement(node); @@ -45748,7 +47733,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 +47744,8 @@ var ts; } } if (isNodeOpeningLikeElement) { - checkJsxAttributesAssignableToTagNameAttributes(node, checkMode); - } - else { - checkJsxChildren(node.parent); + var sig = getResolvedSignature(node); + checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(node), getReturnTypeOfSignature(sig), node); } } /** @@ -45779,7 +47762,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 +47772,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 +47780,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 +47809,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 +47825,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 +47857,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 +47897,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 +47923,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 +47975,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,9 +47986,9 @@ 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)); @@ -46053,9 +48000,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 +48010,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 +48045,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 +48058,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 +48098,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 +48138,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); @@ -46254,16 +48207,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 +48243,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 +48273,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 +48297,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 +48309,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 +48328,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 +48355,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 +48363,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 +48396,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 +48433,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 +48460,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 +48518,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 +48529,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 +48538,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 +48558,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 +48594,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 +48646,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 +48687,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 +48713,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 +48857,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 +48880,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 +48912,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 +48928,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 +48975,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 +48999,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 +49045,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 +49138,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 +49149,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 +49188,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 +49227,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 +49261,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 +49277,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 +49306,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 +49366,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 +49385,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 +49442,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 +49470,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 +49485,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 +49510,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 +49530,58 @@ 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); + } + if (exprTypes.flags & 128 /* StringLiteral */) { + var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(exprTypes, node); + if (!intrinsicType) { + error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, exprTypes.value, "JSX." + JsxNames.IntrinsicElements); + return resolveUntypedCall(node); + } + else { + var fakeSignature = createSignatureForJSXIntrinsic(node, intrinsicType); + checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined), intrinsicType, node.tagName, node.attributes); + return fakeSignature; + } + } + var signatures = getUninstantiatedJsxSignaturesOfType(apparentType); + if (exprTypes.flags & 4 /* String */ || 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 +49591,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 +49640,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 +49684,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 +49722,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 +49738,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 +49752,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 +49789,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 +49804,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 +49848,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 +49857,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 +49895,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 +49909,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 +49973,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 +49986,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 +50010,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 +50017,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 +50080,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 +50094,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 +50113,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 +50144,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 +50240,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 +50309,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 +50331,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 +50344,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 +50352,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 +50375,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 +50413,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 +50424,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 +50468,6 @@ var ts; } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } return type; @@ -48622,7 +50478,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 +50494,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 +50517,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 +50589,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 +50604,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 +50613,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 +50650,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 +50704,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 +50726,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 +50741,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 +50776,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 +50795,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 +50808,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 +50817,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 +50828,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 +50886,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 +50911,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 +50928,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 +50944,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 +50977,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 +51051,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 +51081,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 +51152,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 +51183,29 @@ 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, right); + if (isAssignmentDeclaration(declKind)) { 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 +51213,15 @@ var ts; default: return ts.Debug.fail(); } - function checkSpecialAssignment(special, right) { - if (special === 2 /* ModuleExports */) { + function checkAssignmentDeclaration(kind, right) { + if (kind === 2 /* ModuleExports */) { var rightType_1 = checkExpression(right, checkMode); for (var _i = 0, _a = getPropertiesOfObjectType(rightType_1); _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 +51231,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 +51246,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 +51274,8 @@ var ts; } } } - function isJSSpecialPropertyAssignment(special) { - switch (special) { + function isAssignmentDeclaration(kind) { + switch (kind) { case 2 /* ModuleExports */: return true; case 1 /* ExportsProperty */: @@ -49344,7 +51284,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 +51301,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 +51383,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 +51426,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 +51448,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 +51485,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 +51496,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 +51524,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 +51550,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 +51567,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 +51581,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 +51592,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 +51719,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 +51728,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 +51739,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 +51797,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 +51817,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 +51830,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 +51866,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 +51899,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 +51916,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 +51931,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 +52003,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 +52028,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 +52048,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 +52056,7 @@ var ts; error(declaration, ts.Diagnostics.Duplicate_string_index_signature); } break; - case 134 /* NumberKeyword */: + case 135 /* NumberKeyword */: if (!seenNumericIndexer) { seenNumericIndexer = true; } @@ -50137,7 +52083,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 +52108,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 +52138,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 +52163,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 +52173,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 +52197,7 @@ var ts; } } var returnType = getTypeOfAccessors(getSymbolOfNode(node)); - if (node.kind === 156 /* GetAccessor */) { + if (node.kind === 158 /* GetAccessor */) { checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType); } } @@ -50268,7 +52214,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 +52245,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 +52293,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 +52302,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 +52317,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 +52332,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 +52346,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 +52364,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 +52381,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 +52474,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 +52513,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 +52524,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 +52576,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 +52586,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 +52650,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 +52676,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 +52733,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 +52764,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 +52912,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 +52935,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 +52954,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 +52992,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 +53017,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 +53085,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 +53101,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 +53170,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 +53208,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 +53223,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 +53252,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 +53261,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 +53272,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); @@ -51340,42 +53297,42 @@ 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 */: + case 241 /* 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 */: + case 157 /* Constructor */: + case 196 /* FunctionExpression */: + case 239 /* FunctionDeclaration */: + case 197 /* ArrowFunction */: + case 156 /* MethodDeclaration */: + case 158 /* GetAccessor */: + case 159 /* SetAccessor */: if (node.body) { 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 176 /* InferType */: checkUnusedTypeParameters(node, addDiagnostic); break; default: @@ -51396,11 +53353,11 @@ var ts; 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 */) { + 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; } @@ -51409,7 +53366,7 @@ var ts; addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol))); } break; - case 155 /* Constructor */: + 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 */)) { @@ -51417,8 +53374,8 @@ var ts; } } break; - case 160 /* IndexSignature */: - case 215 /* SemicolonClassElement */: + case 162 /* IndexSignature */: + case 217 /* SemicolonClassElement */: // Can't be private break; default: @@ -51430,9 +53387,9 @@ var ts; 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 (node.flags & 4194304 /* Ambient */ || node.kind !== 176 /* InferType */ && ts.last(getSymbolOfNode(node).declarations) !== node) return; - if (node.kind === 174 /* InferType */) { + if (node.kind === 176 /* 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))); @@ -51447,7 +53404,7 @@ var ts; continue; var name = ts.idText(typeParameter.name); var parent = typeParameter.parent; - if (parent.kind !== 174 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { + if (parent.kind !== 176 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) { if (seenParentsWithEveryUnused.tryAdd(parent)) { var range = ts.isJSDocTemplateTag(parent) // Whole @template tag @@ -51533,7 +53490,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 +53508,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 +53529,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 +53541,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 +53588,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 +53602,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 +53612,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 +53627,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 +53653,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 +53668,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 +53703,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 +53715,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 +53740,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 +53751,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 +53770,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 +53785,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 +53818,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 @@ -51884,28 +53841,28 @@ var ts; 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 (parent.initializer && property) { + checkPropertyAccessibility(parent, 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 +53881,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 +53902,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 +53924,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 +53970,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 +53989,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 +53997,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 +54036,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 +54069,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 +54089,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 +54102,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 +54157,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 +54179,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 +54210,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 +54275,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 +54312,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 +54424,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 +54440,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 +54449,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 +54475,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 +54504,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 +54516,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 +54545,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 +54652,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 +54682,7 @@ var ts; case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -52890,18 +54858,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); } } @@ -52944,7 +54915,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 +54934,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 +54960,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 +54999,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 +55049,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 +55081,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 +55091,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 +55115,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 +55220,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 +55304,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 +55344,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 +55367,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 +55405,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 +55431,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 +55481,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 +55508,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 +55526,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 +55534,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 +55558,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 +55589,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 +55627,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 +55651,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 +55687,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 +55707,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 +55715,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 +55736,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 +55750,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 +55784,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 +55825,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 +55843,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 +56070,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 +56137,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 +56150,6 @@ var ts; } }); } - deferredNodes = undefined; if (ts.isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -54252,13 +56231,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 +56249,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 +56301,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 +56319,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 +56341,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 +56356,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 +56371,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 +56388,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 +56397,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 +56406,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 +56434,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 +56450,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 +56463,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 +56485,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; @@ -54531,12 +56511,12 @@ var ts; 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 +56526,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 +56542,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 +56577,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 +56600,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 +56659,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 +56713,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 +56778,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 +56799,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 +56834,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 +56854,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 +56867,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 +56887,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 +56930,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 +56949,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 +56963,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 +56976,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 +57022,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 +57050,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 +57072,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 +57085,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 +57109,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 +57143,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 +57162,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 +57170,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 +57192,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 +57207,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 +57262,8 @@ var ts; isImplementationOfOverload: isImplementationOfOverload, isRequiredInitializedParameter: isRequiredInitializedParameter, isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty, + isExpandoFunctionDeclaration: isExpandoFunctionDeclaration, + getPropertiesOfContainerFunction: getPropertiesOfContainerFunction, createTypeOfDeclaration: createTypeOfDeclaration, createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration, createTypeOfExpression: createTypeOfExpression, @@ -55266,12 +57292,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 +57305,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 +57324,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 +57376,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 +57391,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 +57415,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 +57462,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 +57491,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 +57526,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 +57574,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 +57598,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 +57628,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 +57641,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 +57651,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 +57663,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 +57687,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 +57744,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 +57759,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 +57774,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 +57801,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 +57844,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 +57900,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 +57965,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 +58001,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 +58031,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 +58044,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 +58060,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 +58078,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 +58103,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 +58117,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 +58134,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 +58149,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 +58202,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 +58212,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 +58221,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 +58241,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 +58281,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 +58309,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 +58335,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 +58360,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 +58389,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 +58407,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 +58419,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 +58435,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 +58464,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 +58513,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 +58530,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 +58547,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 +58575,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 +58601,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 +58642,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 +58661,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 +58669,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 +58677,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 +58698,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 +58713,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 +58740,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 +58762,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 +58832,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 +58841,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 +58868,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 +58932,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 +58954,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 +58978,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 +59059,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 +59086,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 +59142,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 +59155,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 +59171,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 +59195,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 +59208,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 +59228,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 +59243,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 +59252,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 +59269,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 +59297,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 +59317,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 +59340,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 +59361,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 +59369,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 +59377,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 +59417,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 +59431,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 +59445,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 +59453,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 +59461,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 +59473,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 +59485,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 +59497,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 +59509,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 +59521,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 +59533,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 +59541,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 +59560,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 +59578,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 +59590,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 +59608,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 +59620,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 +59635,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 +59649,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 +59667,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 +59680,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 +59692,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 +59704,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 +59723,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 +59737,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 +59751,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 +59768,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 +59782,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 +59798,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 +59814,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 +59837,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 +59851,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 +59863,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 +59887,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 +59909,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 +59921,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 +59933,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 +59945,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 +59957,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 +59970,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 +59983,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 +60000,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 +60020,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 +60034,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 +60072,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 +60084,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 +60105,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 +60123,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 +60137,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 +60149,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 +60163,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 +60177,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 +60196,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 +60211,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 +60231,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 +60247,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 +60261,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 +60275,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 +60293,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 +60309,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 +60327,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 +60339,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 +60351,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 +60363,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 +60377,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 +60391,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 +60405,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 +60417,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 +60433,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 +60454,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 +60467,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 +60493,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 +60515,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 +60537,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 +60557,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 +60576,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 +60595,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 +60607,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 +60619,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 +60631,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 +60649,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 +60667,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 +60681,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 +60693,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 +60705,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 +60719,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 +60736,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 +60754,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 +60766,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 +60781,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 +60792,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 +60858,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 +60874,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 +60890,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 +60902,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 +60918,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 +60932,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 +60944,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 +60956,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 +60970,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 +60984,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 +60996,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 +61009,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 +61024,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 +61039,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 +61053,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 +61066,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 +61087,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 +61171,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 +61183,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 +61195,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 +61210,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 +61226,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 +61249,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 +61264,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 +61306,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 +61407,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 +61918,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 +61930,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 +61958,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 +61970,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 +61983,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 +62040,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 +62055,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 +62066,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 +62078,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 +62324,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 +62352,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 +62373,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 +62407,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 +62422,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 +62459,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 +62494,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 +62510,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 +62525,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 +62560,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 +62577,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 +62602,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 +62640,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 +62651,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 +62681,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 +62709,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 +62738,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 +62759,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 +62790,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 +62798,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 +62820,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 +62885,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 +62904,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 +63007,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 +63019,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 +63055,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 +63072,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 +63084,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 +63096,7 @@ var ts; : propertyName; } break; - case 275 /* SpreadAssignment */: + case 277 /* SpreadAssignment */: // `a` in `({ ...a } = ...)` return bindingElement.name; } @@ -60958,7 +63111,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 +63119,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 +63165,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 +63330,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 +63641,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 +63701,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 +63714,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 +63722,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 +63773,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 +63898,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 +63906,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 +64112,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 +64162,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 +64199,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.getPositionOfLineAndCharacter(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.getPositionOfLineAndCharacter(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 +64838,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 +64884,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 +64892,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 +64928,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 +64942,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 +64962,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 +65314,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 +65381,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 +65578,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 +65609,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 +65665,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 +65686,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 +65734,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 +65758,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 +65784,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 +65818,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 +65840,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 +65857,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 +65928,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 +65939,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 +65977,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 +66042,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 +66111,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 +66313,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 +66321,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 +66369,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 +66489,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 +66560,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 +66571,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 +66588,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 +66700,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 +66858,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 +66959,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 +66981,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 +66994,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 +67005,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 +67027,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 +67072,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 +67117,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 +67229,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 +67240,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 +67273,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 +67294,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 +67302,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 +67323,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 +67412,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 +67810,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 +67891,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 +68021,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 +68067,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 +68114,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 +68308,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 +68327,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 +68335,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 +68345,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 +68414,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 +68430,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 +68456,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 +68570,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 +68598,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 +68628,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 +68849,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 +68862,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 +68906,8 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -66391,15 +68934,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 +68967,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 +68992,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 +69028,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 +69099,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 +69117,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 +69145,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 +69167,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 +69177,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 +69261,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 +69273,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 +69282,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 +69293,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 +69325,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 +69340,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 +69357,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 +69454,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 +69551,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 +69605,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 +69625,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 +69658,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 +69683,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 +69719,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 +69832,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 +69846,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 +69922,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 +70023,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 +70329,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 +70337,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 +70389,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 +70567,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 +70592,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 +70776,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 +70794,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 +70813,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 +70950,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 +71055,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 +71094,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 +71106,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 +71164,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 +71172,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 +71243,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 +71320,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 +71372,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 +71391,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 +71437,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 +71560,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 +71642,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 +71687,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 +71725,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 +71755,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 +71776,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 +71813,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 +71850,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 +71918,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 +71987,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 +72174,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 +72205,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 +72233,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 +72247,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 +72263,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 +72342,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 +72619,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 +72690,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 +72731,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 +72852,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 +73031,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 +73068,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 +73086,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 +73133,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 +73250,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 +73348,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 +73385,7 @@ var ts; function enableSubstitutionsForBlockScopedBindings() { if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) { enabledSubstitutions |= 2 /* BlockScopedBindings */; - context.enableSubstitution(71 /* Identifier */); + context.enableSubstitution(72 /* Identifier */); } } /** @@ -70550,14 +73395,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 +73443,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 +73459,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 +73528,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 +73568,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 +73593,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 +73620,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 +73679,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 +73954,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 +73973,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 +74011,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 +74038,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 +74199,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 +74239,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 +74268,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 +74280,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 +74312,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 +74323,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 +74367,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 +74398,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 +74587,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 +74656,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 +75114,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 +75127,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 +75257,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 +75289,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 +75439,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 +76355,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 +76374,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 +76431,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 +76462,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 +76688,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 +76713,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 +76731,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 +76780,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 +77226,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 +77281,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 +77466,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 +77483,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 +77545,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 +77571,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 +77639,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 +77721,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 +77745,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 +77947,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 +77972,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 +78050,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 +78112,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 +78296,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 +78360,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 +78422,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 +78605,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 +78824,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 +78889,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 +78905,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 +78922,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 +78970,7 @@ var ts; */ function substituteUnspecified(node) { switch (node.kind) { - case 274 /* ShorthandPropertyAssignment */: + case 276 /* ShorthandPropertyAssignment */: return substituteShorthandPropertyAssignment(node); } return node; @@ -76153,12 +79004,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 +79095,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 +79131,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 +79170,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 +79199,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 +79309,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 +79338,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 +79385,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 +79394,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 +79404,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 +79429,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 +79468,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 +79495,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 +79509,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 +79534,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 +79565,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 +79578,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 +79593,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 +79635,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 +79672,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 +79702,7 @@ var ts; var needsScopeFixMarker = false; var resultHasScopeMarker = false; var enclosingDeclaration; - var necessaryTypeRefernces; + var necessaryTypeReferences; var lateMarkedStatements; var lateStatementReplacementMap; var suppressNewDiagnosticContexts; @@ -76869,6 +79720,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 +79730,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) { @@ -76950,15 +79802,16 @@ var ts; } } 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 +79823,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 +79860,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 +79873,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 +79910,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 +79918,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 +79939,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 +79961,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 +79974,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 +79986,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 +79999,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 +80019,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 +80035,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 +80108,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 +80128,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 +80155,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 +80260,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 +80329,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 +80347,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 +80382,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 +80392,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 +80401,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 +80417,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 +80431,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 +80455,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 +80508,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 +80519,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 +80549,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 +80558,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 +80578,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 +80600,7 @@ var ts; if (canProdiceDiagnostic) { getSymbolAccessibilityDiagnostic = oldDiag; } - if (input.kind === 242 /* ModuleDeclaration */) { + if (input.kind === 244 /* ModuleDeclaration */) { needsDeclare = previousNeedsDeclare; } if (node === input) { @@ -77733,7 +80621,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 +80684,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 +80705,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 +80719,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 +80757,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 +80766,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 +80876,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 +80895,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 +80903,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 +81153,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 +81195,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 +81237,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 +81257,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 +81280,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 +81353,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 +81375,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 +81390,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 +81401,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 +81445,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 +81532,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 +81575,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 +81587,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 +81600,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 +81615,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 +81640,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 +81667,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 +81693,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 +81761,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 +82049,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 +82144,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 +82187,7 @@ var ts; writeLines(helper.text); } else { - writeLines(helper.text(makeFileLevelOptmiisticUniqueName)); + writeLines(helper.text(makeFileLevelOptimisticUniqueName)); } helpersEmitted = true; } @@ -79988,7 +82199,8 @@ var ts; // Literals/Pseudo-literals // // SyntaxKind.NumericLiteral - function emitNumericLiteral(node) { + // SyntaxKind.BigIntLiteral + function emitNumericOrBigIntLiteral(node) { emitLiteral(node); } // SyntaxKind.StringLiteral @@ -79998,9 +82210,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 +82230,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 +82241,7 @@ var ts; emit(node.right); } function emitEntityName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -80065,7 +82277,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 +82299,7 @@ var ts; emitNodeWithWriter(node.name, writeProperty); emit(node.questionToken); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); @@ -80097,7 +82309,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 +82320,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitMethodDeclaration(node) { @@ -80127,7 +82339,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 +82351,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitConstructSignature(node) { @@ -80151,7 +82363,7 @@ var ts; emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); popNameGenerationScope(node); } function emitIndexSignature(node) { @@ -80159,10 +82371,10 @@ var ts; emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); emitTypeAnnotation(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitSemicolonClassElement() { - writeSemicolon(); + writeTrailingSemicolon(); } // // Types @@ -80189,22 +82401,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 +82437,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 +82447,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 +82516,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 +82567,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 +82590,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 +82599,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 +82612,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 +82635,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 +82650,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 +82679,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 +82700,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 +82740,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,23 +82767,23 @@ 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); } @@ -80619,36 +82831,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 +82879,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 +82902,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 +82949,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 +82982,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 +83024,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 +83044,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 +83092,7 @@ var ts; } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } function emitSignatureHead(node) { @@ -80923,7 +83144,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 +83156,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 +83183,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 +83196,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 +83213,7 @@ var ts; writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); @@ -81001,7 +83222,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 +83234,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 +83250,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 +83275,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 +83308,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 +83356,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 +83382,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 +83394,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 +83409,6 @@ var ts; writePunctuation(">"); } function emitJsxText(node) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { @@ -81199,7 +83419,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 +83439,7 @@ var ts; } } function emitJsxTagName(node) { - if (node.kind === 71 /* Identifier */) { + if (node.kind === 72 /* Identifier */) { emitExpression(node); } else { @@ -81230,13 +83450,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 +83466,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 +83481,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); @@ -81318,6 +83538,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 +83693,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 +83751,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 +83791,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 +83826,7 @@ var ts; } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { - emitList(node, modifiers, 131328 /* Modifiers */); + emitList(node, modifiers, 262656 /* Modifiers */); writeSpace(); } } @@ -81478,7 +83840,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 +83877,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 +83921,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 +83937,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 +83947,11 @@ var ts; writeSpace(); writePunctuation("|"); break; + case 32 /* AsteriskDelimited */: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case 8 /* AmpersandDelimited */: writeSpace(); writePunctuation("&"); @@ -81588,11 +83962,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 +83975,7 @@ var ts; } return; } - if (format & 7680 /* BracketsMask */) { + if (format & 15360 /* BracketsMask */) { writePunctuation(getOpeningBracket(format)); if (isEmpty && !isUndefined) { // TODO: GH#18217 @@ -81616,23 +83990,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 +84015,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 +84035,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 +84064,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 +84074,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 +84100,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 +84176,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 +84212,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 +84251,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 +84276,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 +84300,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 +84312,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 +84320,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 +84365,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 +84448,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 +84511,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 +84590,7 @@ var ts; i++; } } - function makeFileLevelOptmiisticUniqueName(name) { + function makeFileLevelOptimisticUniqueName(name) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } /** @@ -82272,23 +84633,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 +84690,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 +85479,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 +85512,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 +85522,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 +85530,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 +85542,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 +85554,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 +85570,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 +85604,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 +85631,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 +85719,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 +85735,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 +85774,7 @@ var ts; } } ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText; - function loadWithLocalCache(names, containingFile, loader) { + function loadWithLocalCache(names, containingFile, redirectedReference, loader) { if (names.length === 0) { return []; } @@ -83047,7 +85787,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 +85797,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 +85806,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 +85831,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 +85872,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 +85905,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 +85933,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 +85953,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 +85978,33 @@ 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 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 +86018,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 +86043,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 +86093,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 +86132,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 +86161,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 +86177,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 +86230,7 @@ var ts; } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker; @@ -83455,7 +86241,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 +86267,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 +86277,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 +86326,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 +86352,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 +86379,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 +86444,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 +86472,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 +86494,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 +86527,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 +86542,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 +86605,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 +86671,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 +86762,7 @@ var ts; } return true; } - function getJavaScriptSyntacticDiagnosticsForFile(sourceFile) { + function getJSSyntacticDiagnosticsForFile(sourceFile) { return runWithCancellationToken(function () { var diagnostics = []; var parent = sourceFile; @@ -83982,22 +86772,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 +86795,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 +86842,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 +86903,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 +86968,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 +86995,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 +87025,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 +87075,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 +87121,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 +87177,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 +87199,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 +87265,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 +87278,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 +87312,85 @@ 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) { + 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) { + return forEachResolvedProjectReference(function (referencedProject, referenceProjectPath) { + // not input file from the referenced project, ignore + if (!referencedProject || + toPath(options.configFilePath) === referenceProjectPath || + !ts.contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = ts.changeExtension(fileName.replace(k, v), ".d.ts"); - } + return referencedProject; }); - return result; + } + 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); + }); + } + 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 +87400,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 +87418,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 +87444,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 +87490,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 +87499,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 +87519,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 +87539,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 +87621,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 +87682,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 +87700,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 +87717,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 +87730,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 +87743,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 +87813,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 +87892,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 +87909,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 +87959,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 +87976,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 +88034,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 +88065,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 +88075,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 +88104,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 +88115,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 +88259,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 +88329,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 +88388,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 +88442,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 +88492,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 +88509,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 +88528,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 +88618,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 +88650,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 +88696,7 @@ var ts; */ function removeSemanticDiagnosticsOf(state, path) { if (!state.semanticDiagnosticsFromOldState) { - return false; + return true; } state.semanticDiagnosticsFromOldState.delete(path); state.semanticDiagnosticsPerFile.delete(path); @@ -85765,7 +88743,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 +88756,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 +88937,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 +88969,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 +88986,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 +89014,7 @@ var ts; resolveModuleNames: resolveModuleNames, getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache, resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects, removeResolutionsOfFile: removeResolutionsOfFile, invalidateResolutionOfFile: invalidateResolutionOfFile, setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports, @@ -86086,7 +89076,7 @@ var ts; } function clearPerDirectoryResolutions() { perDirectoryResolvedModuleNames.clear(); - nonRelaticeModuleNameCache.clear(); + nonRelativeModuleNameCache.clear(); perDirectoryResolvedTypeReferenceDirectives.clear(); nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions); nonRelativeExternalModuleResolutions.clear(); @@ -86102,15 +89092,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 +89111,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 +89124,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 +89161,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 +89189,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 +89239,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 +89258,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 +89282,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 +89311,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 +89366,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 +89416,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 +89493,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 +89536,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 +89603,117 @@ 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 (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++; } - 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]; + return count; } 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 +89777,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 +89794,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 +89815,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 +89847,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 +89873,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 +89943,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 +90011,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 +90019,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 +90065,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 +90101,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 +90120,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 +90135,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 +90166,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 +90180,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 +90199,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 +90224,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 +90259,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 +90275,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 +90334,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 +90344,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 +90373,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 +90400,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 +90522,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 +90537,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 +90583,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 +90609,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 +90620,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 +90661,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 +90701,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 +90723,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 +90741,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 +90812,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 +90827,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 +90848,818 @@ 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); } } } - } - function buildInvalidatedProjects() { - buildSomeProjects(function (p) { return context.invalidatedProjects.hasKey(p); }); - } - function buildDependentInvalidatedProjects() { - buildSomeProjects(function (p) { return context.queuedProjects.hasKey(p); }); - } - function buildSomeProjects(predicate) { - var resolvedNames = resolveProjectNames(rootNames); - if (resolvedNames === undefined) - 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; + 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 invalidateProject(configFileName, reloadLevel) { + invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); + } + function invalidateResolvedProject(resolved, reloadLevel) { + if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) { + configFileCache.removeKey(resolved); + globalDependencyGraph = undefined; + } + projectStatus.removeKey(resolved); + diagnostics.removeKey(resolved); + addProjToQueue(resolved, reloadLevel); + } + /** + * 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; + // 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 }; 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); return resultFlags; + function buildErrors(diagnostics, errorFlags, errorType) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); + 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 +91695,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 +91705,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 +91854,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 +91883,6 @@ var ts; : undefined; } server.findArgument = findArgument; - /*@internal*/ function nowString() { // E.g. "12:34:56.789" var d = new Date(); @@ -88713,13 +91896,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 +91939,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 +91971,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 +92056,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 +92185,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 +92392,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 +92497,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 +92676,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 +92796,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..86872c57c6b 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.2.0", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ @@ -75,6 +75,7 @@ "gulp-typescript": "latest", "istanbul": "latest", "jake": "latest", + "lodash": "4.17.10", "merge2": "latest", "minimist": "latest", "mkdirp": "latest", 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/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/src/compiler/binder.ts b/src/compiler/binder.ts index 489f212967d..fcd9b854c49 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -234,13 +234,17 @@ namespace ts { } 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; } } @@ -636,6 +640,7 @@ namespace ts { function bindChildrenWorker(node: Node): void { if (checkUnreachable(node)) { bindEachChild(node); + bindJSDoc(node); return; } switch (node.kind) { @@ -1176,7 +1181,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 +1379,7 @@ namespace ts { } function bindJSDocTypeAlias(node: JSDocTypedefTag | JSDocCallbackTag) { + node.tagName.parent = node; if (node.fullName) { setParentPointers(node, node.fullName); } @@ -2108,7 +2113,7 @@ namespace ts { // 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,6 +2189,19 @@ namespace ts { return bindFunctionExpression(node); case SyntaxKind.CallExpression: + 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); } @@ -2286,14 +2304,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 +2324,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 +2365,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 @@ -2390,7 +2419,7 @@ 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) { @@ -2456,7 +2485,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,6 +2511,12 @@ 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; @@ -2508,25 +2548,27 @@ 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.Assignment; const excludeFlags = SymbolFlags.ValueModuleExcludes & ~SymbolFlags.Assignment; - namespaceSymbol = forEachIdentifierInEntityName(propertyAccess.expression, namespaceSymbol, (id, symbol, parent) => { + 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); } }); } + return namespaceSymbol; + } + + function bindPotentiallyNewExpandoMemberToNamespace(declaration: PropertyAccessEntityNameExpression | CallExpression, namespaceSymbol: Symbol | undefined, isPrototypeProperty: boolean) { if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) { return; } @@ -2536,10 +2578,19 @@ namespace ts { (namespaceSymbol.members || (namespaceSymbol.members = createSymbolTable())) : (namespaceSymbol.exports || (namespaceSymbol.exports = createSymbolTable())); - const isMethod = isFunctionLikeDeclaration(getAssignedExpandoInitializer(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.Assignment, excludes & ~SymbolFlags.Assignment); + 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); } /** @@ -2557,6 +2608,9 @@ namespace ts { return true; } const node = symbol.valueDeclaration; + if (isCallExpression(node)) { + return !!getAssignedExpandoInitializer(node); + } let init = !node ? undefined : isVariableDeclaration(node) ? node.initializer : isBinaryExpression(node) ? node.right : @@ -2657,7 +2711,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 +2922,6 @@ namespace ts { } } - /* @internal */ export function isExportsOrModuleExportsOrAlias(sourceFile: SourceFile, node: Expression): boolean { return isExportsIdentifier(node) || isModuleExportsPropertyAccessExpression(node) || @@ -2892,6 +2945,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 +3052,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 +3083,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 +3126,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 +3190,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 +3212,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 +3289,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 +3313,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 +3344,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 +3359,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 +3393,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 +3435,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 +3476,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 +3496,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 +3514,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 +3528,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 +3702,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 +3722,7 @@ namespace ts { case SyntaxKind.AnyKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.NeverKeyword: case SyntaxKind.ObjectKeyword: case SyntaxKind.StringKeyword: @@ -3717,11 +3782,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 +3802,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 +3816,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 +3839,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 +3850,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 +3898,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 +3930,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..637e77c545f 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 */ @@ -64,9 +68,11 @@ namespace ts { state.semanticDiagnosticsPerFile = createMap>(); } state.changedFilesSet = createMap(); + const useOldState = BuilderState.canReuseOldState(state.referencedMap, oldState); + const oldCompilerOptions = useOldState ? oldState!.program.getCompilerOptions() : 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) { @@ -83,6 +89,8 @@ namespace ts { // 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 +109,11 @@ namespace ts { state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { + const sourceFile = state.program.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) { @@ -193,6 +206,19 @@ 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 options = state.program.getCompilerOptions(); + if (forEach(state.program.getSourceFiles(), f => + state.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 +227,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 +242,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 +250,41 @@ 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 + return !!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) ); } @@ -235,7 +294,7 @@ namespace ts { */ function removeSemanticDiagnosticsOf(state: BuilderProgramState, path: Path) { if (!state.semanticDiagnosticsFromOldState) { - return false; + return true; } state.semanticDiagnosticsFromOldState.delete(path); state.semanticDiagnosticsPerFile!.delete(path); @@ -294,7 +353,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 +366,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.getProgram(), + configFileParsingDiagnostics, + projectReferences + }); host = oldProgramOrHost as CompilerHost; } else { @@ -410,7 +476,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[] = []; @@ -623,9 +689,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,18 +699,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); + 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: program } = getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences); return { // Only return program, all other methods are not implemented getProgram: () => program, diff --git a/src/compiler/builderState.ts b/src/compiler/builderState.ts index 12936e5b2e8..7c7bebde9f9 100644 --- a/src/compiler/builderState.ts +++ b/src/compiler/builderState.ts @@ -88,7 +88,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 +100,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 +130,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 +143,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(); @@ -254,6 +292,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 +368,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 +430,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 +489,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); } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9e74fb8521c..2bd831332f8 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(); @@ -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 @@ -627,7 +668,7 @@ namespace ts { const identityRelation = createMap(); const enumRelation = createMap(); - type TypeSystemEntity = Symbol | Type | Signature; + type TypeSystemEntity = Node | Symbol | Type | Signature; const enum TypeSystemPropertyName { Type, @@ -635,6 +676,8 @@ namespace ts { DeclaredType, ResolvedReturnType, ImmediateBaseConstraint, + EnumTagType, + JSDocTypeReference, } const enum CheckMode { @@ -827,7 +870,7 @@ namespace ts { (source.flags | target.flags) & SymbolFlags.Assignment) { Debug.assert(source !== target); if (!(target.flags & SymbolFlags.Transient)) { - target = cloneSymbol(target); + target = cloneSymbol(resolveSymbol(target)); } // 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 +880,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 +899,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 +909,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 = (getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node; - const targetList = sourceSymbolFile === firstFile ? firstInstanceList : secondInstanceList; - targetList.instances.push(errorNode); - }); - forEach(target.declarations, node => { - const errorNode = (getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? getNameOfExpando(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 = (getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? getNameOfExpando(node) : getNameOfDeclaration(node)) || node; - addDuplicateDeclarationError(errorNode, message, symbolName, source.declarations && source.declarations[0]); + 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 +963,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 +1250,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) { @@ -1432,14 +1479,14 @@ namespace 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) { 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; } } @@ -1519,8 +1566,7 @@ 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) { + if (some(result.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 } } @@ -1691,7 +1737,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"); @@ -1906,7 +1954,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) { @@ -2072,8 +2120,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); } /** @@ -2182,6 +2230,9 @@ namespace ts { function getDeclarationOfJSPrototypeContainer(symbol: Symbol) { const decl = symbol.parent!.valueDeclaration; + if (!decl) { + return undefined; + } const initializer = isAssignmentDeclaration(decl) ? getAssignedExpandoInitializer(decl) : hasOnlyExpressionInitializer(decl) ? getDeclaredExpandoInitializer(decl) : undefined; @@ -2219,7 +2270,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 && !extensionIsTS(resolvedModule.extension)) { errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference); } // merged symbol is module declaration symbol combined with all augmentations @@ -2240,7 +2291,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); @@ -2273,7 +2324,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)); @@ -2318,11 +2369,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); @@ -2534,6 +2590,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); + 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` @@ -2542,10 +2636,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)) { @@ -3049,6 +3145,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); @@ -3075,7 +3174,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; } } @@ -3126,9 +3225,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 }; @@ -3168,21 +3273,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); @@ -3192,6 +3303,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(); @@ -3279,6 +3394,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); @@ -3346,12 +3464,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); @@ -3362,7 +3481,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) { @@ -3370,20 +3489,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; } } @@ -3400,7 +3527,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 } } @@ -3457,8 +3584,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]); @@ -3570,10 +3697,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)); @@ -3607,8 +3739,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; @@ -3637,8 +3778,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; @@ -3853,7 +4000,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); } @@ -3865,14 +4012,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]); @@ -3896,6 +4050,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; + } } } @@ -3999,6 +4172,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("") @@ -4108,6 +4289,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; @@ -4173,7 +4357,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; @@ -4221,7 +4405,8 @@ namespace ts { // State encounteredError: boolean; - visitedSymbols: Map | undefined; + visitedTypes: Map | undefined; + symbolDepth: Map | undefined; inferTypeParameters: TypeParameter[] | undefined; approximateLength: number; truncating?: boolean; @@ -4252,6 +4437,9 @@ namespace ts { const declaration = symbol.declarations[0]; const name = getNameOfDeclaration(declaration); if (name) { + if (isCallExpression(declaration) && isBindableObjectDefinePropertyCall(declaration)) { + return symbolName(symbol); + } return declarationNameToString(name); } if (declaration.parent && declaration.parent.kind === SyntaxKind.VariableDeclaration) { @@ -4462,6 +4650,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: @@ -4470,6 +4660,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); } @@ -4533,21 +4725,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); @@ -4572,6 +4771,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) { @@ -4591,53 +4794,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 exprType = getLiteralTypeFromPropertyName(name); + const declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); + type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); } } else { @@ -4647,17 +4806,17 @@ 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 { // 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) ? + type = everyType(parentType, isTupleLikeType) ? getTupleElementType(parentType, index) || declaration.initializer && checkDeclarationInitializer(declaration) : elementType; if (!type) { @@ -4673,11 +4832,11 @@ namespace 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)) & 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; } @@ -4708,7 +4867,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; } @@ -4823,7 +4982,7 @@ namespace ts { 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) { @@ -4839,9 +4998,11 @@ namespace ts { definedInMethod = true; } } - jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + if (!isCallExpression(expression)) { + jsdocType = getJSDocTypeFromAssignmentDeclaration(jsdocType, expression, symbol, declaration); + } if (!jsdocType) { - (types || (types = [])).push(isBinaryExpression(expression) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); + (types || (types = [])).push((isBinaryExpression(expression) || isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType); } } let type = jsdocType; @@ -4860,9 +5021,7 @@ 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; @@ -4904,7 +5063,32 @@ namespace ts { } /** If we don't have an explicit JSDoc type, get the type from the initializer. */ - function getInitializerTypeFromAssignmentDeclaration(symbol: Symbol, resolvedSymbol: Symbol | undefined, expression: BinaryExpression, kind: AssignmentDeclarationKind) { + 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 && kind === AssignmentDeclarationKind.ModuleExports && @@ -4937,9 +5121,7 @@ namespace ts { return result; } if (isEmptyArrayLiteralType(type)) { - if (noImplicitAny) { - reportImplicitAnyError(expression, anyArrayType); - } + reportImplicitAny(expression, anyArrayType); return anyArrayType; } return type; @@ -4989,8 +5171,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; } @@ -5090,9 +5272,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; @@ -5149,7 +5331,7 @@ namespace ts { return type; } if (declaration.kind === SyntaxKind.ExportAssignment) { - return checkExpression((declaration).expression); + return widenTypeForVariableLikeDeclaration(checkExpressionCached((declaration).expression), declaration); } // Handle variable, parameter or property @@ -5158,7 +5340,7 @@ namespace ts { } let type: Type | undefined; if (isInJSFile(declaration) && - (isBinaryExpression(declaration) || isPropertyAccessExpression(declaration) && isBinaryExpression(declaration.parent))) { + (isCallExpression(declaration) || isBinaryExpression(declaration) || isPropertyAccessExpression(declaration) && isBinaryExpression(declaration.parent))) { type = getWidenedTypeFromAssignmentDeclaration(symbol); } else if (isJSDocPropertyLikeTag(declaration) @@ -5195,6 +5377,14 @@ 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)); } @@ -5273,14 +5463,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; } @@ -5563,7 +5751,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 { @@ -5573,9 +5761,6 @@ namespace ts { function getConstructorsForTypeArguments(type: Type, typeArgumentNodes: ReadonlyArray | undefined, location: Node): ReadonlyArray { const typeArgCount = length(typeArgumentNodes); const isJavascript = isInJSFile(location); - if (isJavascriptConstructorType(type) && !typeArgCount) { - return getSignaturesOfType(type, SignatureKind.Call); - } return filter(getSignaturesOfType(type, SignatureKind.Construct), sig => (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= length(sig.typeParameters)); } @@ -5620,7 +5805,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; @@ -5657,7 +5853,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 @@ -5668,8 +5866,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 @@ -5687,7 +5885,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)) { @@ -5745,7 +5943,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); } } } @@ -5999,6 +6197,7 @@ namespace ts { case SyntaxKind.UnknownKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: case SyntaxKind.ObjectKeyword: @@ -6160,7 +6359,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(); @@ -6478,7 +6677,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; } } @@ -6514,8 +6713,7 @@ 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; for (let i = 0; i < signatureLists.length; i++) { for (const signature of signatureLists[i]) { @@ -6561,8 +6759,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 => 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); @@ -6681,6 +6879,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) { @@ -6699,7 +6898,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); @@ -6708,6 +6907,7 @@ 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); @@ -6731,7 +6931,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); @@ -6741,11 +6941,9 @@ 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; + // 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. + const iterationType = constraintType.flags & TypeFlags.Index ? getIndexType(getApparentType((constraintType).type)) : constraintType; forEachType(iterationType, addMemberForKeyType); } setStructuredTypeMembers(type, members, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); @@ -6795,7 +6993,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) { @@ -6941,8 +7139,9 @@ 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); @@ -6994,7 +7193,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; @@ -7242,6 +7445,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 : @@ -7276,10 +7480,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; @@ -7372,8 +7576,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; } @@ -7539,35 +7747,37 @@ 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 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. + const baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny); + const circularityMapper = createTypeMapper(typeParameters!, map(typeParameters!, () => baseDefaultType)); + for (let i = numTypeArguments; i < numTypeParameters; i++) { + result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters![i]) || baseDefaultType, circularityMapper); + } + for (let i = numTypeArguments; i < numTypeParameters; i++) { + const mapper = createTypeMapper(typeParameters!, result); + let defaultType = getDefaultFromTypeParameter(typeParameters![i]); + if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { + defaultType = anyType; + } + result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType; + } + result.length = typeParameters!.length; + return result; + } + return typeArguments && typeArguments.slice(); } function getSignatureFromDeclaration(declaration: SignatureDeclaration | JSDocSignature): Signature { @@ -7813,6 +8023,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) { @@ -8140,7 +8351,7 @@ namespace ts { 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 @@ -8164,7 +8375,7 @@ 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!; @@ -8238,10 +8449,19 @@ 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) @@ -8272,12 +8492,21 @@ 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 { + if (!pushTypeResolution(symbol, TypeSystemPropertyName.JSDocTypeReference)) { + return errorType; + } const assignedType = getAssignedClassType(symbol); const valueType = getTypeOfSymbol(symbol); const referenceType = valueType.symbol && valueType.symbol !== symbol && !isInferredClassType(valueType) && getTypeReferenceTypeWorker(node, valueType.symbol, typeArguments); + if (!popTypeResolution()) { + getSymbolLinks(symbol).resolvedJSDocType = errorType; + error(node, 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)!; + const type = (referenceType && assignedType ? getIntersectionType([assignedType, referenceType]) : referenceType || assignedType)!; + return getSymbolLinks(symbol).resolvedJSDocType = type; } } @@ -8414,7 +8643,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; @@ -8511,6 +8740,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)); } @@ -8552,6 +8785,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. */ @@ -8677,6 +8922,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; @@ -8718,6 +8977,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; @@ -8737,10 +8997,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 { @@ -8812,8 +9070,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); } @@ -8836,25 +9095,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 { @@ -8894,7 +9155,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; } @@ -8905,9 +9166,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. @@ -8935,8 +9197,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; @@ -8967,6 +9232,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); @@ -8982,6 +9248,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)) { @@ -8997,13 +9264,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); } @@ -9030,7 +9300,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; } @@ -9058,11 +9328,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; @@ -9071,7 +9342,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. @@ -9120,14 +9391,24 @@ 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)); + const name = prop.valueDeclaration && getNameOfDeclaration(prop.valueDeclaration) as PropertyName; + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(symbolName(prop)); } if (type && type.flags & include) { return type; @@ -9136,8 +9417,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) { @@ -9152,10 +9433,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) { @@ -9223,19 +9504,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 | undefined, cacheSymbol: boolean, missingType: Type) { const accessExpression = accessNode && accessNode.kind === SyntaxKind.ElementAccessExpression ? accessNode : undefined; - const propName = isTypeUsableAsLateBoundName(indexType) ? getLateBoundNameFromType(indexType) : - accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? - getPropertyNameForKnownSymbolName(idText((accessExpression.argumentExpression).name)) : - undefined; + const propName = isTypeUsableAsLateBoundName(indexType) + ? getLateBoundNameFromType(indexType) + : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) + ? getPropertyNameForKnownSymbolName(idText((accessExpression.argumentExpression).name)) + : 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) { @@ -9243,13 +9528,16 @@ 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); + 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)) { @@ -9261,7 +9549,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))) { @@ -9302,7 +9590,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)); } @@ -9319,6 +9607,16 @@ namespace ts { return missingType; } + function getIndexNodeForAccessExpression(accessNode: ElementAccessExpression | IndexedAccessTypeNode | PropertyName) { + 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); } @@ -9331,6 +9629,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 { @@ -9342,12 +9651,20 @@ 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 @@ -9370,7 +9687,7 @@ namespace ts { 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, missingType = accessNode ? errorType : unknownType): Type { if (objectType === wildcardType || indexType === wildcardType) { return wildcardType; } @@ -9379,7 +9696,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; } @@ -9691,6 +10008,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 @@ -9715,10 +10036,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; @@ -9738,7 +10076,7 @@ namespace ts { skippedPrivateMembers.set(rightProp.escapedName, true); } else if (isSpreadableProperty(rightProp)) { - members.set(rightProp.escapedName, getNonReadonlySymbol(rightProp)); + members.set(rightProp.escapedName, getSpreadSymbol(rightProp)); } } @@ -9762,7 +10100,7 @@ namespace ts { } } else { - members.set(leftProp.escapedName, getNonReadonlySymbol(leftProp)); + members.set(leftProp.escapedName, getSpreadSymbol(leftProp)); } } @@ -9773,25 +10111,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; @@ -9805,7 +10144,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; @@ -9813,10 +10152,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; @@ -9825,22 +10165,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; } @@ -9901,6 +10248,8 @@ namespace ts { return stringType; case SyntaxKind.NumberKeyword: return numberType; + case SyntaxKind.BigIntKeyword: + return bigintType; case SyntaxKind.BooleanKeyword: return booleanType; case SyntaxKind.SymbolKeyword: @@ -10176,7 +10525,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); } @@ -10264,7 +10613,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)) : @@ -10274,6 +10631,8 @@ namespace ts { } return t; }); + type.instantiating = false; + return result; } } return instantiateAnonymousType(type, mapper); @@ -10303,6 +10662,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; @@ -10422,7 +10787,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: @@ -10444,7 +10809,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; @@ -10523,6 +10888,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); } @@ -10543,7 +10912,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)); } @@ -10579,7 +10949,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, relation)) { + if (!errorNode || !elaborateError(expr, source, target, relation, headMessage)) { return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain); } return false; @@ -10589,20 +10959,20 @@ 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, relation: Map): 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)) { + 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, relation); + 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, relation); + return elaborateError((node as BinaryExpression).right, source, target, relation, headMessage); } break; case SyntaxKind.ObjectLiteralExpression: @@ -10611,11 +10981,13 @@ namespace ts { return elaborateArrayLiteral(node as ArrayLiteralExpression, source, target, relation); case SyntaxKind.JsxAttributes: return elaborateJsxAttributes(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): boolean { + 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]) { @@ -10624,7 +10996,7 @@ namespace ts { return !(returnType.flags & (TypeFlags.Any | TypeFlags.Never)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined); })) { const resultObj: { error?: Diagnostic } = {}; - checkTypeAssignableTo(source, target, node, /*errorMessage*/ undefined, /*containingChain*/ undefined, resultObj); + checkTypeAssignableTo(source, target, node, headMessage, /*containingChain*/ undefined, resultObj); const diagnostic = resultObj.error!; addRelatedInfo(diagnostic, createDiagnosticForNode( node, @@ -10636,6 +11008,46 @@ namespace ts { 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; + } + type ElaborationIterator = IterableIterator<{ errorNode: Node, innerExpression: Expression | undefined, nameType: Type, errorMessage?: DiagnosticMessage | undefined }>; /** * For every element returned from the iterator, checks that element to issue an error on a property of that element's type @@ -10647,10 +11059,11 @@ namespace ts { 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, relation); + 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; } @@ -10674,19 +11087,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; @@ -10725,6 +11141,11 @@ namespace ts { if (isTupleLikeType(source)) { 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; } @@ -10732,7 +11153,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; } @@ -10862,13 +11283,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); @@ -10966,6 +11387,10 @@ namespace ts { 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; @@ -11013,6 +11438,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; @@ -11038,11 +11464,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) || @@ -11086,6 +11512,7 @@ namespace ts { ): boolean { let errorInfo: DiagnosticMessageChain | undefined; + let relatedInfo: [DiagnosticRelatedInformation, ...DiagnosticRelatedInformation[]] | undefined; let maybeKeys: string[]; let sourceStack: Type[]; let targetStack: Type[]; @@ -11093,7 +11520,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"); @@ -11124,6 +11551,9 @@ namespace ts { } const diag = createDiagnosticForNodeFromMessageChain(errorNode!, errorInfo, relatedInformation); + if (relatedInfo) { + addRelatedInfo(diag, ...relatedInfo); + } if (errorOutputContainer) { errorOutputContainer.error = diag; } @@ -11131,9 +11561,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) { @@ -11196,12 +11636,12 @@ 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; @@ -11243,7 +11683,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) { @@ -11260,11 +11701,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); @@ -11281,8 +11722,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), @@ -11297,7 +11737,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) { @@ -11317,7 +11757,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; } } @@ -11334,22 +11774,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); @@ -11359,6 +11799,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; @@ -11368,7 +11812,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)) { @@ -11395,15 +11839,16 @@ 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) { // 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. + // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) reportError(Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); } else { @@ -11439,8 +11884,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 { @@ -11540,35 +11985,24 @@ namespace ts { } // 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; } @@ -11605,9 +12039,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; } @@ -11662,7 +12094,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; } @@ -11703,7 +12135,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) { @@ -11728,7 +12160,7 @@ namespace ts { 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) { @@ -11760,12 +12192,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)); @@ -11788,15 +12236,20 @@ namespace ts { 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; + // 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)) { @@ -11814,14 +12267,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; } } @@ -11844,12 +12299,15 @@ namespace ts { 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) { @@ -11918,7 +12376,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 @@ -12005,7 +12463,24 @@ namespace ts { const unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); if (unmatchedProperty) { if (reportErrors) { - reportError(Diagnostics.Property_0_is_missing_in_type_1, symbolToString(unmatchedProperty), typeToString(source)); + const props = arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + 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; } @@ -12159,8 +12634,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); @@ -12371,6 +12846,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 @@ -12389,8 +12883,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; @@ -12407,48 +12900,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. @@ -12680,7 +13183,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; } @@ -12747,6 +13250,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 @@ -12764,9 +13271,14 @@ namespace ts { } 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 { @@ -12787,16 +13299,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 && type.flags & TypeFlags.FreshLiteral ? 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; } @@ -12835,6 +13349,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) { @@ -12850,7 +13368,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; } @@ -12867,10 +13386,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; } @@ -12947,7 +13469,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; @@ -12963,7 +13485,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; @@ -13125,23 +13647,40 @@ 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; 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: @@ -13149,26 +13688,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); } } } @@ -13178,10 +13719,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); @@ -13291,18 +13830,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; @@ -13317,13 +13856,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); @@ -13333,32 +13872,36 @@ 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) { 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; } } } - return undefined; + } + + function getUnmatchedProperty(source: Type, target: Type, requireOptionalProperties: boolean): Symbol | undefined { + return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; } function tupleTypesDefinitelyUnrelated(source: TupleTypeReference, target: TupleTypeReference) { @@ -13383,10 +13926,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; } @@ -13455,7 +14000,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); @@ -13468,11 +14013,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)) { @@ -13481,6 +14028,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 @@ -13521,6 +14086,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; @@ -13554,7 +14122,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; @@ -13582,6 +14165,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) { @@ -13606,6 +14197,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 @@ -13615,31 +14244,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; } } @@ -13702,7 +14307,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); @@ -13760,7 +14370,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) { @@ -13809,15 +14419,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. @@ -13881,17 +14493,17 @@ namespace ts { 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; + 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; + 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; + 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": @@ -14048,19 +14660,38 @@ namespace ts { return undefined; } + function isDiscriminantType(type: Type): boolean { + if (type.flags & TypeFlags.Union) { + if (type.flags & (TypeFlags.Boolean | TypeFlags.EnumLiteral)) { + return true; + } + let combined = 0; + for (const t of (type).types) combined |= t.flags; + if (combined & TypeFlags.Unit && !(combined & TypeFlags.Instantiable)) { + return true; + } + } + return false; + } + 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.HasNonUniformType) && 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) { @@ -14122,7 +14753,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 @@ -14167,21 +14801,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; @@ -14225,7 +14870,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; } @@ -14423,11 +15068,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; } @@ -14473,10 +15122,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; @@ -14619,7 +15270,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; } @@ -14744,8 +15395,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; } @@ -14806,9 +15469,12 @@ 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); } @@ -15074,9 +15740,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; @@ -15093,23 +15759,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]); } } } @@ -15136,6 +15803,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) { @@ -15153,7 +15846,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); @@ -15163,6 +15856,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. @@ -15191,34 +15887,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; @@ -15226,7 +15907,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; } @@ -15246,24 +15927,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) { @@ -15551,7 +16221,12 @@ namespace ts { 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; } } @@ -15609,7 +16284,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)); @@ -15630,6 +16305,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 || @@ -15658,7 +16337,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. @@ -15678,6 +16375,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; @@ -15829,11 +16531,17 @@ 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; } @@ -15848,7 +16556,7 @@ namespace ts { if (isInJS && className) { const classSymbol = checkExpression(className).symbol; if (classSymbol && classSymbol.members && (classSymbol.flags & SymbolFlags.Function)) { - const classType = getJavascriptClassType(classSymbol); + const classType = getJSClassType(classSymbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -15861,7 +16569,7 @@ namespace ts { else if (isInJS && (container.kind === SyntaxKind.FunctionExpression || container.kind === SyntaxKind.FunctionDeclaration) && getJSDocClassTag(container)) { - const classType = getJavascriptClassType(container.symbol); + const classType = getJSClassType(container.symbol); if (classType) { return getFlowTypeOfReference(node, classType); } @@ -15913,6 +16621,31 @@ namespace ts { 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) { @@ -16009,16 +16742,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 // ... @@ -16030,19 +16765,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; @@ -16293,9 +17029,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; } @@ -16358,6 +17107,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); } @@ -16456,6 +17208,10 @@ namespace ts { } 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); } @@ -16474,6 +17230,8 @@ namespace ts { return restType; } } + return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, IndexKind.Number) || + getIndexTypeOfContextualType(t, IndexKind.String); } return undefined; }, /*noReductions*/ true); @@ -16483,11 +17241,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. @@ -16530,7 +17283,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)); } @@ -16579,48 +17331,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; } /** @@ -16661,7 +17424,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: @@ -16707,72 +17472,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 = isInJSFile(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) { @@ -16790,23 +17500,42 @@ namespace ts { 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, isInJSFile(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, isInJSFile(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 @@ -16820,7 +17549,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; @@ -16841,7 +17570,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 ); @@ -16961,7 +17690,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; @@ -16983,7 +17712,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) { @@ -16992,7 +17721,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) { @@ -17004,36 +17733,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) : @@ -17119,6 +17860,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 @@ -17127,7 +17880,7 @@ 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 && @@ -17212,7 +17965,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; @@ -17224,7 +17977,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; } @@ -17274,7 +18027,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; } @@ -17285,9 +18038,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; } @@ -17297,22 +18049,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 { @@ -17322,7 +18071,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)) { @@ -17331,6 +18080,8 @@ namespace ts { else { checkExpression(node.closingElement.tagName); } + + checkJsxChildren(node); } function checkJsxElement(node: JsxElement, _checkMode: CheckMode | undefined): Type { @@ -17339,8 +18090,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 @@ -17348,6 +18099,7 @@ namespace ts { : Diagnostics.JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma); } + checkJsxChildren(node); return getJsxElementTypeAt(node) || anyType; } @@ -17384,16 +18136,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; @@ -17411,7 +18166,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); @@ -17419,7 +18174,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; @@ -17429,7 +18184,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); } } @@ -17447,15 +18202,17 @@ 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))); 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); } } @@ -17463,10 +18220,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. @@ -17474,9 +18231,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; } } @@ -17554,57 +18312,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 = isInJSFile(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) { @@ -17680,193 +18387,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); @@ -17875,37 +18432,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 = isInJSFile(openingLikeElement); - return getUnionType(instantiatedSignatures!.map(sig => getJsxPropsTypeFromClassType(sig, isJs, openingLikeElement, /*reportErrors*/ true))); } /** @@ -17931,57 +18486,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; @@ -18020,7 +18524,7 @@ namespace ts { } } - function checkJsxOpeningLikeElementOrOpeningFragment(node: JsxOpeningLikeElement | JsxOpeningFragment, checkMode: CheckMode | undefined) { + function checkJsxOpeningLikeElementOrOpeningFragment(node: JsxOpeningLikeElement | JsxOpeningFragment) { const isNodeOpeningLikeElement = isJsxOpeningLikeElement(node); if (isNodeOpeningLikeElement) { @@ -18045,10 +18549,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); } } @@ -18090,53 +18592,6 @@ namespace ts { 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 checkJsxExpression(node: JsxExpression, checkMode?: CheckMode) { if (node.expression) { const type = checkExpression(node.expression, checkMode); @@ -18216,7 +18671,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; } @@ -18304,6 +18759,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, @@ -18375,7 +18838,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; } } @@ -18403,6 +18866,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 @@ -18585,7 +19054,7 @@ namespace ts { } function markPropertyAsReferenced(prop: Symbol, nodeForCheckWriteOnly: Node | undefined, isThisAccess: boolean) { - if (!prop || !(prop.flags & SymbolFlags.ClassMember) || !prop.valueDeclaration || !hasModifier(prop.valueDeclaration, ModifierFlags.Private)) { + if (nodeForCheckWriteOnly && isInTypeQuery(nodeForCheckWriteOnly) || !(prop.flags & SymbolFlags.ClassMember) || !prop.valueDeclaration || !hasModifier(prop.valueDeclaration, ModifierFlags.Private)) { return; } if (nodeForCheckWriteOnly && isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & SymbolFlags.SetAccessor && !(prop.flags & SymbolFlags.GetAccessor))) { @@ -18730,13 +19199,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); } @@ -18783,9 +19245,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 { @@ -18798,6 +19259,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); @@ -18873,14 +19337,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; @@ -18902,6 +19367,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' @@ -18922,13 +19396,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) { @@ -18966,15 +19449,10 @@ namespace ts { 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); @@ -18992,6 +19470,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 @@ -19111,6 +19593,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 @@ -19118,31 +19614,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( @@ -19153,7 +19631,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) { @@ -19231,7 +19709,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; @@ -19382,6 +19860,7 @@ namespace ts { const isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; const isDecorator = node.kind === SyntaxKind.Decorator; const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node); + const reportErrors = !candidatesOutArray; let typeArguments: NodeArray | undefined; @@ -19398,7 +19877,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); } @@ -19474,34 +19955,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)); + } } } @@ -19558,7 +20037,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) { @@ -19571,7 +20053,10 @@ namespace ts { checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration)); } 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; } } @@ -19763,12 +20248,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) { @@ -19780,12 +20265,12 @@ 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 { let relatedInformation: DiagnosticRelatedInformation | undefined; - if (node.arguments.length === 1 && isTypeAssertion(first(node.arguments))) { + 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); @@ -19878,7 +20363,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) { @@ -19996,9 +20481,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); } @@ -20046,8 +20531,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); } @@ -20070,6 +20555,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. @@ -20082,26 +20620,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: @@ -20114,19 +20632,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."); } @@ -20161,38 +20667,40 @@ namespace ts { * Indicates whether a declaration can be treated as a constructor in a JavaScript * file. */ - function isJavascriptConstructor(node: Declaration | undefined): boolean { - if (node && isInJSFile(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; - + const symbol = getSymbolOfNode(func); return !!symbol && symbol.members !== 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)) { + if (valueType.symbol && !isInferredClassType(valueType) && isJSConstructor(valueType.symbol.valueDeclaration)) { inferred = getInferredClassType(valueType.symbol); } return assigned && inferred ? @@ -20200,21 +20708,18 @@ namespace ts { 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; } @@ -20275,7 +20780,7 @@ namespace ts { if (!funcSymbol && node.expression.kind === SyntaxKind.Identifier) { funcSymbol = getResolvedSymbol(node.expression as Identifier); } - const type = funcSymbol && getJavascriptClassType(funcSymbol); + const type = funcSymbol && getJSClassType(funcSymbol); if (type) { return signature.target ? instantiateType(type, signature.mapper) : type; } @@ -20688,6 +21193,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) { @@ -20924,7 +21441,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); } @@ -21000,6 +21517,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)) { @@ -21057,7 +21575,6 @@ namespace ts { } } checkSignatureDeclaration(node); - checkNodeDeferred(node); } } @@ -21115,25 +21632,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 { @@ -21227,13 +21778,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: @@ -21243,7 +21803,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); @@ -21253,12 +21819,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; } @@ -21271,11 +21837,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; } @@ -21304,6 +21880,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) || @@ -21460,7 +22037,7 @@ namespace ts { if (element.kind !== SyntaxKind.SpreadElement) { const propName = "" + elementIndex as __String; const type = isTypeAny(sourceType) ? sourceType : - isTupleLikeType(sourceType) ? getTupleElementType(sourceType, elementIndex) : + everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : elementType; if (type) { return checkDestructuringAssignment(element, type, checkMode); @@ -21486,8 +22063,8 @@ namespace ts { } 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))) : + const type = everyType(sourceType, isTupleType) ? + mapType(sourceType, t => sliceTupleType(t, elementIndex)) : createArrayType(elementType); return checkDestructuringAssignment(restExpression, type, checkMode); } @@ -21558,6 +22135,7 @@ namespace ts { case SyntaxKind.TemplateExpression: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.NullKeyword: @@ -21668,17 +22246,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) { @@ -21696,6 +22295,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; @@ -21727,7 +22330,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(); } } @@ -21760,8 +22365,17 @@ namespace ts { leftType; case SyntaxKind.EqualsToken: const declKind = isBinaryExpression(left.parent) ? getAssignmentDeclarationKind(left.parent) : AssignmentDeclarationKind.None; - checkAssignmentDeclaration(declKind, right); + 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 { @@ -21778,9 +22392,8 @@ namespace ts { return Debug.fail(); } - function checkAssignmentDeclaration(kind: AssignmentDeclarationKind, right: Expression) { + function checkAssignmentDeclaration(kind: AssignmentDeclarationKind, rightType: Type) { if (kind === AssignmentDeclarationKind.ModuleExports) { - const rightType = checkExpression(right, checkMode); for (const prop of getPropertiesOfObjectType(rightType)) { const propType = getTypeOfSymbol(prop); if (propType.symbol && propType.symbol.flags & SymbolFlags.Class) { @@ -21984,7 +22597,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; @@ -22034,15 +22647,11 @@ namespace ts { isTypeAssertion(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; } } @@ -22062,6 +22671,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); } @@ -22069,17 +22679,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); } @@ -22179,13 +22790,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); } @@ -22215,7 +22826,7 @@ namespace ts { 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); @@ -22231,6 +22842,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: @@ -22240,7 +22854,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: @@ -22301,7 +22915,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: @@ -23000,7 +23614,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; } @@ -23033,8 +23647,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); @@ -23792,41 +24406,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); @@ -23837,6 +24420,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; @@ -23969,6 +24590,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)) { @@ -24058,8 +24686,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)) { @@ -24684,10 +25312,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); } } } @@ -24737,6 +25365,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 @@ -24752,7 +25385,6 @@ namespace ts { 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)); } } @@ -24945,7 +25577,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 @@ -25173,14 +25805,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]; } } @@ -25211,9 +25847,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; + } } } @@ -25632,6 +26270,7 @@ namespace ts { case "any": case "unknown": case "number": + case "bigint": case "boolean": case "string": case "symbol": @@ -25825,8 +26464,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); } @@ -25838,7 +26480,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); } } @@ -25866,7 +26508,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); } } } @@ -26089,6 +26731,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); @@ -26543,7 +27187,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; @@ -26956,7 +27600,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: @@ -27122,14 +27766,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: @@ -27190,10 +27841,10 @@ namespace ts { clear(potentialThisCollisions); clear(potentialNewTargetCollisions); - deferredNodes = createMap(); forEach(node.statements, checkSourceElement); + checkSourceElement(node.endOfFileToken); - checkDeferredNodes(); + checkDeferredNodes(node); if (isExternalOrCommonJsModule(node)) { registerForUnusedIdentifiersCheck(node); @@ -27207,8 +27858,6 @@ namespace ts { }); } - deferredNodes = undefined; - if (isExternalOrCommonJsModule(node)) { checkExternalModuleExports(node); } @@ -27308,8 +27957,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); @@ -27427,12 +28079,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"; } @@ -27597,9 +28249,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); @@ -27623,7 +28272,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); @@ -27691,6 +28343,9 @@ namespace ts { ) { return resolveExternalModuleName(node, node); } + if (isCallExpression(parent) && isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) { + return getSymbolOfNode(parent); + } // falls through case SyntaxKind.NumericLiteral: @@ -27710,6 +28365,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; } @@ -27735,24 +28393,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; } @@ -27794,10 +28448,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) { @@ -27886,8 +28536,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); } @@ -27900,7 +28553,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]; } @@ -28151,7 +28804,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; } @@ -28308,6 +28962,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; } @@ -28405,20 +29062,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, enclosing: Node): Expression { - const enumResult = type.flags & TypeFlags.EnumLiteral && nodeBuilder.symbolToExpression(type.symbol, SymbolFlags.Value, enclosing); - return enumResult || 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, node); + return literalTypeToNode(type, node, tracker); } function createResolver(): EmitResolver { @@ -28505,7 +29162,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) { @@ -28618,6 +29280,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); } @@ -28663,6 +29328,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); @@ -28690,38 +29357,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) { @@ -29781,6 +30443,12 @@ 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))) && @@ -29789,19 +30457,25 @@ namespace ts { } function checkAmbientInitializer(node: VariableDeclaration | PropertyDeclaration | PropertySignature) { - if (node.initializer) { - const isInvalidInitializer = !(isStringOrNumberLiteralExpression(node.initializer) || isSimpleLiteralEnumReference(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_or_literal_enum_reference); + 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); } } } @@ -29965,10 +30639,11 @@ namespace ts { } function checkGrammarConstructorTypeParameters(node: ConstructorDeclaration) { - const jsdocTypeParameters = isInJSFile(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); } } @@ -30110,6 +30785,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)) { diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index edee847019a..18e88ad9d3a 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,30 @@ 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 }, ]; @@ -138,11 +166,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 +187,8 @@ namespace ts { es2018: ScriptTarget.ES2018, esnext: ScriptTarget.ESNext, }), + affectsSourceFile: true, + affectsModuleResolution: true, paramType: Diagnostics.VERSION, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, @@ -177,6 +207,7 @@ namespace ts { es2015: ModuleKind.ES2015, esnext: ModuleKind.ESNext }), + affectsModuleResolution: true, paramType: Diagnostics.KIND, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, @@ -189,6 +220,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 +228,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 +246,7 @@ namespace ts { "react-native": JsxEmit.ReactNative, "react": JsxEmit.React }), + affectsSourceFile: true, paramType: Diagnostics.KIND, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, @@ -323,6 +357,7 @@ namespace ts { { name: "noImplicitAny", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -331,6 +366,7 @@ namespace ts { { name: "strictNullChecks", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -339,14 +375,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 +401,7 @@ namespace ts { { name: "noImplicitThis", type: "boolean", + affectsSemanticDiagnostics: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -363,6 +410,7 @@ namespace ts { { name: "alwaysStrict", type: "boolean", + affectsSourceFile: true, strictFlag: true, showInSimplifiedHelpView: true, category: Diagnostics.Strict_Type_Checking_Options, @@ -397,6 +445,7 @@ namespace ts { { name: "noFallthroughCasesInSwitch", type: "boolean", + affectsBindDiagnostics: true, affectsSemanticDiagnostics: true, showInSimplifiedHelpView: true, category: Diagnostics.Additional_Checks, @@ -410,6 +459,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 +467,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 +477,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 +493,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 +505,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 +516,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 @@ -549,30 +604,12 @@ namespace ts { 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,137 @@ 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 ? _ => false : matchesSpecs( + configFileName, + configParseResult.configFileSpecs.validatedIncludeSpecs, + configParseResult.configFileSpecs.validatedExcludeSpecs + ) + ), + f => getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, 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, + }, + 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 _ => false; + 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 _ => false; + } + + 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, 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 +1803,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 +1816,7 @@ namespace ts { case "object": return {}; default: - return (option as CommandLineOptionOfCustomType).type.keys().next().value; + return option.type.keys().next().value; } } @@ -1825,7 +1964,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, @@ -1845,7 +1985,8 @@ namespace ts { filesSpecs = >raw.files; const hasReferences = hasProperty(raw, "references") && !isNullOrUndefined(raw.references); const hasZeroOrNoReferences = !hasReferences || raw.references.length === 0; - if (filesSpecs.length === 0 && hasZeroOrNoReferences) { + 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; @@ -1898,19 +2039,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, @@ -1918,7 +2058,6 @@ namespace ts { }); } } - result.projectReferences = references; } else { createCompilerDiagnosticOnlyIfJson(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "references", "Array"); @@ -1935,13 +2074,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", @@ -1949,6 +2086,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; @@ -1991,7 +2149,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; @@ -2115,24 +2273,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, @@ -2141,7 +2303,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); @@ -2151,8 +2313,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)) { @@ -2265,7 +2427,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); } @@ -2407,7 +2569,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); } @@ -2436,11 +2598,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. @@ -2451,8 +2618,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. // @@ -2478,16 +2662,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 }; @@ -2629,7 +2806,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 */ @@ -2657,7 +2834,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 9eabae70d2e..4fe6674d3f5 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.2"; /** 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; } @@ -511,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) { @@ -800,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]; @@ -823,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 { @@ -838,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; } @@ -852,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; } } @@ -1020,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 { @@ -1040,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) { @@ -1135,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]); @@ -1234,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); @@ -1409,9 +1443,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; @@ -1534,6 +1571,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; @@ -1598,8 +1636,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) { @@ -2026,7 +2065,6 @@ namespace ts { } /** Represents a "prefix*suffix" pattern. */ - /* @internal */ export interface Pattern { prefix: string; suffix: string; @@ -2125,4 +2163,8 @@ namespace ts { deleted(oldItems[oldIndex++]); } } + + export function fill(length: number, cb: (index: number) => T): T[] { + return new Array(length).fill(0).map((_, i) => cb(i)); + } } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 18b64b74e0a..e3f8e1a7ad5 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1007,6 +1007,10 @@ "category": "Error", "code": 1349 }, + "Print the final configuration instead of building.": { + "category": "Message", + "code": 1350 + }, "Duplicate identifier '{0}'.": { "category": "Error", @@ -1056,7 +1060,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 +1236,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 +1260,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 +1488,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 }, @@ -1816,7 +1820,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 +1944,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 }, @@ -2088,15 +2092,15 @@ "category": "Error", "code": 2577 }, - "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i @types/node`.": { + "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`.": { + "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`.": { + "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 }, @@ -2112,6 +2116,18 @@ "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 @@ -2477,14 +2493,42 @@ "category": "Error", "code": 2732 }, - "Index '{0}' is out-of-bounds in tuple of length {1}.": { - "category": "Error", - "code": 2733 - }, "It is highly likely that you are missing a semicolon.": { "category": "Error", "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 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", @@ -2948,7 +2992,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", @@ -3748,10 +3795,26 @@ "category": "Message", "code": 6212 }, - "Did you mean to use `new` with this expression?": { + "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", @@ -3874,10 +3937,6 @@ "category": "Error", "code": 6370 }, - "Skipping clean because not all projects could be located": { - "category": "Error", - "code": 6371 - }, "The expected type comes from property '{0}' which is declared here on type '{1}'": { "category": "Message", @@ -3887,6 +3946,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", @@ -3916,6 +3979,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 @@ -4026,6 +4093,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 @@ -4146,6 +4250,10 @@ "category": "Error", "code": 8030 }, + "You cannot rename a module via a global import.": { + "category": "Error", + "code": 8031 + }, "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause.": { "category": "Error", "code": 9002 @@ -4404,6 +4512,10 @@ "category": "Message", "code": 90033 }, + "Add parameter name": { + "category": "Message", + "code": 90034 + }, "Convert function to an ES2015 class": { "category": "Message", "code": 95001 @@ -4644,7 +4756,6 @@ "category": "Message", "code": 95062 }, - "Add missing enum member '{0}'": { "category": "Message", "code": 95063 @@ -4653,12 +4764,40 @@ "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 } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 2d103b8af8f..15b6540900f 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 = 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 }; } } @@ -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,52 +133,62 @@ 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(); @@ -192,7 +200,7 @@ namespace ts { } 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) { @@ -1504,7 +1653,7 @@ namespace ts { let indentAfterDot = false; if (!(getEmitFlags(node) & EmitFlags.NoIndentation)) { const dotRangeStart = node.expression.end; - const dotRangeEnd = skipTrivia(currentSourceFile.text, node.expression.end) + 1; + const dotRangeEnd = skipTrivia(currentSourceFile!.text, node.expression.end) + 1; const dotToken = createToken(SyntaxKind.DotToken); dotToken.pos = dotRangeStart; dotToken.end = dotRangeEnd; @@ -1513,7 +1662,7 @@ namespace ts { } emitExpression(node.expression); - increaseIndentIf(indentBeforeDot); + increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); const shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); if (shouldEmitDotDot) { @@ -1521,7 +1670,7 @@ namespace ts { } emitTokenWithComment(SyntaxKind.DotToken, node.expression.end, writePunctuation, node); - increaseIndentIf(indentAfterDot); + increaseIndentIf(indentAfterDot, /*writeSpaceIfNotIndenting*/ false); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); } @@ -1532,7 +1681,7 @@ namespace ts { 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); + const text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); return !expression.numericLiteralFlags && !stringContains(text, tokenToString(SyntaxKind.DotToken)!); } @@ -1668,11 +1817,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 +1833,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 +1858,7 @@ namespace ts { } function emitSpreadExpression(node: SpreadElement) { - writePunctuation("..."); + emitTokenWithComment(SyntaxKind.DotDotDotToken, node.pos, writePunctuation, node); emitExpression(node.expression); } @@ -1771,19 +1920,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 +1996,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 +2045,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 +2059,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 +2081,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 +2113,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 +2134,7 @@ namespace ts { function emitDebuggerStatement(node: DebuggerStatement) { writeToken(SyntaxKind.DebuggerKeyword, node.pos, writeKeyword); - writeSemicolon(); + writeTrailingSemicolon(); } // @@ -2048,7 +2205,7 @@ namespace ts { } else { emitSignatureHead(node); - writeSemicolon(); + writeTrailingSemicolon(); } } @@ -2076,7 +2233,7 @@ namespace ts { return false; } - if (!nodeIsSynthesized(body) && !rangeIsOnSingleLine(body, currentSourceFile)) { + if (!nodeIsSynthesized(body) && !rangeIsOnSingleLine(body, currentSourceFile!)) { return false; } @@ -2194,7 +2351,7 @@ namespace ts { writePunctuation("="); writeSpace(); emit(node.type); - writeSemicolon(); + writeTrailingSemicolon(); } function emitEnumDeclaration(node: EnumDeclaration) { @@ -2218,7 +2375,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 +2408,7 @@ namespace ts { emitTokenWithComment(SyntaxKind.EqualsToken, node.name.end, writePunctuation, node); writeSpace(); emitModuleReference(node.moduleReference); - writeSemicolon(); + writeTrailingSemicolon(); } function emitModuleReference(node: ModuleReference) { @@ -2274,7 +2431,7 @@ namespace ts { writeSpace(); } emitExpression(node.moduleSpecifier); - writeSemicolon(); + writeTrailingSemicolon(); } function emitImportClause(node: ImportClause) { @@ -2313,7 +2470,7 @@ namespace ts { } writeSpace(); emitExpression(node.expression); - writeSemicolon(); + writeTrailingSemicolon(); } function emitExportDeclaration(node: ExportDeclaration) { @@ -2332,7 +2489,7 @@ namespace ts { writeSpace(); emitExpression(node.moduleSpecifier); } - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamespaceExportDeclaration(node: NamespaceExportDeclaration) { @@ -2343,7 +2500,7 @@ namespace ts { nextPos = emitTokenWithComment(SyntaxKind.NamespaceKeyword, nextPos, writeKeyword, node); writeSpace(); emit(node.name); - writeSemicolon(); + writeTrailingSemicolon(); } function emitNamedExports(node: NamedExports) { @@ -2421,7 +2578,6 @@ namespace ts { } function emitJsxText(node: JsxText) { - commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } @@ -2490,7 +2646,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 +2715,7 @@ namespace ts { function emitSpreadAssignment(node: SpreadAssignment) { if (node.expression) { - writePunctuation("..."); + emitTokenWithComment(SyntaxKind.DotDotDotToken, node.pos, writePunctuation, node); emitExpression(node.expression); } } @@ -2573,6 +2729,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 +2908,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 +3000,7 @@ namespace ts { setSourceFile(sourceFile); emitPrologueDirectives(sourceFile.statements, /*startWithNewLine*/ true, seenPrologueDirectives); } + setSourceFile(undefined); } } @@ -2703,7 +3008,7 @@ namespace ts { if (isSourceFile(sourceFileOrBundle)) { const shebang = getShebang(sourceFileOrBundle.text); if (shebang) { - write(shebang); + writeComment(shebang); writeLine(); return true; } @@ -2790,7 +3095,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(); } } @@ -2864,6 +3175,11 @@ namespace ts { writeSpace(); writePunctuation("|"); break; + case ListFormat.AsteriskDelimited: + writeSpace(); + writePunctuation("*"); + writeSpace(); + break; case ListFormat.AmpersandDelimited: writeSpace(); writePunctuation("&"); @@ -2933,7 +3249,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 */ @@ -3027,89 +3348,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); } @@ -3148,18 +3451,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(); } } @@ -3167,7 +3470,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(); } @@ -3188,13 +3491,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 { @@ -3214,7 +3517,7 @@ namespace ts { return synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format); } else { - return !rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile); + return !rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile!); } } else { @@ -3233,13 +3536,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 { @@ -3273,12 +3576,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) { @@ -3303,23 +3606,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); } /** @@ -3588,7 +3891,7 @@ namespace ts { } } - function makeFileLevelOptmiisticUniqueName(name: string) { + function makeFileLevelOptimisticUniqueName(name: string) { return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true); } @@ -3710,6 +4013,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(currentSourceFile!, 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..8433ee6e489 --- /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 = new Set(); + const nameStack: string[] = []; + return (obj, name, cbOk, cbFail) => { + if (seen.has(obj) || nameStack.length > 4) { + return cbFail(seen.has(obj), nameStack); + } + + seen.add(obj); + nameStack.push(name); + const res = cbOk(); + nameStack.pop(); + seen.delete(obj); + 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: ReadonlySet = new Set(["arguments", "caller", "constructor", "eval", "super_"]); + const reservedFunctionProperties: ReadonlySet = new Set(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.has(key) && + (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + // 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 name.startsWith("_"); + } + + 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 aedd1d4c3dc..b8aa9fa2df4 100644 --- a/src/compiler/moduleNameResolver.ts +++ b/src/compiler/moduleNameResolver.ts @@ -62,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' */ } @@ -74,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 }; } @@ -98,6 +99,7 @@ namespace ts { types?: string; typesVersions?: MapLike>; main?: string; + tsconfig?: string; } interface PackageJson extends PackageJsonPathFields { @@ -126,7 +128,7 @@ namespace ts { return value; } - function readPackageJsonPathField(jsonContent: PackageJson, fieldName: K, baseDirectory: string, state: ModuleResolutionState): PackageJson[K] | undefined { + 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)); @@ -141,6 +143,10 @@ namespace ts { || 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); } @@ -258,8 +264,11 @@ 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); + if (redirectedReference) { + options = redirectedReference.commandLine.options; + } const failedLookupLocations: string[] = []; const moduleResolutionState: ModuleResolutionState = { compilerOptions: options, host, traceEnabled, failedLookupLocations }; @@ -281,6 +290,9 @@ 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); + } } let resolved = primaryLookup(); @@ -292,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 }; @@ -310,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); @@ -337,8 +347,16 @@ namespace ts { if (traceEnabled) { trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); } - const result = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, 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); } @@ -381,8 +399,13 @@ namespace ts { // 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); + } } } } @@ -397,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; } /** @@ -405,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 { @@ -415,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 { @@ -530,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) { @@ -560,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}`); @@ -573,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); } } } @@ -663,6 +730,9 @@ namespace ts { function tryLoadModuleUsingOptionalResolutionSettings(extensions: Extensions, moduleName: string, containingDirectory: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState): Resolved | undefined { + const resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state); + if (resolved) return resolved.value; + if (!isExternalModuleNameRelative(moduleName)) { return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state); } @@ -671,6 +741,17 @@ namespace ts { } } + 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, state: ModuleResolutionState): Resolved | undefined { @@ -749,22 +830,13 @@ namespace ts { } function tryLoadModuleUsingBaseUrl(extensions: Extensions, moduleName: string, loader: ResolutionKindSpecificLoader, state: ModuleResolutionState): Resolved | undefined { - const { baseUrl, paths } = state.compilerOptions; + 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, baseUrl, moduleName); } - if (paths) { - if (state.traceEnabled) { - trace(state.host, Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - const resolved = tryLoadModuleUsingPaths(extensions, moduleName, baseUrl, paths, loader, /*onlyRecordFailures*/ false, state); - if (resolved) { - return resolved.value; - } - } 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); @@ -778,30 +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; } - export function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache?: ModuleResolutionCache): ResolvedModuleWithFailedLookupLocations { - return nodeModuleNameResolverWorker(moduleName, getDirectoryPath(containingFile), compilerOptions, host, cache, /*jsOnly*/ false); + /* @internal */ + export function tryResolveJSModule(moduleName: string, initialDir: string, host: ModuleResolutionHost): string | undefined { + const { resolvedModule } = tryResolveJSModuleWorker(moduleName, initialDir, host); + return resolvedModule && resolvedModule.resolvedFileName; } - function nodeModuleNameResolverWorker(moduleName: string, containingDirectory: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, cache: ModuleResolutionCache | undefined, jsOnly: boolean): ResolvedModuleWithFailedLookupLocations { + 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, 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); @@ -812,14 +895,14 @@ namespace ts { 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 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache); + const resolved = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference); if (!resolved) return undefined; let resolvedValue = resolved.value; @@ -889,6 +972,10 @@ namespace ts { /*@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`. @@ -945,9 +1032,9 @@ namespace ts { * 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, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined { - if (extensions === Extensions.Json) { + if (extensions === Extensions.Json || extensions === Extensions.TSConfig) { const extensionLess = tryRemoveExtension(candidate, Extension.Json); - return extensionLess === undefined ? undefined : tryAddingExtensions(extensionLess, extensions, 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" @@ -958,7 +1045,7 @@ namespace ts { // 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); @@ -985,6 +1072,7 @@ 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); } @@ -1022,15 +1110,6 @@ namespace ts { return withPackageId(packageId, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths)); } - function loadNodeModuleFromDirectoryWorker(extensions: Extensions, candidate: string, onlyRecordFailures: boolean, state: ModuleResolutionState, packageJsonContent: PackageJsonPathFields | undefined, versionPaths: VersionPaths | undefined): PathAndExtension | undefined { - const fromPackageJson = packageJsonContent && loadModuleFromPackageJson(packageJsonContent, versionPaths, extensions, candidate, state); - if (fromPackageJson) { - return fromPackageJson; - } - const directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - return loadModuleFromFile(extensions, combinePaths(candidate, "index"), !directoryExists, state); - } - interface PackageJsonInfo { packageJsonContent: PackageJsonPathFields | undefined; packageId: PackageId | undefined; @@ -1052,7 +1131,7 @@ namespace ts { const jsPath = readPackageJsonMainField(packageJsonContent, packageDirectory, state); if (typeof jsPath === "string" && jsPath.length > packageDirectory.length) { const potentialSubModule = jsPath.substring(packageDirectory.length + 1); - subModuleName = (forEach(supportedJavascriptExtensions, extension => + subModuleName = (forEach(supportedJSExtensions, extension => tryRemoveExtension(potentialSubModule, extension)) || potentialSubModule) + Extension.Dts; } else { @@ -1090,20 +1169,26 @@ namespace ts { } } - function loadModuleFromPackageJson(jsonContent: PackageJsonPathFields, versionPaths: VersionPaths | undefined, extensions: Extensions, candidate: string, state: ModuleResolutionState): PathAndExtension | undefined { - let file = extensions !== Extensions.JavaScript && extensions !== Extensions.Json - ? readPackageJsonTypesFields(jsonContent, candidate, state) - : readPackageJsonMainField(jsonContent, candidate, state); - if (!file) { - if (extensions === Extensions.TypeScript) { - // When resolving typescript modules, try resolving using main field as well - file = readPackageJsonMainField(jsonContent, candidate, state); - if (!file) { - return undefined; - } - } - else { - 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); } } @@ -1125,21 +1210,26 @@ namespace ts { return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false); }; - const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(file), state.host); + 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 && containsPath(candidate, file)) { - const moduleName = getRelativePathFromDirectory(candidate, file, /*ignoreCase*/ false); + if (versionPaths && (!packageFile || containsPath(candidate, packageFile))) { + const moduleName = getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false); 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, moduleName); } - const result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailures, state); + const result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state); if (result) { return removeIgnoredPackageId(result.value); } } // It won't have a `packageId` set, because we disabled `considerPackageJson`. - return removeIgnoredPackageId(loader(extensions, file, onlyRecordFailures, state)); + 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. */ @@ -1153,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: @@ -1171,17 +1262,17 @@ namespace ts { return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) }; } - function loadModuleFromNearestNodeModulesDirectory(extensions: Extensions, moduleName: string, directory: string, state: ModuleResolutionState, cache: NonRelativeModuleNameResolutionCache | undefined): SearchResult { - return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache); + 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 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); + 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): SearchResult { - const perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); + 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); @@ -1204,7 +1295,7 @@ namespace ts { 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)) { @@ -1349,7 +1440,7 @@ namespace ts { } } - 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 failedLookupLocations: string[] = []; const state: ModuleResolutionState = { compilerOptions, host, traceEnabled, failedLookupLocations }; @@ -1366,7 +1457,7 @@ namespace ts { } 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, state); diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index 6033d95b2a5..1913ee90b2b 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 { @@ -260,6 +260,9 @@ 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; @@ -267,8 +270,8 @@ namespace ts.moduleSpecifiers { const packageRootPath = moduleFileName.substring(0, parts.packageRootIndex); const packageJsonPath = combinePaths(packageRootPath, "package.json"); - const packageJsonContent = host.fileExists!(packageJsonPath) - ? JSON.parse(host.readFile!(packageJsonPath)!) + const packageJsonContent = host.fileExists(packageJsonPath) + ? JSON.parse(host.readFile(packageJsonPath)!) : undefined; const versionPaths = packageJsonContent && packageJsonContent.typesVersions ? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions) @@ -325,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; } } @@ -415,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 415a62e5627..3e98b6cbdbc 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); } @@ -1482,7 +1476,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: @@ -1510,8 +1512,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: @@ -2237,8 +2241,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; @@ -2882,8 +2885,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 { @@ -2892,6 +2896,7 @@ namespace ts { case SyntaxKind.UnknownKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.SymbolKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.UndefinedKeyword: @@ -2912,11 +2917,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(); @@ -2950,6 +2956,7 @@ namespace ts { case SyntaxKind.UnknownKeyword: case SyntaxKind.StringKeyword: case SyntaxKind.NumberKeyword: + case SyntaxKind.BigIntKeyword: case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: case SyntaxKind.UniqueKeyword: @@ -2967,6 +2974,7 @@ namespace ts { case SyntaxKind.NewKeyword: case SyntaxKind.StringLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.ObjectKeyword: @@ -2980,7 +2988,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. @@ -3205,6 +3213,7 @@ namespace ts { case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.TemplateHead: @@ -4614,6 +4623,7 @@ namespace ts { function parsePrimaryExpression(): PrimaryExpression { switch (token()) { case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: return parseLiteralNode(); @@ -4728,8 +4738,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); @@ -5130,7 +5139,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 { @@ -6308,7 +6317,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); @@ -6441,13 +6450,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(); @@ -6462,7 +6464,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; @@ -6538,51 +6542,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; } @@ -6665,9 +6668,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); } @@ -6724,7 +6726,7 @@ namespace ts { } } - function parseParameterOrPropertyTag(atToken: AtToken, tagName: Identifier, target: PropertyLikeParse, indent: number): JSDocParameterTag | JSDocPropertyTag { + function parseParameterOrPropertyTag(start: number, tagName: Identifier, target: PropertyLikeParse, indent: number): JSDocParameterTag | JSDocPropertyTag { let typeExpression = tryParseTypeExpression(); let isNameFirst = !typeExpression; skipWhitespaceOrAsterisk(); @@ -6737,15 +6739,14 @@ namespace ts { } const result = target === PropertyLikeParse.Property ? - createNode(SyntaxKind.JSDocPropertyTag, atToken.pos) : - createNode(SyntaxKind.JSDocParameterTag, atToken.pos); - const comment = parseTagComments(indent + scanner.getStartPos() - atToken.pos); + 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; @@ -6779,33 +6780,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); @@ -6834,37 +6832,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); @@ -6877,7 +6871,6 @@ namespace ts { let child: JSDocTypeTag | JSDocPropertyTag | false; let jsdocTypeLiteral: JSDocTypeLiteral | undefined; let childTypeTag: JSDocTypeTag | undefined; - const start = atToken.pos; while (child = tryParse(() => parseChildPropertyTag(indent))) { if (!jsdocTypeLiteral) { jsdocTypeLiteral = createNode(SyntaxKind.JSDocTypeLiteral, start); @@ -6931,9 +6924,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); @@ -6941,7 +6933,6 @@ 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, indent) as JSDocParameterTag)) { @@ -7029,8 +7020,7 @@ namespace ts { 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(); @@ -7038,7 +7028,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; @@ -7054,10 +7044,10 @@ namespace ts { if (!(target & t)) { return false; } - return parseParameterOrPropertyTag(atToken, tagName, target, indent); + 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) { @@ -7075,8 +7065,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); @@ -7724,7 +7713,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 @@ -7779,7 +7768,7 @@ 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 if (arg!.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; @@ -7802,7 +7791,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": { @@ -7812,11 +7801,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; } @@ -7852,10 +7841,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; @@ -7882,10 +7871,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; } @@ -7904,9 +7893,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; @@ -7914,7 +7903,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 61bf38db805..15c09a1a79b 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -198,7 +198,7 @@ namespace ts { }; } - 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 +207,7 @@ namespace ts { ...program.getSemanticDiagnostics(sourceFile, cancellationToken) ]; - if (program.getCompilerOptions().declaration) { + if (getEmitDeclarations(program.getCompilerOptions())) { addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken)); } @@ -406,7 +406,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 +418,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 +442,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 +454,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 +485,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 +534,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 +594,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. @@ -594,18 +630,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 +652,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. @@ -646,8 +681,8 @@ namespace ts { 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; const shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options); const structuralIsReused = tryReuseStructureFromOldProgram(); @@ -656,15 +691,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 +710,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 +726,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(); @@ -715,10 +753,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 +805,12 @@ namespace ts { isEmittedFile, getConfigFileParsingDiagnostics, getResolvedModuleWithFailedLookupLocationsFromCache, - getProjectReferences + getProjectReferences, + getResolvedProjectReferences, + getProjectReferenceRedirect, + getResolvedProjectReferenceToRedirect, + getResolvedProjectReferenceByPath, + forEachResolvedProjectReference }; verifyCompilerOptions(); @@ -798,9 +849,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 +882,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 +953,7 @@ namespace ts { } } else { - resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, oldProgramState); + resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName); } if (resolvesToAmbientModuleInNonModifiedFile) { @@ -922,7 +966,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 +996,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 +1008,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 +1070,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 +1095,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 +1126,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 +1203,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 +1230,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 +1254,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 +1270,6 @@ namespace ts { fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile); } resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives(); - resolvedProjectReferences = oldProgram.getProjectReferences(); sourceFileToPackageName = oldProgram.sourceFileToPackageName; redirectTargetsMap = oldProgram.redirectTargetsMap; @@ -1257,10 +1307,14 @@ namespace ts { }; } - function getProjectReferences() { + function getResolvedProjectReferences() { return resolvedProjectReferences; } + function getProjectReferences() { + return projectReferences; + } + function getPrependNodes(): InputFiles[] { if (!projectReferences) { return emptyArray; @@ -1271,12 +1325,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 +1406,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); } @@ -1440,7 +1495,7 @@ namespace ts { // constructs from within a JavaScript file as syntactic errors. if (isSourceFileJS(sourceFile)) { if (!sourceFile.additionalSyntacticDiagnostics) { - sourceFile.additionalSyntacticDiagnostics = getJavascriptSyntacticDiagnosticsForFile(sourceFile); + sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile); } return concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics); } @@ -1538,7 +1593,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 +1819,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 { @@ -1825,12 +1891,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 +1945,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; + } } } @@ -1924,7 +2000,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 +2059,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 +2082,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 @@ -2044,7 +2124,7 @@ namespace ts { return file; } - let redirectedPath: string | undefined; + let redirectedPath: Path | undefined; if (refFile) { const redirect = getProjectReferenceRedirect(fileName); if (redirect) { @@ -2076,9 +2156,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 +2169,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(); @@ -2135,26 +2212,112 @@ namespace ts { return file; } + function addFileToFilesByName(file: SourceFile | undefined, path: Path, redirectedPath: Path | undefined) { + filesByName.set(path, file); + if (redirectedPath) { + filesByName.set(redirectedPath, 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) { + 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) { + return forEachResolvedProjectReference((referencedProject, referenceProjectPath) => { + // not input file from the referenced project, ignore + if (!referencedProject || + toPath(options.configFilePath!) === referenceProjectPath || + !contains(referencedProject.commandLine.fileNames, fileName, isSameFile)) { return undefined; } - if (normalized.indexOf(k) === 0) { - result = changeExtension(fileName.replace(k, v), ".d.ts"); - } + + return referencedProject; }); - return result; + } + + 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); + }); + } + + 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 +2329,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 +2341,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 +2351,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 +2381,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 +2428,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 +2439,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; @@ -2339,29 +2505,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 +2544,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 +2580,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 +2646,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 +2655,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 +2669,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 +2688,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 +2718,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 +2732,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 +2798,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 +2884,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 +2905,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 +2961,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) || @@ -2812,28 +2979,37 @@ namespace ts { export function parseConfigHostFromCompilerHost(host: CompilerHost): ParseConfigFileHost { return { fileExists: f => host.fileExists(f), - readDirectory: (root, extensions, includes, depth?) => host.readDirectory ? host.readDirectory(root, extensions, includes, depth) : [], + readDirectory(root, extensions, excludes, includes, depth) { + Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return host.readDirectory!(root, extensions, excludes, includes, depth); + }, readFile: f => host.readFile(f), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: () => host.getCurrentDirectory(), - onUnRecoverableConfigFileDiagnostic: () => undefined + 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 b339220c38e..b8d4d248077 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -60,81 +60,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, @@ -913,7 +920,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; @@ -937,18 +944,29 @@ 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) { + 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 + return { type, value: tokenValue }; } } @@ -965,24 +983,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) { @@ -999,29 +1017,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 { @@ -1201,7 +1215,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 @@ -1288,28 +1303,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) { @@ -1331,27 +1343,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; @@ -1500,7 +1527,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) { @@ -1576,36 +1603,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))) { @@ -1626,8 +1653,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; @@ -2016,7 +2043,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/sourcemap.ts b/src/compiler/sourcemap.ts index eff543849cd..76cf24e51dc 100644 --- a/src/compiler/sourcemap.ts +++ b/src/compiler/sourcemap.ts @@ -1,595 +1,522 @@ /* @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*(\/\/[@#] .*)?$/; + + /** + * 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. + */ + export function tryGetSourceMappingURL(text: string, lineStarts: ReadonlyArray = computeLineStarts(text)) { + for (let index = lineStarts.length - 1; index >= 0; index--) { + const line = text.substring(lineStarts[index], lineStarts[index + 1]); + 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 +541,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) { + return compareValues(left.sourceIndex, right.sourceIndex); + } + + 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 generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath) as Path; + const generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + const sourceFileAbsolutePaths = map.sources.map(source => getNormalizedAbsolutePath(source, sourceRoot)); + const sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(source => host.getCanonicalFileName(source) as Path); + const sourceToSourceIndexMap = createMapFromEntries(sourceFileCanonicalPaths.map((source, i) => [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) + : -1; + let source: string | undefined; + let sourcePosition: number | undefined; + if (isSourceMapping(mapping)) { + const sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; + const sourceFile = host.getSourceFileLike(sourceFilePath); + source = map.sources[mapping.sourceIndex]; + sourcePosition = sourceFile !== undefined + ? getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + : -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..8ee1e4571b3 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -36,23 +36,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 +300,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 +779,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 +829,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", ""); 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 14e7900b0da..973b9db618e 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -5,7 +5,7 @@ namespace ts { 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,6 +154,14 @@ 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; @@ -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) { @@ -373,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; } @@ -1043,7 +1052,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 => { diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts index 0865861414e..94d6994f8d2 100644 --- a/src/compiler/transformers/declarations/diagnostics.ts +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -434,7 +434,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 +446,7 @@ namespace ts { return { diagnosticMessage, errorNode: node, - typeName: getNameOfDeclaration((node as ExpressionWithTypeArguments).parent.parent) + typeName: getNameOfDeclaration(node.parent.parent as Declaration) }; } @@ -466,4 +466,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..66f635a31e9 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); @@ -2610,7 +2620,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 +2682,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 +2701,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 +2808,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 +3127,11 @@ namespace ts { containsYield ? createToken(SyntaxKind.AsteriskToken) : undefined, /*name*/ undefined, /*typeParameters*/ undefined, - loopParameters, + currentState.loopParameters, /*type*/ undefined, - loopBody + loopBody ), - loopBodyFlags + emitFlags ) ) ] @@ -2765,106 +3140,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 +3150,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 +3180,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 +3189,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 +3200,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 +3238,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 +3287,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 +3729,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 +3739,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 +3802,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 +4376,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..700c0c8af25 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. @@ -1899,6 +1901,9 @@ namespace ts { case SyntaxKind.NumericLiteral: return createIdentifier("Number"); + case SyntaxKind.BigIntLiteral: + return getGlobalBigIntNameWithFallback(); + case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: return createIdentifier("Boolean"); @@ -1910,6 +1915,9 @@ namespace ts { case SyntaxKind.NumberKeyword: return createIdentifier("Number"); + case SyntaxKind.BigIntKeyword: + return getGlobalBigIntNameWithFallback(); + case SyntaxKind.SymbolKeyword: return languageVersion < ScriptTarget.ES2015 ? getGlobalSymbolNameWithFallback() @@ -1920,7 +1928,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 +1944,7 @@ namespace ts { case SyntaxKind.ImportType: break; + default: return Debug.failBadSyntaxKind(node); } @@ -1940,11 +1952,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 +2002,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 +2021,9 @@ namespace ts { case TypeReferenceSerializationKind.VoidNullableOrNeverType: return createVoidZero(); + case TypeReferenceSerializationKind.BigIntLikeType: + return getGlobalBigIntNameWithFallback(); + case TypeReferenceSerializationKind.BooleanType: return createIdentifier("Boolean"); @@ -2113,6 +2133,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 3692e9ca057..4b9e75102b6 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -11,52 +11,27 @@ 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; } enum BuildResultFlags { @@ -76,8 +51,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 +70,7 @@ namespace ts { OutOfDateWithUpstream, UpstreamOutOfDate, UpstreamBlocked, + ComputingUpstream, /** * Projects with no outputs (i.e. "solution" files) @@ -109,6 +86,7 @@ namespace ts { | Status.OutOfDateWithUpstream | Status.UpstreamOutOfDate | Status.UpstreamBlocked + | Status.ComputingUpstream | Status.ContainerOnly; export namespace Status { @@ -178,6 +156,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 +174,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 +272,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 +288,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 +311,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,70 +319,7 @@ 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 CompilerHost { getModifiedTime(fileName: string): Date | undefined; setModifiedTime(fileName: string, date: Date): void; deleteFile(fileName: string): void; @@ -461,7 +328,30 @@ namespace ts { reportSolutionBuilderStatus: DiagnosticReporter; } - 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 +365,8 @@ namespace ts { }; } - export function createSolutionBuilderHost(system = sys, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter) { - const host = createCompilerHostWorker({}, /*setParentNodes*/ undefined, system) as SolutionBuilderHost; + function createSolutionBuilderHostBase(system = sys, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter) { + const host = createCompilerHostWorker({}, /*setParentNodes*/ undefined, system) 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,8 +375,14 @@ namespace ts { return host; } - export function createSolutionBuilderWithWatchHost(system = sys, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter) { - const host = createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderWithWatchHost; + export function createSolutionBuilderHost(system = sys, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportErrorSummary?: ReportEmitErrorSummary) { + const host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderHost; + host.reportErrorSummary = reportErrorSummary; + return host; + } + + export function createSolutionBuilderWithWatchHost(system?: System, reportDiagnostic?: DiagnosticReporter, reportSolutionBuilderStatus?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter) { + const host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) as SolutionBuilderWithWatchHost; const watchHost = createWatchHost(system, reportWatchStatus); host.onWatchStatusChange = watchHost.onWatchStatusChange; host.watchFile = watchHost.watchFile; @@ -496,23 +392,57 @@ namespace ts { 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) { + 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 configFileCache = createConfigFileCache(host); - let context = createBuildContext(defaultOptions); + const currentDirectory = host.getCurrentDirectory(); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + const parseConfigFileHost = parseConfigHostFromCompilerHost(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); + + // Watch state + 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 existingWatchersForWildcards = createMap(); + // Watches for the solution + const allWatchedWildcardDirectories = createFileMap>(toPath); + const allWatchedInputFiles = createFileMap>(toPath); + const allWatchedConfigFiles = createFileMap(toPath); + return { buildAllProjects, - getUpToDateStatus, getUpToDateStatusOfFile, cleanAllProjects, resetBuildContext, @@ -526,87 +456,176 @@ 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); + } + + 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, hostWithWatch.watchFile(resolved, () => { + invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.Full); + })); + } + } + + function watchWildCardDirectories(resolved: ResolvedConfigFileName, parsed: ParsedCommandLine) { + if (!options.watch) return; + updateWatchingWildcardDirectories( + getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), + createMapFromTemplate(parsed.configFileSpecs!.wildcardDirectories), + (dir, flags) => { + return hostWithWatch.watchDirectory(dir, fileOrDirectory => { + const fileOrDirectoryPath = toPath(fileOrDirectory); + if (fileOrDirectoryPath !== toPath(dir) && hasExtension(fileOrDirectoryPath) && !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, ConfigFileProgramReloadLevel.Partial); + }, !!(flags & WatchDirectoryFlags.Recursive)); + } + ); + } + + function watchInputFiles(resolved: ResolvedConfigFileName, parsed: ParsedCommandLine) { + if (!options.watch) return; + mutateMap( + getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), + arrayToMap(parsed.fileNames, toPath), + { + createNewValue: (_key, input) => hostWithWatch.watchFile(input, () => { + invalidateProjectAndScheduleBuilds(resolved, ConfigFileProgramReloadLevel.None); + }), + 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 +633,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 +710,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 +725,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 +811,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,133 +872,153 @@ 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; + } + + const buildResult = buildSingleProject(resolved); + const dependencyGraph = getGlobalDependencyGraph(); + const referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (!referencingProjects) return; + // Always use build order to queue projects + for (const project of dependencyGraph.buildQueue) { + const 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); + } + } + } + + 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; } @@ -956,7 +1028,7 @@ namespace ts { host, rootNames: configFile.fileNames, options: configFile.options, - configFileParsingDiagnostics: configFile.errors, + configFileParsingDiagnostics: configFile.errors }; const program = createProgram(programOptions); @@ -966,53 +1038,36 @@ namespace ts { ...program.getConfigFileParsingDiagnostics(), ...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; + return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } // 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(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); } } // 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"); } let newestDeclarationFileContentChangedTime = minimumDate; let anyDtsChanged = false; - program.emit(/*targetSourceFile*/ undefined, (fileName, content, writeBom, onError) => { + let emitDiagnostics: Diagnostic[] | undefined; + const reportEmitDiagnostic = (d: Diagnostic) => (emitDiagnostics || (emitDiagnostics = [])).push(d); + emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, (fileName, content, writeBom, onError) => { let priorChangeTime: Date | undefined; - - if (!anyDtsChanged && isDeclarationFile(fileName) && host.fileExists(fileName)) { - if (host.readFile(fileName) === content) { - // Check for unchanged .d.ts files - resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; + 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; } } @@ -1020,24 +1075,36 @@ namespace ts { host.writeFile(fileName, content, writeBom, onError, 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"); + } + const status: UpToDateStatus = { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime }; - context.projectStatus.setValue(proj, status); + diagnostics.removeKey(proj); + projectStatus.setValue(proj, status); return resultFlags; + + function buildErrors(diagnostics: ReadonlyArray, errorFlags: BuildResultFlags, errorType: string) { + resultFlags |= errorFlags; + reportAndStoreErrors(proj, diagnostics); + projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: `${errorType} errors` }); + return resultFlags; + } } 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) { + if (options.verbose) { reportStatus(Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath!); } @@ -1052,22 +1119,18 @@ namespace ts { host.setModifiedTime(file, now); } - context.projectStatus.setValue(proj.options.configFilePath!, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime } as UpToDateStatus); + 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 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 +1143,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,46 +1157,23 @@ 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); } 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; } @@ -1163,8 +1184,8 @@ namespace ts { verboseReportProjectStatus(next, status); const projName = proj.options.configFilePath!; - if (status.type === UpToDateStatusType.UpToDate && !context.options.force) { - reportErrors(errors); + 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 @@ -1173,21 +1194,21 @@ namespace ts { continue; } - if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !context.options.force) { - reportErrors(errors); + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes && !options.force) { + reportAndStoreErrors(next, errors); // Fake build updateOutputTimestamps(proj); continue; } if (status.type === UpToDateStatusType.UpstreamBlocked) { - reportErrors(errors); - 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) { - reportErrors(errors); + reportAndStoreErrors(next, errors); // Do nothing continue; } @@ -1199,21 +1220,27 @@ namespace ts { return anyFailed ? ExitStatus.DiagnosticsPresent_OutputsSkipped : ExitStatus.Success; } - function reportErrors(errors: Diagnostic[]) { - errors.forEach((err) => host.reportDiagnostic(err)); + 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 { @@ -1224,13 +1251,21 @@ namespace ts { * 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 { @@ -1284,6 +1319,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 2d3cbcf54fe..c41f47f3c4a 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -25,7 +25,7 @@ "checker.ts", "factory.ts", "visitor.ts", - "sourcemapDecoder.ts", + "sourcemap.ts", "transformers/utilities.ts", "transformers/destructuring.ts", "transformers/ts.ts", @@ -42,8 +42,6 @@ "transformers/declarations/diagnostics.ts", "transformers/declarations.ts", "transformer.ts", - "sourcemap.ts", - "comments.ts", "emitter.ts", "watchUtilities.ts", "program.ts", @@ -52,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 a0d07e00591..b4c405c3174 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; @@ -1697,6 +1781,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 +1795,7 @@ namespace ts { export interface ExpressionWithTypeArguments extends NodeWithTypeArguments { kind: SyntaxKind.ExpressionWithTypeArguments; - parent: HeritageClause; + parent: HeritageClause | JSDocAugmentsTag; expression: LeftHandSideExpression; } @@ -2333,7 +2420,6 @@ namespace ts { export interface JSDocTag extends Node { parent: JSDoc | JSDocTypeLiteral; - atToken: AtToken; tagName: Identifier; comment?: string; } @@ -2367,7 +2453,7 @@ namespace ts { export interface JSDocTemplateTag extends JSDocTag { kind: SyntaxKind.JSDocTemplateTag; - constraint: TypeNode | undefined; + constraint: JSDocTypeExpression | undefined; typeParameters: NodeArray; } @@ -2551,7 +2637,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 +2690,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 +2720,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 +2799,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 +2808,7 @@ namespace ts { fileExists(path: string): boolean; readFile(path: string): string | undefined; + trace?(s: string): void; } /** @@ -2796,7 +2896,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 +2915,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 +2929,7 @@ namespace ts { export interface ResolvedProjectReference { commandLine: ParsedCommandLine; sourceFile: SourceFile; + references?: ReadonlyArray; } /* @internal */ @@ -2857,16 +2963,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 +2988,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; } @@ -2979,7 +3079,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; @@ -3011,8 +3111,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 +3132,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 +3141,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 +3174,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 +3262,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 +3335,9 @@ namespace ts { // Prefer aliases which are not directly visible UseAliasDefinedOutsideCurrentScope = 0x00000008, + + // Skip building an accessible symbol chain + /* @internal */ DoNotIncludeSymbolChain = 0x00000010, } /* @internal */ @@ -3356,6 +3464,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. @@ -3388,7 +3497,7 @@ namespace ts { 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 +3514,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 { @@ -3520,6 +3630,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 +3653,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 */ @@ -3578,6 +3692,7 @@ namespace ts { export interface ReverseMappedSymbol extends TransientSymbol { propertyType: Type; mappedType: MappedType; + constraintType: IndexType; } export const enum InternalSymbolName { @@ -3653,22 +3768,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 +3800,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 +3811,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 +3843,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 +3874,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,6 +3907,7 @@ 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 /* @internal */ @@ -3802,12 +3920,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 +3951,10 @@ namespace ts { value: number; } + export interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } + // Enum types (TypeFlags.Enum) export interface EnumType extends Type { } @@ -3843,6 +3975,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 +4071,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 +4098,7 @@ namespace ts { templateType?: Type; modifiersType?: Type; resolvedApparentType?: Type; + instantiating?: boolean; } export interface EvolvingArrayType extends ObjectType { @@ -3973,6 +4110,7 @@ namespace ts { export interface ReverseMappedType extends ObjectType { source: Type; mappedType: MappedType; + constraintType: IndexType; } /* @internal */ @@ -4097,6 +4235,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, @@ -4233,6 +4378,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 +4556,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 +4572,7 @@ namespace ts { /*@internal*/ version?: boolean; /*@internal*/ watch?: boolean; esModuleInterop?: boolean; + /* @internal */ showConfig?: boolean; [option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined; } @@ -4516,7 +4672,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 +4687,6 @@ namespace ts { export interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; /* @internal */ spec: ConfigFileSpecs; } @@ -4559,6 +4713,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 +4971,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 { @@ -4845,13 +5004,13 @@ 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; @@ -4878,25 +5037,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 +5075,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 +5108,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 +5215,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 +5224,6 @@ namespace ts { useCaseSensitiveFileNames(): boolean; getCurrentDirectory(): string; - /* @internal */ isSourceFileFromExternalLibrary(file: SourceFile): boolean; getLibFileFromReference(ref: FileReference): SourceFile | undefined; @@ -5231,8 +5385,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 +5466,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(path: Path): 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 +5581,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 +5635,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 +5702,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 +5818,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 +5835,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 { @@ -5618,4 +5851,10 @@ namespace ts { readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; readonly allowTextChangesInNewFiles?: 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 1efbd278aed..6b1778aab30 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -7,7 +7,7 @@ namespace ts { return pathIsRelative(moduleName) || isRootedDiskPath(moduleName); } - export function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): T[] { + export function sortAndDeduplicateDiagnostics(diagnostics: ReadonlyArray): SortedReadonlyArray { return sortAndDeduplicate(diagnostics, compareDiagnostics); } } @@ -64,7 +64,6 @@ namespace ts { getText: () => str, write: writeText, rawWrite: writeText, - writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -73,7 +72,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, @@ -101,22 +102,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))); } /** @@ -241,14 +228,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 && @@ -532,14 +525,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. @@ -562,6 +558,7 @@ namespace ts { case SyntaxKind.TemplateTail: return "}" + escapeText(node.text, CharacterCodes.backtick) + "`"; case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.RegularExpressionLiteral: return node.text; } @@ -773,12 +770,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! @@ -983,9 +981,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; @@ -1605,6 +1605,7 @@ namespace ts { } // falls through case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.ThisKeyword: return isInExpressionContext(node); @@ -1682,7 +1683,7 @@ namespace ts { return isInJSFile(file); } - export function isSourceFileNotJavascript(file: SourceFile): boolean { + export function isSourceFileNotJS(file: SourceFile): boolean { return !isInJSFile(file); } @@ -1777,7 +1778,7 @@ namespace ts { } 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 */ @@ -1796,16 +1797,26 @@ namespace ts { 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 getExpandoInitializer). * We treat the right hand side of assignments with container-like initalizers as declarations. */ - export function getAssignedExpandoInitializer(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 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; + } + } } /** @@ -1912,12 +1923,35 @@ namespace ts { /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property /// assignments we treat as special in the binder - export function getAssignmentDeclarationKind(expr: BinaryExpression): AssignmentDeclarationKind { + export function getAssignmentDeclarationKind(expr: BinaryExpression | CallExpression): AssignmentDeclarationKind { const special = getAssignmentDeclarationKindWorker(expr); return special === AssignmentDeclarationKind.Property || isInJSFile(expr) ? special : AssignmentDeclarationKind.None; } - function getAssignmentDeclarationKindWorker(expr: BinaryExpression): AssignmentDeclarationKind { + 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 AssignmentDeclarationKind.None; @@ -1934,7 +1968,7 @@ namespace ts { if (lhs.expression.kind === SyntaxKind.ThisKeyword) { return AssignmentDeclarationKind.ThisProperty; } - else if (isIdentifier(lhs.expression) && lhs.expression.escapedText === "module" && lhs.name.escapedText === "exports") { + else if (isModuleExportsPropertyAccessExpression(lhs)) { // module.exports = expr return AssignmentDeclarationKind.ModuleExports; } @@ -1999,7 +2033,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; @@ -2057,10 +2091,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 { @@ -2463,6 +2496,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 || @@ -2471,7 +2505,7 @@ namespace ts { node.kind === SyntaxKind.ImportSpecifier || node.kind === SyntaxKind.ExportSpecifier || node.kind === SyntaxKind.ExportAssignment && exportAssignmentIsAlias(node) || - isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports; + isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.ModuleExports && exportAssignmentIsAlias(node); } export function exportAssignmentIsAlias(node: ExportAssignment | BinaryExpression): boolean { @@ -2558,6 +2592,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 @@ -2873,6 +2911,7 @@ namespace ts { case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.ArrayLiteralExpression: case SyntaxKind.ObjectLiteralExpression: @@ -2894,7 +2933,6 @@ namespace ts { } } - /* @internal */ export function getBinaryOperatorPrecedence(kind: SyntaxKind): number { switch (kind) { case SyntaxKind.BarBarToken: @@ -3011,7 +3049,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; } @@ -3072,7 +3110,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 { @@ -3163,18 +3201,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++; }, @@ -3197,7 +3228,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(); + } }; } @@ -3252,7 +3355,7 @@ namespace ts { } export interface EmitFileNames { - jsFilePath: string; + jsFilePath: string | undefined; sourceMapFilePath: string | undefined; declarationFilePath: string | undefined; declarationMapPath: string | undefined; @@ -3273,7 +3376,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)); @@ -3477,13 +3580,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; } @@ -3497,7 +3600,7 @@ namespace ts { } if (emitInterveningSeparator && trailingSeparator) { - writer.write(" "); + writer.writeSpace(" "); } } } @@ -3631,7 +3734,7 @@ namespace ts { } else { // Single line comment of style //.... - writer.write(text.substring(commentPos, commentEnd)); + writer.writeComment(text.substring(commentPos, commentEnd)); } } @@ -3640,14 +3743,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); } } @@ -3742,11 +3845,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; @@ -3773,15 +3885,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); } @@ -3818,8 +3921,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 @@ -4329,7 +4432,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(); @@ -4463,6 +4566,31 @@ 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; + } } namespace ts { @@ -4984,14 +5112,19 @@ namespace ts { } break; } + case SyntaxKind.CallExpression: case SyntaxKind.BinaryExpression: { - const expr = declaration as BinaryExpression; + const expr = declaration as BinaryExpression | CallExpression; switch (getAssignmentDeclarationKind(expr)) { case AssignmentDeclarationKind.ExportsProperty: case AssignmentDeclarationKind.ThisProperty: case AssignmentDeclarationKind.Property: case AssignmentDeclarationKind.PrototypeProperty: - return (expr.left as PropertyAccessExpression).name; + 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; } @@ -5202,7 +5335,7 @@ 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; @@ -5235,6 +5368,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; } @@ -5999,6 +6136,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); } @@ -6173,30 +6314,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* @@ -6360,6 +6477,7 @@ namespace ts { case SyntaxKind.Identifier: case SyntaxKind.RegularExpressionLiteral: case SyntaxKind.NumericLiteral: + case SyntaxKind.BigIntLiteral: case SyntaxKind.StringLiteral: case SyntaxKind.NoSubstitutionTemplateLiteral: case SyntaxKind.TemplateExpression: @@ -6723,7 +6841,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; } @@ -6802,7 +6920,6 @@ namespace ts { /* @internal */ namespace ts { - /** @internal */ export function isNamedImportsOrExports(node: Node): node is NamedImportsOrExports { return node.kind === SyntaxKind.NamedImports || node.kind === SyntaxKind.NamedExports; } @@ -6866,9 +6983,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; @@ -6877,7 +6993,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); @@ -6906,7 +7021,6 @@ namespace ts { }; } - /* @internal */ export function formatMessage(_dummy: any, message: DiagnosticMessage): string { let text = getLocaleSpecificMessage(message); @@ -6917,7 +7031,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); @@ -6938,7 +7051,6 @@ namespace ts { }; } - /* @internal */ export function createCompilerDiagnosticFromMessageChain(chain: DiagnosticMessageChain): Diagnostic { return { file: undefined, @@ -6951,8 +7063,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); @@ -6983,14 +7094,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) || @@ -7085,28 +7194,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 { @@ -7329,7 +7437,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 @@ -7746,7 +7853,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; } @@ -8010,48 +8117,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; } @@ -8181,12 +8300,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; } /** @@ -8374,4 +8493,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..7a5c12cae4e 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, @@ -101,15 +100,31 @@ namespace ts { getGlobalDiagnostics(): ReadonlyArray; getSemanticDiagnostics(): ReadonlyArray; getConfigFileParsingDiagnostics(): ReadonlyArray; - emit(): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult; } 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}`; + } + /** * 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) { @@ -227,16 +242,16 @@ namespace ts { 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 => onWatchStatusChange!( + createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), + newLine, + compilerOptions + ) + ); } } @@ -263,10 +278,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 +290,7 @@ 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 */ @@ -337,9 +353,9 @@ 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 */ @@ -360,6 +376,9 @@ namespace ts { /** Compiler options */ options: CompilerOptions; + + /** Project References */ + projectReferences?: ReadonlyArray; } /** @@ -413,11 +432,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); @@ -463,9 +482,10 @@ namespace ts { 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); @@ -479,7 +499,8 @@ namespace ts { fileExists: path => host.fileExists(path), readFile, getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, + trace: host.trace ? s => host.trace!(s) : undefined }; // From tsc we want to get already parsed result and hence check for rootFileNames @@ -542,7 +563,8 @@ namespace ts { }, maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, getCurrentProgram, - writeLog + writeLog, + readDirectory: (path, extensions, exclude, include, depth?) => directoryStructureHost.readDirectory!(path, extensions, exclude, include, depth), }; // Cache for the module resolution const resolutionCache = createResolutionCache(compilerHost, configFileName ? @@ -552,11 +574,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 +611,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; } } @@ -620,7 +642,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 @@ -758,8 +780,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 +795,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 +848,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 +880,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 +893,7 @@ namespace ts { if (eventKind === FileWatcherEventKind.Deleted && sourceFilesCache.get(path)) { resolutionCache.invalidateResolutionOfFile(path); } + resolutionCache.removeResolutionsFromProjectReferenceRedirects(path); nextSourceFileVersion(path); // Update the program @@ -931,6 +953,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)) { diff --git a/src/harness/client.ts b/src/harness/client.ts index d873cd9b4fe..2035802ca67 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 */ @@ -390,34 +393,41 @@ 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, - fileToRename: body.info.fileToRename, - 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.lastRenameEntry.inputs.fileName !== fileName || + this.lastRenameEntry.inputs.position !== position || + this.lastRenameEntry.inputs.findInStrings !== findInStrings || + this.lastRenameEntry.inputs.findInComments !== findInComments) { this.getRenameInfo(fileName, position, findInStrings, findInComments); } @@ -684,6 +694,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..532a2d65578 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; diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 1abb7d4c1cc..ad8cb429a91 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -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); @@ -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,7 @@ namespace FourSlash { public verifyNoErrors() { ts.forEachKey(this.inputFiles, fileName => { if (!ts.isAnySupportedFileExtension(fileName) - || !this.getProgram().getCompilerOptions().allowJs && !ts.extensionIsTypeScript(ts.extensionFromPath(fileName))) return; + || !this.getProgram().getCompilerOptions().allowJs && !ts.extensionIsTS(ts.extensionFromPath(fileName))) return; const errors = this.getDiagnostics(fileName).filter(e => e.category !== ts.DiagnosticCategory.Suggestion); if (errors.length) { this.printErrorLog(/*expectErrors*/ false, errors); @@ -635,7 +613,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 +626,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 +646,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 +729,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 +752,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 +779,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 +797,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 +812,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 +833,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,117 +853,6 @@ 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; /** Use `getChecker` instead of accessing this directly. */ @@ -1180,12 +965,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 +982,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 +1099,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 +1137,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 +1146,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,7 +1168,7 @@ Actual: ${stringify(fullActual)}`); } } - public verifyRenameLocations(startRanges: ArrayOrSingle, options: ReadonlyArray | { findInStrings?: boolean, findInComments?: boolean, ranges: ReadonlyArray }) { + public verifyRenameLocations(startRanges: ArrayOrSingle, options: FourSlashInterface.RenameLocationsOptions) { const { findInStrings = false, findInComments = false, ranges = this.getRanges() } = ts.isArray(options) ? { findInStrings: false, findInComments: false, ranges: options } : options; for (const startRange of toArray(startRanges)) { @@ -1406,7 +1185,10 @@ Actual: ${stringify(fullActual)}`); 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 }; + }))); } } @@ -1528,7 +1310,7 @@ Actual: ${stringify(fullActual)}`); public verifyRenameInfoSucceeded(displayName: string | undefined, fullDisplayName: string | undefined, kind: string | undefined, kindModifiers: string | undefined, fileToRename: string | undefined, expectedRange: Range | undefined): void { const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (!renameInfo.canRename) { - this.raiseError("Rename did not succeed"); + throw this.raiseError("Rename did not succeed"); } this.validate("displayName", displayName, renameInfo.displayName); @@ -1554,9 +1336,8 @@ Actual: ${stringify(fullActual)}`); public verifyRenameInfoFailed(message?: string) { const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (renameInfo.canRename) { - this.raiseError("Rename was expected to fail"); + throw this.raiseError("Rename was expected to fail"); } - this.validate("error", message, renameInfo.localizedErrorMessage); } @@ -2043,6 +1824,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); @@ -2107,7 +1897,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"); } @@ -2438,7 +2228,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) { @@ -2449,12 +2252,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))); } @@ -2496,29 +2299,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) { @@ -2609,7 +2390,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, @@ -2625,22 +2406,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); @@ -3018,11 +2783,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)) { @@ -3213,74 +2973,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; @@ -3330,16 +3022,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) { @@ -3383,6 +3065,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 { @@ -3436,7 +3135,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}`); } @@ -3446,19 +3145,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; @@ -3851,7 +3551,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 { @@ -3958,6 +3658,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) { } @@ -4025,24 +3734,6 @@ 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", - ]; constructor(protected state: FourSlash.TestState, private negative = false) { if (!negative) { @@ -4050,58 +3741,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); } @@ -4174,10 +3817,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); } @@ -4188,10 +3827,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); @@ -4202,7 +3837,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); } @@ -4441,10 +4076,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. */ @@ -4467,7 +4098,7 @@ namespace FourSlashInterface { this.state.verifyRenameInfoFailed(message); } - 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); } @@ -4506,6 +4137,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 { @@ -4656,7 +4300,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 }; } } @@ -4776,6 +4420,509 @@ 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"), + 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", + ].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", + ].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; @@ -4791,29 +4938,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; } @@ -4894,14 +5041,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 { @@ -4929,4 +5076,11 @@ 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; + }; + 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..fc275529258 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -490,7 +490,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 +1159,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 +1325,9 @@ namespace Harness { const [, content] = value; outputLines += content; } + if (pretty) { + outputLines += ts.getErrorSummaryText(ts.getErrorCountForSummary(diagnostics), IO.newLine()); + } return outputLines; } @@ -1643,6 +1646,7 @@ namespace Harness { else { sourceMapCode = ""; result.maps.forEach(sourceMap => { + if (sourceMapCode) sourceMapCode += "\r\n"; sourceMapCode += fileOutput(sourceMap, harnessSettings); }); } @@ -1668,6 +1672,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 abb03babc8d..ccad290aed7 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,7 +282,7 @@ 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 @@ -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..92c3e2d4a94 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(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/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index 57fa33a84c2..9b030e212f1 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; 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 f21ee7fb6bb..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 = /[:*?"<>|]/; diff --git a/src/jsTyping/jsTyping.ts b/src/jsTyping/jsTyping.ts index 3b1868aea84..379ca6491a6 100644 --- a/src/jsTyping/jsTyping.ts +++ b/src/jsTyping/jsTyping.ts @@ -24,13 +24,11 @@ namespace ts.JsTyping { version: Version; } - /* @internal */ export function isTypingUpToDate(cachedTyping: CachedTyping, availableTypingVersions: MapLike) { 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/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/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..c8e99f0d1db 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -295,6 +295,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; @@ -1350,7 +1410,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..ec3ab3244b0 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 @@ - + @@ -3766,7 +3766,7 @@ - + @@ -3775,7 +3775,7 @@ - + @@ -3784,7 +3784,7 @@ - + @@ -3793,7 +3793,7 @@ - + @@ -3802,7 +3802,7 @@ - + @@ -5437,7 +5437,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/server/editorServices.ts b/src/server/editorServices.ts index b1f88dff3b7..23baa9119bf 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; @@ -291,7 +340,8 @@ namespace ts.server { 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" + TypeRoots = "Type root directory", + NodeModulesForClosedScriptInfo = "node_modules for closed script infos in them", } const enum ConfigFileWatcherStatus { @@ -353,10 +403,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(); @@ -380,6 +438,7 @@ namespace ts.server { * Container of all known scripts */ private 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 @@ -438,7 +497,7 @@ namespace ts.server { private readonly hostConfiguration: HostConfiguration; private safelist: SafeList = defaultTypeSafeList; - private legacySafelist: { [key: string]: string } = {}; + private readonly legacySafelist = createMap(); private pendingProjectUpdates = createMap(); /* @internal */ @@ -461,6 +520,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 +574,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 +651,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 +754,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 +846,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 +878,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,15 +931,20 @@ 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.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(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); + } } } @@ -882,6 +975,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 @@ -927,6 +1021,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 +1048,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()); @@ -1393,19 +1489,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 +1533,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 +1550,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 +1611,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, @@ -1585,22 +1671,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 +1696,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 +1735,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 +1747,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 +1828,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 +1837,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 +1847,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); @@ -1847,7 +1937,7 @@ 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 project = new InferredProject(this, this.documentRegistry, compilerOptions, projectRootPath, currentDirectory, this.currentPluginConfigOverrides); if (isSingleInferredProject) { this.inferredProjects.unshift(project); } @@ -1878,6 +1968,12 @@ namespace ts.server { 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 +2019,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 +2120,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 +2150,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 +2163,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); } @@ -2031,7 +2221,6 @@ namespace ts.server { if (project.hasExternalProjectRef() && project.pendingReload === ConfigFileProgramReloadLevel.Full && !this.pendingProjectUpdates.has(project.getProjectName())) { - this.loadConfiguredProject(project); project.updateGraph(); } }); @@ -2063,7 +2252,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 +2263,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 +2276,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 +2297,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 +2378,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 +2389,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); @@ -2248,7 +2440,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 @@ -2326,17 +2518,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); } } - } + }); } }); @@ -2560,13 +2749,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 +2878,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 +2906,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 +2924,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..45d932abc3e 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; @@ -92,7 +115,7 @@ namespace ts.server { private program: Program; private externalFiles: SortedReadonlyArray; private missingFilesMap: Map; - private plugins: PluginModule[] = []; + private plugins: PluginModuleWithName[] = []; /*@internal*/ /** @@ -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 { @@ -539,10 +571,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}`); @@ -574,14 +606,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)); @@ -653,7 +682,7 @@ namespace ts.server { return this.rootFiles; } return map(this.program.getSourceFiles(), sourceFile => { - const scriptInfo = this.projectService.getScriptInfoForPath(sourceFile.resolvedPath || sourceFile.path); + 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!; }); @@ -783,41 +812,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 +845,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 +862,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) ); @@ -916,12 +902,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 +933,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 +948,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); + } } } @@ -1017,6 +1012,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 +1098,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 +1121,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 +1137,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 +1152,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 +1177,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 +1245,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 +1272,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 +1289,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) { @@ -1311,10 +1352,15 @@ namespace ts.server { /* @internal */ pendingReload: ConfigFileProgramReloadLevel; + /* @internal */ + pendingReloadReason: string | undefined; /*@internal*/ configFileSpecs: ConfigFileSpecs | undefined; + /*@internal*/ + canConfigFileJsonReportNoInputFiles: boolean; + /** Ref count to the project when opened from external project */ private externalProjectRefCount = 0; @@ -1327,6 +1373,9 @@ namespace ts.server { protected isInitialLoadPending: () => boolean = returnTrue; + /*@internal*/ + sendLoadingProjectFinish = false; + /*@internal*/ constructor(configFileName: NormalizedPath, projectService: ProjectService, @@ -1359,12 +1408,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 +1431,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 +1440,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 +1467,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 +1579,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); } } diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 2804b27deaf..193621da82a 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,23 +1093,18 @@ 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; /** * File or directory to rename. * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. */ fileToRename?: string; - /** - * Error message if item can not be renamed. - */ - localizedErrorMessage?: string; - /** * Display name of the item to be renamed. */ @@ -1123,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; } /** @@ -1132,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 { @@ -1365,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. */ @@ -2380,6 +2406,7 @@ namespace ts.server.protocol { */ export interface DiagnosticEvent extends Event { body?: DiagnosticEventBody; + event: DiagnosticEventKind; } export interface ConfigFileDiagnosticEventBody { @@ -2442,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 { @@ -2475,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. */ @@ -2734,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 diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index 5c4eaa9a374..77329099871 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,6 +25,14 @@ 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 */ @@ -57,10 +64,12 @@ namespace ts.server { this.switchToScriptVersionCache(); } + /** Public for testing */ public useText(newText?: string) { this.svc = undefined; this.text = newText; this.lineMap = undefined; + this.fileSize = undefined; this.version.text++; } @@ -69,13 +78,14 @@ namespace ts.server { this.ownFileText = false; this.text = undefined; this.lineMap = undefined; + this.fileSize = undefined; } /** * 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 +102,8 @@ namespace ts.server { this.ownFileText = false; return true; } + + return false; } /** @@ -99,7 +111,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,6 +133,23 @@ 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() @@ -162,22 +193,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 { @@ -250,6 +281,9 @@ namespace ts.server { /*@internal*/ cacheSourceFile: DocumentRegistrySourceFileCache; + /*@internal*/ + mTime?: number; + constructor( private readonly host: ServerHost, readonly fileName: NormalizedPath, @@ -274,6 +308,11 @@ namespace ts.server { return this.textStorage.version; } + /*@internal*/ + getTelemetryFileSize() { + return this.textStorage.getTelemetryFileSize(); + } + /*@internal*/ public isDynamicOrHasMixedContent() { return this.hasMixedContent || this.isDynamic; @@ -435,7 +474,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 { diff --git a/src/server/scriptVersionCache.ts b/src/server/scriptVersionCache.ts index d7ac25062d0..0ffb3a195ad 100644 --- a/src/server/scriptVersionCache.ts +++ b/src/server/scriptVersionCache.ts @@ -382,7 +382,6 @@ namespace ts.server { } } - /* @internal */ export class LineIndex { root: LineNode; // set this to true to check each edit for accuracy diff --git a/src/server/session.ts b/src/server/session.ts index e6c4c33a53d..ffc9dc75506 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,77 @@ 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 ): 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) || 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 +398,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 +436,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 +467,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 +508,7 @@ namespace ts.server { globalPlugins?: ReadonlyArray; pluginProbeLocations?: ReadonlyArray; allowLocalPluginLoads?: boolean; + typesMapLocation?: string; } export class Session implements EventSender { @@ -538,6 +569,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 +586,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 +607,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 +645,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 +661,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 +706,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 +941,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 +1038,7 @@ namespace ts.server { kind: info.kind, displayParts: info.displayParts, textSpan: { - start: newLoc.position, + start: newLoc.pos, length: info.textSpan.length }, originalFileName: info.fileName, @@ -1116,7 +1194,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 +1204,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 +1226,38 @@ 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 + ); 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), 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 +1266,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 +1280,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); @@ -1416,7 +1514,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 +1539,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 +1777,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 +1811,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 +1821,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 +1831,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 +1915,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 +1957,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 +2041,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 +2366,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 +2424,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 +2453,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 +2489,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..15b217822c0 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,14 @@ 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); } } 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/convertToAsyncFunction.ts b/src/services/codefixes/convertToAsyncFunction.ts index e8e24b40a0c..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 { @@ -63,17 +58,17 @@ namespace ts.codefix { const allVarNames: SymbolAndIdentifier[] = []; 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: isInJavascript }; + 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); diff --git a/src/services/codefixes/fixAddMissingMember.ts b/src/services/codefixes/fixAddMissingMember.ts index dda0903562a..bbad3e03824 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({ @@ -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); } 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 6822cae7911..1c7070c74bf 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,141 @@ 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 = findProperty(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 = findProperty(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 = findProperty(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 createJsonPropertyAssignment(name: string, initializer: Expression) { + return createPropertyAssignment(createStringLiteral(name), initializer); + } + + function findProperty(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); + } + + 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 } = 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/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/importFixes.ts b/src/services/codefixes/importFixes.ts index 578f55f5c68..14bfc8b2761 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( @@ -289,7 +289,7 @@ namespace ts.codefix { // `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( @@ -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 f924208e321..9cf5133d982 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 (isSourceFileJS(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,9 +181,9 @@ 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); } } @@ -140,45 +194,119 @@ namespace ts.codefix { case SyntaxKind.Constructor: return true; case SyntaxKind.FunctionExpression: - return !!declaration.name; + const parent = declaration.parent; + return isVariableDeclaration(parent) && isIdentifier(parent.name) || !!declaration.name; } return false; } - function annotateParameters(changes: textChanges.ChangeTracker, parameterDeclaration: ParameterDeclaration, containingFunction: FunctionLike, sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken): void { + function annotateParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterDeclaration: ParameterDeclaration, containingFunction: FunctionLike, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { if (!isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { return; } - 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; - } + 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); - zipWith(containingFunction.parameters, types, (parameter, type) => { - if (!parameter.type && !parameter.initializer) { - annotate(changes, sourceFile, parameter, type, program); + if (isInJSFile(containingFunction)) { + annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); + } + else { + for (const { declaration, type } of parameterInferences) { + if (declaration && !declaration.type && !declaration.initializer) { + annotate(changes, sourceFile, declaration, type, program, host); + } } - }); + } } - 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 +317,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 +332,42 @@ 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: FunctionLikeDeclaration, 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.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 +379,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 +390,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: FunctionLikeDeclaration, program: Program, cancellationToken: CancellationToken): ParameterInference[] | undefined { + const checker = program.getTypeChecker(); if (references.length === 0) { return undefined; } - if (!declaration.parameters) { return undefined; } @@ -260,17 +413,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 +432,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 +671,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 +816,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 +854,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 ff8c3147824..488af58a2f0 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 }; } @@ -198,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" }; } @@ -270,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; @@ -299,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, @@ -377,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; @@ -515,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) { @@ -573,10 +396,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. @@ -616,7 +436,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) @@ -624,24 +444,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 }; } @@ -700,7 +503,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; @@ -708,7 +511,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, @@ -762,28 +565,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); @@ -1190,9 +971,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; @@ -1348,23 +1129,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 { @@ -1387,7 +1158,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 }; } @@ -1397,14 +1168,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; } @@ -1703,6 +1476,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; } } @@ -1756,6 +1532,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: @@ -1764,6 +1541,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) { @@ -1918,7 +1699,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: @@ -1933,6 +1713,8 @@ namespace ts.Completions { case SyntaxKind.VarKeyword: case SyntaxKind.YieldKeyword: return true; + case SyntaxKind.AsyncKeyword: + return isPropertyDeclaration(contextToken.parent); } return isDeclarationName(contextToken) @@ -2136,7 +1918,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); @@ -2179,25 +1961,13 @@ namespace ts.Completions { 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. @@ -2258,11 +2028,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 "@": @@ -2271,14 +2037,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); } @@ -2287,16 +2053,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..0ed29a73bb5 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,7 +34,7 @@ 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. */ @@ -59,7 +60,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 +85,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 +151,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): RenameLocation { + return { ...entryToDocumentSpan(entry), ...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 +251,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 +371,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 +407,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 +425,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 +434,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 +483,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, !!options.isForRename) || originalSymbol; // Compute the meaning from the location and the symbol it references const searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : SemanticMeaning.All; @@ -417,12 +492,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 = !options.isForRename ? 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.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 +538,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, isForRename: boolean): Symbol | undefined { const { parent } = node; - if (isExportSpecifier(parent)) { + if (isExportSpecifier(parent) && !isForRename) { 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 +656,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 +744,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 +758,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 +783,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 +815,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 +863,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 +954,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 +1062,25 @@ 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 { 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 +1092,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 +1102,15 @@ namespace ts.FindAllReferences.Core { } // For `export { foo as bar }`, rename `foo`, but not `bar`. - if (!(referenceLocation === propertyName && state.options.isForRename)) { + if (!state.options.isForRename || 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 && !state.options.isForRename) { const imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (imported) searchForImportedSymbol(imported, state); } @@ -1074,12 +1145,11 @@ namespace ts.FindAllReferences.Core { const { symbol } = importOrExport; if (importOrExport.kind === ImportExport.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); } } @@ -1099,13 +1169,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); } } @@ -1428,7 +1499,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 +1510,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, implementations: boolean): Symbol[] { const result: Symbol[] = []; - forEachRelatedSymbol(symbol, location, checker, + forEachRelatedSymbol(symbol, location, checker, isForRename, (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, + 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 +1536,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 +1572,14 @@ 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 -- just rename the local. + if (!isForRenamePopulateSearchSymbolSet) { + const bindingElementPropertySymbol = isObjectBindingElementWithoutPropertyName(location.parent) ? getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, EntryKind.SearchedPropertyFoundLocal); + } - function fromRoot(sym: Symbol): T | undefined { + 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 +1587,24 @@ 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 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, + (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)))); diff --git a/src/services/formatting/formatting.ts b/src/services/formatting/formatting.ts index c1de1574e88..a5135f11783 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, @@ -1072,7 +1106,10 @@ namespace ts.formatting { * Trimming will be done for lines after the previous range */ function trimTrailingWhitespacesForRemainingRange() { - const startPosition = previousRange ? previousRange.end : originalRange.pos; + if (!previousRange) { + return; + } + const startPosition = previousRange.end; const startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; const endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; @@ -1211,6 +1248,9 @@ namespace ts.formatting { if ((node).typeArguments === list) { return SyntaxKind.LessThanToken; } + break; + case SyntaxKind.TypeLiteral: + return SyntaxKind.OpenBraceToken; } return SyntaxKind.Unknown; @@ -1222,6 +1262,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/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..ae031da5728 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") { @@ -196,15 +197,23 @@ namespace ts { } function getSourceFileToImportFromResolved(resolved: ResolvedModuleWithFailedLookupLocations | undefined, oldToNew: PathUpdater, host: LanguageServiceHost): ToImport | undefined { - return resolved && ( - (resolved.resolvedModule && getIfExists(resolved.resolvedModule.resolvedFileName)) || firstDefined(resolved.failedLookupLocations, getIfExists)); + // 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 getIfExists(oldLocation: string): ToImport | undefined { - const newLocation = oldToNew(oldLocation); + function tryEach(cb: (oldFileName: string) => ToImport | undefined): ToImport | undefined { + return resolved && ( + (resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || firstDefined(resolved.failedLookupLocations, cb)); + } - return host.fileExists!(oldLocation) || newLocation !== undefined && host.fileExists!(newLocation) // TODO: GH#18217 - ? newLocation !== undefined ? { newFileName: newLocation, updated: true } : { newFileName: oldLocation, updated: false } - : undefined; + function tryGetNewFile(oldFileName: string): ToImport | undefined { + const newFileName = oldToNew(oldFileName); + return newFileName !== undefined && host.fileExists!(newFileName) ? { newFileName, updated: true } : undefined; // TODO: GH#18217 + } + + function tryGetOldFile(oldFileName: string): ToImport | undefined { + const newFileName = oldToNew(oldFileName); + return host.fileExists!(oldFileName) ? newFileName !== undefined ? { newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 } } 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 86bee92eaec..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)); @@ -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 641eb643f92..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 : ""); diff --git a/src/services/navigationBar.ts b/src/services/navigationBar.ts index ab7c4327bb5..760d6e71031 100644 --- a/src/services/navigationBar.ts +++ b/src/services/navigationBar.ts @@ -281,6 +281,9 @@ namespace ts.NavigationBar { 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 => isStringLiteral(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..9c504357102 100644 --- a/src/services/organizeImports.ts +++ b/src/services/organizeImports.ts @@ -146,7 +146,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 +266,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/pathCompletions.ts b/src/services/pathCompletions.ts deleted file mode 100644 index 22cc56903c0..00000000000 --- a/src/services/pathCompletions.ts +++ /dev/null @@ -1,512 +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)); - } - } - } - - // 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 } 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)); - } - } - } - } - } - - /** - * 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 = normalizePath(combinePaths(projectDir, baseUrl)); - getCompletionEntriesForDirectoryFragment(fragment, absolute, fileExtensions, /*includeExtensions*/ false, host, /*exclude*/ undefined, result); - if (paths) { - addCompletionEntriesFromPaths(result, fragment, absolute, fileExtensions, paths, host); - } - } - - 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 = unmangleScopedPackageName(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 = unmangleScopedPackageName(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 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 - * - * /// , 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 96b5ba18070..c1915a66431 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 */ @@ -677,7 +677,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: diff --git a/src/services/refactors/generateGetAccessorAndSetAccessor.ts b/src/services/refactors/generateGetAccessorAndSetAccessor.ts index 57b25445f5d..70f16e3b7b2 100644 --- a/src/services/refactors/generateGetAccessorAndSetAccessor.ts +++ b/src/services/refactors/generateGetAccessorAndSetAccessor.ts @@ -20,8 +20,8 @@ namespace ts.refactor.generateGetAccessorAndSetAccessor { 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, @@ -226,7 +226,7 @@ namespace ts.refactor.generateGetAccessorAndSetAccessor { 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); + (entry.kind !== FindAllReferences.EntryKind.Span && rangeContainsRange(constructor, entry.node) && isIdentifier(entry.node) && isWriteAccess(entry.node)) ? entry.node : undefined); forEach(referenceEntries, entry => { const parent = entry.parent; diff --git a/src/services/refactors/moveToNewFile.ts b/src/services/refactors/moveToNewFile.ts index 8b6af714892..87973226b3c 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); }; @@ -612,7 +612,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,7 +653,7 @@ 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; @@ -663,13 +663,32 @@ namespace ts.refactor { } } } + 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 649ed33786f..7ba32c91309 100644 --- a/src/services/rename.ts +++ b/src/services/rename.ts @@ -39,47 +39,43 @@ namespace ts.Rename { } 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 = node.text.endsWith("/index") || node.text.endsWith("/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, - localizedErrorMessage: undefined, fullDisplayName: name, kindModifiers: ScriptElementKindModifier.none, - triggerSpan: createTriggerSpanForNode(node, sourceFile), + triggerSpan, }; } - function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: ScriptElementKind, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfo { + 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 7f2ac2bcc81..2abfe7095ec 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -541,6 +541,7 @@ namespace ts { public fileName: string; public path: Path; public resolvedPath: Path; + public originalFileName: string; public text: string; public scriptSnapshot: IScriptSnapshot; public lineMap: ReadonlyArray; @@ -1138,7 +1139,7 @@ namespace ts { const useCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames(host); const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); - const sourceMapper = getSourceMapper(getCanonicalFileName, currentDirectory, log, host, () => program); + const sourceMapper = getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, () => program); function getValidSourceFile(fileName: string): SourceFile { const sourceFile = program.getSourceFile(fileName); @@ -1175,9 +1176,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; } @@ -1217,6 +1219,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 +1232,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 +1246,7 @@ namespace ts { options: newSettings, host: compilerHost, oldProgram: program, - projectReferences: hostCache.getProjectReferences() + projectReferences }; program = createProgram(options); @@ -1270,7 +1276,7 @@ namespace ts { // 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 +1383,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 +1481,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 +1496,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 +1506,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 +1519,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,7 +1533,7 @@ 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); } @@ -1536,22 +1542,22 @@ namespace ts { 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, isForRename: true }, FindAllReferences.toRenameLocation); } } 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 +1565,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 +1809,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); } } @@ -2142,7 +2159,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..3ee11817c49 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -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 resolveModuleNames: (moduleName: string[], containingFile: string) => (ResolvedModuleFull | undefined)[]; + public resolveTypeReferenceDirectives: (typeDirectiveNames: string[], containingFile: string) => (ResolvedTypeReferenceDirective | undefined)[]; public directoryExists: (directoryName: string) => boolean; 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)); }; } } diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index 29a2b728db2..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(); @@ -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..92ebcc8c261 100644 --- a/src/services/sourcemaps.ts +++ b/src/services/sourcemaps.ts @@ -1,69 +1,64 @@ /* @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, + useCaseSensitiveFileNames: boolean, currentDirectory: string, log: (message: string) => void, host: LanguageServiceHost, getProgram: () => Program, ): SourceMapper { + const getCanonicalFileName = createGetCanonicalFileName(useCaseSensitiveFileNames); let sourcemappedFileCache: SourceFileLikeCache; - return { tryGetOriginalLocation, tryGetGeneratedLocation, toLineColumnOffset, clearCache }; + return { tryGetSourcePosition, tryGetGeneratedPosition, toLineColumnOffset, clearCache }; + + function toPath(fileName: string) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } function scanForSourcemapURL(fileName: string) { - const mappedFile = sourcemappedFileCache.get(toPath(fileName, currentDirectory, getCanonicalFileName)); + const mappedFile = sourcemappedFileCache.get(toPath(fileName)); 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; - } - } + + return tryGetSourceMappingURL(mappedFile.text, getLineStarts(mappedFile)); } - function convertDocumentToSourceMapper(file: { sourceMapper?: sourcemaps.SourceMapper }, contents: string, mapFileName: string) { - let maps: sourcemaps.SourceMapData | undefined; - try { - maps = JSON.parse(contents); - } - catch { - // swallow error - } - if (!maps || !maps.sources || !maps.file || !maps.mappings) { + function convertDocumentToSourceMapper(file: { sourceMapper?: DocumentPositionMapper }, contents: string, mapFileName: string) { + const map = tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { // obviously invalid map - return file.sourceMapper = sourcemaps.identitySourceMapper; + return file.sourceMapper = identitySourceMapConsumer; } - return file.sourceMapper = sourcemaps.decode({ - readFile: s => host.readFile!(s), // TODO: GH#18217 - fileExists: s => host.fileExists!(s), // TODO: GH#18217 + const program = getProgram(); + return file.sourceMapper = createDocumentPositionMapper({ + getSourceFileLike: s => { + // Lookup file in program, if provided + const 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, log, - }, mapFileName, maps, getProgram(), sourcemappedFileCache); + }, map, mapFileName); } - function getSourceMapper(fileName: string, file: SourceFileLike): sourcemaps.SourceMapper { + function getSourceMapper(fileName: string, file: SourceFileLike): DocumentPositionMapper { if (!host.readFile || !host.fileExists) { - return file.sourceMapper = sourcemaps.identitySourceMapper; + return file.sourceMapper = identitySourceMapConsumer; } if (file.sourceMapper) { return file.sourceMapper; @@ -86,26 +81,30 @@ namespace ts { } possibleMapLocations.push(fileName + ".map"); for (const location of possibleMapLocations) { - const mapPath = toPath(location, getDirectoryPath(fileName), getCanonicalFileName); + const mapPath = ts.toPath(location, getDirectoryPath(fileName), getCanonicalFileName); if (host.fileExists(mapPath)) { return convertDocumentToSourceMapper(file, host.readFile(mapPath)!, mapPath); // TODO: GH#18217 } } - return file.sourceMapper = sourcemaps.identitySourceMapper; + return file.sourceMapper = identitySourceMapConsumer; } - 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); if (!file) return undefined; - const newLoc = getSourceMapper(info.fileName, file).getOriginalPosition(info); - return newLoc === info ? undefined : tryGetOriginalLocation(newLoc) || newLoc; + const newLoc = getSourceMapper(info.fileName, file).getSourcePosition(info); + return newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; } - function tryGetGeneratedLocation(info: sourcemaps.SourceMappableLocation): sourcemaps.SourceMappableLocation | undefined { + function tryGetGeneratedPosition(info: DocumentPosition): DocumentPosition | undefined { const program = getProgram(); - const declarationPath = getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); + 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; @@ -114,12 +113,16 @@ namespace ts { } function getFile(fileName: string): SourceFileLike | undefined { - return getProgram().getSourceFile(fileName) || sourcemappedFileCache.get(toPath(fileName, currentDirectory, getCanonicalFileName)); + const path = toPath(fileName); + const file = getProgram().getSourceFileByPath(path); + if (file && file.resolvedPath === path) { + return file; + } + return sourcemappedFileCache.get(path); } 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 = getFile(fileName)!; // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } @@ -127,4 +130,31 @@ namespace ts { sourcemappedFileCache = createSourceFileLikeCache(host); } } + + interface SourceFileLikeCache { + get(path: Path): SourceFileLike | undefined; + } + + 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; + } + }; + } } 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 d4aec1b1c6f..5c175146e34 100644 --- a/src/services/suggestionDiagnostics.ts +++ b/src/services/suggestionDiagnostics.ts @@ -82,7 +82,7 @@ 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); @@ -113,65 +113,70 @@ 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 { + if (!isAsyncFunction(node) && + node.body && + isBlock(node.body) && + hasReturnStatementWithPromiseHandler(node.body) && + returnsPromise(node, checker)) { + 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 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.NullKeyword: + case SyntaxKind.Identifier: // identifier includes undefined + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + return true; + default: + return false; + } } } diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index cc59aa3c0ce..e0728f98a29 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -534,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..15044416f84 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,6 +56,7 @@ "codefixes/importFixes.ts", "codefixes/fixSpelling.ts", "codefixes/fixAddMissingMember.ts", + "codefixes/fixAddMissingNewOperator.ts", "codefixes/fixCannotFindModule.ts", "codefixes/fixClassDoesntImplementInheritedAbstractMember.ts", "codefixes/fixClassSuperMustPrecedeThisAccess.ts", @@ -66,9 +70,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 +86,6 @@ "services.ts", "breakpoints.ts", "transform.ts", - "shims.ts" + "shims.ts", ] } diff --git a/src/services/types.ts b/src/services/types.ts index 08a09d7f912..0d14ad2b978 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -86,12 +86,12 @@ 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; + /*@internal*/ sourceMapper?: DocumentPositionMapper; } export interface SourceMapSource { @@ -212,9 +212,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 +231,15 @@ namespace ts { isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; + /* @internal */ inspectValue?(options: InspectValueOptions): Promise; + writeFile?(fileName: string, content: string): void; } /* @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 +270,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, @@ -287,19 +291,19 @@ 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; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: 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 +335,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 */ @@ -526,12 +530,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 +621,8 @@ namespace ts { } export interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } export interface ReferenceEntry extends DocumentSpan { @@ -698,25 +714,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,20 +825,24 @@ namespace ts { tags?: JSDocTagInfo[]; } - export interface RenameInfo { - canRename: boolean; + 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; - localizedErrorMessage?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + export interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } export interface SignatureHelpParameter { name: string; @@ -933,6 +980,7 @@ namespace ts { Whitespace, Identifier, NumberLiteral, + BigIntLiteral, StringLiteral, RegExpLiteral, } @@ -1081,7 +1129,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 { @@ -1089,6 +1144,7 @@ namespace ts { identifier = "identifier", keyword = "keyword", numericLiteral = "number", + bigintLiteral = "bigint", operator = "operator", stringLiteral = "string", whiteSpace = "whitespace", @@ -1137,5 +1193,6 @@ namespace ts { jsxAttribute = 22, jsxText = 23, jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25, } } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 40a9936b605..22e6b31b55c 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: @@ -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; } @@ -358,6 +372,9 @@ namespace ts { const kind = getAssignmentDeclarationKind(node as BinaryExpression); const { right } = node as BinaryExpression; switch (kind) { + case AssignmentDeclarationKind.ObjectDefinePropertyValue: + case AssignmentDeclarationKind.ObjectDefinePropertyExports: + case AssignmentDeclarationKind.ObjectDefinePrototypeProperty: case AssignmentDeclarationKind.None: return ScriptElementKind.unknown; case AssignmentDeclarationKind.ExportsProperty: @@ -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, @@ -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/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/projectsRunner.ts b/src/testRunner/projectsRunner.ts index 3dcf1911dde..457201c1387 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 { @@ -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 42edf839964..32772ed311b 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -65,6 +65,7 @@ "unittests/matchFiles.ts", "unittests/moduleResolution.ts", "unittests/organizeImports.ts", + "unittests/parsePseudoBigInt.ts", "unittests/paths.ts", "unittests/printer.ts", "unittests/programMissingFiles.ts", @@ -75,6 +76,7 @@ "unittests/reuseProgramStructure.ts", "unittests/session.ts", "unittests/semver.ts", + "unittests/showConfig.ts", "unittests/symbolWalker.ts", "unittests/telemetry.ts", "unittests/textChanges.ts", diff --git a/src/testRunner/unittests/commandLineParsing.ts b/src/testRunner/unittests/commandLineParsing.ts index 7ac9504f1f8..7e2090eb3bd 100644 --- a/src/testRunner/unittests/commandLineParsing.ts +++ b/src/testRunner/unittests/commandLineParsing.ts @@ -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, diff --git a/src/testRunner/unittests/compileOnSave.ts b/src/testRunner/unittests/compileOnSave.ts index 49d1659deec..4b98d71ef0a 100644 --- a/src/testRunner/unittests/compileOnSave.ts +++ b/src/testRunner/unittests/compileOnSave.ts @@ -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); diff --git a/src/testRunner/unittests/configurationExtension.ts b/src/testRunner/unittests/configurationExtension.ts index 012b8e0d2fa..57c899eb5a8 100644 --- a/src/testRunner/unittests/configurationExtension.ts +++ b/src/testRunner/unittests/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": "", @@ -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/convertCompilerOptionsFromJson.ts index 3b422e9a645..7b8af54f930 100644 --- a/src/testRunner/unittests/convertCompilerOptionsFromJson.ts +++ b/src/testRunner/unittests/convertCompilerOptionsFromJson.ts @@ -1,33 +1,50 @@ namespace ts { describe("convertCompilerOptionsFromJson", () => { - function assertCompilerOptions(json: any, configFileName: string, expectedResult: { compilerOptions: CompilerOptions, errors: Diagnostic[] }) { + 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/convertToAsyncFunction.ts b/src/testRunner/unittests/convertToAsyncFunction.ts index 99788e1310e..21c6a29f8e4 100644 --- a/src/testRunner/unittests/convertToAsyncFunction.ts +++ b/src/testRunner/unittests/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) { + 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) { + 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,27 +343,6 @@ 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", () => { _testConvertToAsyncFunction("convertToAsyncFunction_basic", ` function [#|f|](): Promise{ @@ -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", ` @@ -1194,14 +1154,126 @@ const [#|foo|] = function () { } `); + _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)); +} +`); }); 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 +} diff --git a/src/testRunner/unittests/customTransforms.ts b/src/testRunner/unittests/customTransforms.ts index 819b5d80df5..c4ff21d0a25 100644 --- a/src/testRunner/unittests/customTransforms.ts +++ b/src/testRunner/unittests/customTransforms.ts @@ -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())) { diff --git a/src/testRunner/unittests/extractTestHelpers.ts b/src/testRunner/unittests/extractTestHelpers.ts index 6e46c1304ab..cc3ba9f372e 100644 --- a/src/testRunner/unittests/extractTestHelpers.ts +++ b/src/testRunner/unittests/extractTestHelpers.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/moduleResolution.ts b/src/testRunner/unittests/moduleResolution.ts index e12e60e49ea..05e17384978 100644 --- a/src/testRunner/unittests/moduleResolution.ts +++ b/src/testRunner/unittests/moduleResolution.ts @@ -83,7 +83,7 @@ namespace ts { describe("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); } } @@ -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", @@ -1104,14 +1112,18 @@ 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); + 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/organizeImports.ts b/src/testRunner/unittests/organizeImports.ts index b4f54afa21b..355292c6d89 100644 --- a/src/testRunner/unittests/organizeImports.ts +++ b/src/testRunner/unittests/organizeImports.ts @@ -270,7 +270,7 @@ 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); }); @@ -741,7 +741,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/parsePseudoBigInt.ts b/src/testRunner/unittests/parsePseudoBigInt.ts new file mode 100644 index 00000000000..0ffbee6345e --- /dev/null +++ b/src/testRunner/unittests/parsePseudoBigInt.ts @@ -0,0 +1,71 @@ +namespace ts { + describe("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" + ); + }); + }); + }); +} \ No newline at end of file diff --git a/src/testRunner/unittests/programMissingFiles.ts b/src/testRunner/unittests/programMissingFiles.ts index 37d4c791196..55dfa7f5cc2 100644 --- a/src/testRunner/unittests/programMissingFiles.ts +++ b/src/testRunner/unittests/programMissingFiles.ts @@ -98,4 +98,38 @@ namespace ts { ]); }); }); + + describe("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/projectReferences.ts b/src/testRunner/unittests/projectReferences.ts index 4702c0c26ce..5b99e01585d 100644 --- a/src/testRunner/unittests/projectReferences.ts +++ b/src/testRunner/unittests/projectReferences.ts @@ -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); }); }); diff --git a/src/testRunner/unittests/reuseProgramStructure.ts b/src/testRunner/unittests/reuseProgramStructure.ts index f0f9cc6493b..0ab50a65105 100644 --- a/src/testRunner/unittests/reuseProgramStructure.ts +++ b/src/testRunner/unittests/reuseProgramStructure.ts @@ -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; @@ -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,55 +833,64 @@ 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); }); }); }); @@ -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/session.ts b/src/testRunner/unittests/session.ts index b3b2cf6ce22..ac5d8093e31 100644 --- a/src/testRunner/unittests/session.ts +++ b/src/testRunner/unittests/session.ts @@ -502,7 +502,7 @@ namespace ts.server { typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, - logger: projectSystem.nullLogger, + logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler(this.customHandler, () => { @@ -570,7 +570,7 @@ namespace ts.server { typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, - logger: projectSystem.nullLogger, + logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler("echo", (req: protocol.Request) => ({ diff --git a/src/testRunner/unittests/showConfig.ts b/src/testRunner/unittests/showConfig.ts new file mode 100644 index 00000000000..a2b5bb10258 --- /dev/null +++ b/src/testRunner/unittests/showConfig.ts @@ -0,0 +1,34 @@ +namespace ts { + describe("showTSConfig", () => { + function showTSConfigCorrectly(name: string, commandLinesArgs: string[]) { + describe(name, () => { + const commandLine = parseCommandLine(commandLinesArgs); + const initResult = convertToTSConfig(commandLine, `/${name}/tsconfig.json`, { getCurrentDirectory() { return `/${name}`; }, useCaseSensitiveFileNames: true }); + const outputFileName = `showConfig/${name.replace(/[^a-z0-9\-. ]/ig, "")}/tsconfig.json`; + + it(`Correct output for ${outputFileName}`, () => { + // 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"]); + }); +} \ No newline at end of file diff --git a/src/testRunner/unittests/telemetry.ts b/src/testRunner/unittests/telemetry.ts index 1c11a40c2ee..f2a7d854124 100644 --- a/src/testRunner/unittests/telemetry.ts +++ b/src/testRunner/unittests/telemetry.ts @@ -211,15 +211,36 @@ namespace ts.projectSystem { }, "/jsconfig.json"); }); + it("sends telemetry for file sizes", () => { + const jsFile = makeFile("/a.js", "1"); + const tsFile = makeFile("/b.ts", "12"); + const tsconfig = makeFile("/jsconfig.json", { + compilerOptions: autoJsCompilerOptions + }); + const et = new TestServerEventManager([tsconfig, jsFile, tsFile]); + et.service.openClientFile(jsFile.path); + et.assertProjectInfoTelemetryEvent({ + fileStats: fileStats({ js: 1, jsSize: 1, ts: 1, tsSize: 2 }), + compilerOptions: autoJsCompilerOptions, + typeAcquisition: { + enable: true, + include: false, + exclude: false, + }, + configFileName: "jsconfig.json", + }, "/jsconfig.json"); + }); + it("detects whether language service was disabled", () => { const file = makeFile("/a.js"); const tsconfig = makeFile("/jsconfig.json", {}); const et = new TestServerEventManager([tsconfig, file]); - et.host.getFileSize = () => server.maxProgramSizeForNonTsFiles + 1; + const fileSize = server.maxProgramSizeForNonTsFiles + 1; + et.host.getFileSize = () => fileSize; et.service.openClientFile(file.path); et.getEvent(server.ProjectLanguageServiceStateEvent); et.assertProjectInfoTelemetryEvent({ - fileStats: fileStats({ js: 1 }), + fileStats: fileStats({ js: 1, jsSize: fileSize }), compilerOptions: autoJsCompilerOptions, configFileName: "jsconfig.json", typeAcquisition: { diff --git a/src/testRunner/unittests/textChanges.ts b/src/testRunner/unittests/textChanges.ts index 699f668b552..164073207b3 100644 --- a/src/testRunner/unittests/textChanges.ts +++ b/src/testRunner/unittests/textChanges.ts @@ -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. diff --git a/src/testRunner/unittests/textStorage.ts b/src/testRunner/unittests/textStorage.ts index 5486cf57745..5dce083120b 100644 --- a/src/testRunner/unittests/textStorage.ts +++ b/src/testRunner/unittests/textStorage.ts @@ -29,20 +29,20 @@ namespace ts.textStorage { 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}`); + assert.strictEqual(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}`); + assert.strictEqual(start1, start2, `lineToTextSpan ${line}::start:: expected ${start1} to equal ${start2}`); + assert.strictEqual(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}`); + assert.strictEqual(line1, line2, `positionToLineOffset ${pos}::line:: expected ${line1} to equal ${line2}`); + assert.strictEqual(offset1, offset2, `positionToLineOffset ${pos}::offset:: expected ${offset1} to equal ${offset2}`); } }); @@ -52,16 +52,93 @@ namespace ts.textStorage { 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"); + assert.isFalse(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"); + assert.isFalse(ts1.hasScriptVersionCache_TestOnly(), "should not have script version cache - 2"); ts1.getLineInfo(0); assert.isTrue(ts1.hasScriptVersionCache_TestOnly(), "have script version cache - 2"); }); + + it("should be able to return the file size immediately after construction", () => { + 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!); + + assert.strictEqual(f.content.length, ts1.getTelemetryFileSize()); + }); + + it("should be able to return the file size when backed by text", () => { + 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.useText(f.content); + assert.isFalse(ts1.hasScriptVersionCache_TestOnly()); + + assert.strictEqual(f.content.length, ts1.getTelemetryFileSize()); + }); + + it("should be able to return the file size when backed by a 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!); + + ts1.useScriptVersionCache_TestOnly(); + assert.isTrue(ts1.hasScriptVersionCache_TestOnly()); + + assert.strictEqual(f.content.length, ts1.getTelemetryFileSize()); + }); + + it("should be able to return the file size when a JS file is too large to load into text", () => { + const largeFile = { + path: "/a/large.js", + content: " ".repeat(server.maxFileSize + 1) + }; + + const host = projectSystem.createServerHost([largeFile]); + + // The large-file handling requires a ScriptInfo with a containing project + const projectService = projectSystem.createProjectService(host); + projectService.openClientFile(largeFile.path); + const scriptInfo = projectService.getScriptInfo(largeFile.path); + + const ts1 = new server.TextStorage(host, server.asNormalizedPath(largeFile.path), /*initialVersion*/ undefined, scriptInfo!); + + assert.isTrue(ts1.reloadFromDisk()); + assert.isFalse(ts1.hasScriptVersionCache_TestOnly()); + + assert.strictEqual(largeFile.content.length, ts1.getTelemetryFileSize()); + }); + + it("should return the file size without reloading the file", () => { + const oldText = "hello"; + const newText = "goodbye"; + + const changingFile = { + path: "/a/changing.ts", + content: oldText + }; + + const host = projectSystem.createServerHost([changingFile]); + // Since script info is not used in these tests, just cheat by passing undefined + const ts1 = new server.TextStorage(host, server.asNormalizedPath(changingFile.path), /*initialVersion*/ undefined, /*info*/undefined!); + + assert.isTrue(ts1.reloadFromDisk()); + + // Refresh the file and notify TextStorage + host.writeFile(changingFile.path, newText); + ts1.delayReloadFromFileIntoText(); + + assert.strictEqual(oldText.length, ts1.getTelemetryFileSize()); + + assert.isTrue(ts1.reloadWithFileText()); + + assert.strictEqual(newText.length, ts1.getTelemetryFileSize()); + }); }); } diff --git a/src/testRunner/unittests/transform.ts b/src/testRunner/unittests/transform.ts index e975e10c09c..f219fb6c683 100644 --- a/src/testRunner/unittests/transform.ts +++ b/src/testRunner/unittests/transform.ts @@ -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 6d6f95ce19c..72b1121e861 100644 --- a/src/testRunner/unittests/tsbuild.ts +++ b/src/testRunner/unittests/tsbuild.ts @@ -23,6 +23,42 @@ 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", () => { @@ -199,7 +235,7 @@ namespace ts { tick(); touch(fs, "/src/logic/index.ts"); // 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"); // Rebuild this project @@ -210,10 +246,26 @@ namespace ts { 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"); + // Does not build tests or core because there is no change in declaration file + tick(); + builder.buildInvalidatedProject(); + assert.isBelow(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"); + + // Rebuild this project + tick(); + fs.writeFileSync("/src/logic/index.ts", `${fs.readFileSync("/src/logic/index.ts")} +export class cNew {}`); + 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"); + // 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/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"); }); }); @@ -224,6 +276,10 @@ namespace ts { 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 +296,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,6 +319,142 @@ namespace ts { verifyProjectWithResolveJsonModule("/src/tests/tsconfig_withIncludeAndFiles.json"); }); }); + + describe("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("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("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 { @@ -377,7 +584,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)); @@ -457,4 +663,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..9178416373c 100644 --- a/src/testRunner/unittests/tsbuildWatchMode.ts +++ b/src/testRunner/unittests/tsbuildWatchMode.ts @@ -1,8 +1,11 @@ namespace ts.tscWatch { export import libFile = TestFSWithWatch.libFile; - function createSolutionBuilder(system: WatchedSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { + import projectsLocation = TestFSWithWatch.tsbuildProjectsLocation; + import getFilePathInProject = TestFSWithWatch.getTsBuildProjectFilePath; + import getFileFromProject = TestFSWithWatch.getTsBuildProjectFile; + export 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 }); + return ts.createSolutionBuilder(host, rootNames, defaultOptions || { watch: true }); } function createSolutionBuilderWithWatch(host: WatchedSystem, rootNames: ReadonlyArray, defaultOptions?: BuildOptions) { @@ -13,7 +16,6 @@ namespace ts.tscWatch { } describe("tsbuild-watch program updates", () => { - const projectsLocation = "/user/username/projects"; const project = "sample1"; const enum SubProject { core = "core", @@ -24,17 +26,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 { @@ -58,13 +67,17 @@ namespace ts.tscWatch { return getOutputFileNames(subProject, baseFileNameWithoutExtension).map(f => [f, host.getModifiedTime(f)] as OutputFileStamp); } - function getOutputFileStamps(host: WatchedSystem): OutputFileStamp[] { - return [ + function getOutputFileStamps(host: WatchedSystem, 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))); + } + return result; } function verifyChangedFiles(actualStamps: OutputFileStamp[], oldTimeStamps: OutputFileStamp[], changedFiles: string[]) { @@ -85,70 +98,901 @@ 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() { + function createSolutionInWatchMode(allFiles: ReadonlyArray, defaultOptions?: BuildOptions, disableConsoleClears?: boolean) { 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); + 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: WatchedSystem) { + 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) { + const outputFileStamps = getOutputFileStamps(host, additionalFiles); + host.writeFile(fileName, content); + verifyChangeAfterTimeout(outputFileStamps); + } + + function verifyChangeAfterTimeout(outputFileStamps: OutputFileStamp[]) { + host.checkTimeoutQueueLengthAndRun(1); // Builds core + const changedCore = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles(changedCore, outputFileStamps, [ + ...getOutputFileNames(SubProject.core, "anotherModule"), // This should not be written really + ...getOutputFileNames(SubProject.core, "index"), + ...(additionalFiles ? getOutputFileNames(SubProject.core, newFileWithoutExtension) : emptyArray) + ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds logic + const changedLogic = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles(changedLogic, changedCore, [ + ...getOutputFileNames(SubProject.logic, "index") // Again these need not be written + ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds tests + const changedTests = getOutputFileStamps(host, additionalFiles); + verifyChangedFiles(changedTests, changedLogic, [ + ...getOutputFileNames(SubProject.tests, "index") // Again these need not be written + ]); + 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 host = createSolutionInWatchMode(allFiles); + const outputFileStamps = getOutputFileStamps(host); + host.writeFile(core[1].path, `${core[1].content} +function foo() { }`); + 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.checkTimeoutQueueLength(0); + checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(host); + }); + + 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 = createWatchedSystem(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") + ]); + host.checkTimeoutQueueLengthAndRun(1); // Builds tests + const changedTests = getOutputFileStamps(host); + verifyChangedFiles(changedTests, changedLogic, [ + ...getOutputFileNames(SubProject.tests, "index") + ]); + 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 = createWatchedSystem([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; }`); + + // 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); + const changedCore = getOutputFileStamps(); 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 - ]); 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") ]); host.checkTimeoutQueueLength(0); checkOutputErrorsIncremental(host, emptyArray); + verifyWatches(); + } + + function getOutputFileStamps(): OutputFileStamp[] { + const result = [ + ...getOutputStamps(host, SubProject.core, "index"), + ...getOutputStamps(host, SubProject.logic, "index"), + ]; + 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 = createWatchedSystem(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); + 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); + 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("tsc-watch and tsserver works with project references", () => { + describe("invoking when references are already built", () => { + function verifyWatchesOfProject(host: WatchedSystem, 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: WatchedSystem) => ReadonlyArray) { + // Build the composite project + const host = createWatchedSystem(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: WatchedSystem) => ReadonlyArray) { + // Build the composite project + const { host, solutionBuilder } = createSolutionOfProject(allFiles, currentDirectory, solutionBuilderconfig, getOutputFileStamps); + + // Build in watch mode + const watch = createWatchOfConfigFileReturningBuilder(watchConfig, host); + checkOutputErrorsInitial(host, emptyArray); + + return { host, solutionBuilder, watch }; + } + + function createSolutionAndServiceOfProject(allFiles: ReadonlyArray, + currentDirectory: string, + solutionBuilderconfig: string, + openFileName: string, + getOutputFileStamps: (host: WatchedSystem) => 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); + } + + type Watch = () => BuilderProgram; + + function verifyDependencies(watch: Watch, filePath: string, expected: ReadonlyArray) { + checkArray(`${filePath} dependencies`, watch().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: WatchedSystem, withTsserver?: boolean) { + verifyWatchesOfProject(host, withTsserver ? expectedWatchedFiles.filter(f => f !== tests[1].path.toLowerCase()) : expectedWatchedFiles, expectedWatchedDirectoriesRecursive); + } + + function verifyScenario( + edit: (host: WatchedSystem, 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().getProgram(), 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: WatchedSystem, + watch: Watch, + expectedProgramFiles: ReadonlyArray, + expectedWatchedFiles: ReadonlyArray, + expectedWatchedDirectoriesRecursive: ReadonlyArray, + dependencies: ReadonlyArray<[string, ReadonlyArray]>, + expectedWatchedDirectories?: ReadonlyArray) { + checkProgramActualFiles(watch().getProgram(), 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: WatchedSystem) { + return expectedFiles.map(file => [file, host.getModifiedTime(file)] as OutputFileStamp); + } + + function verifyProgram(host: WatchedSystem, watch: Watch) { + verifyWatchState(host, watch, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, defaultDependencies, expectedWatchedDirectories); + } + + function verifyProject(host: WatchedSystem, service: projectSystem.TestProjectService, orphanInfos?: ReadonlyArray) { + verifyServerState(host, service, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos); + } + + function verifyServerState( + host: WatchedSystem, + 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: WatchedSystem, solutionBuilder: SolutionBuilder) => void, + expectedEditErrors: ReadonlyArray, + expectedProgramFiles: ReadonlyArray, + expectedWatchedFiles: ReadonlyArray, + expectedWatchedDirectoriesRecursive: ReadonlyArray, + dependencies: ReadonlyArray<[string, ReadonlyArray]>, + revert?: (host: WatchedSystem) => 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: WatchedSystem) { + return expectedFiles.map(file => [file, host.getModifiedTime(file)] as OutputFileStamp); + } + 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/tscWatchMode.ts b/src/testRunner/unittests/tscWatchMode.ts index da1c4fd0d70..65f64b9da78 100644 --- a/src/testRunner/unittests/tscWatchMode.ts +++ b/src/testRunner/unittests/tscWatchMode.ts @@ -12,23 +12,32 @@ namespace ts.tscWatch { export import checkOutputDoesNotContain = TestFSWithWatch.checkOutputDoesNotContain; export import Tsc_WatchDirectory = TestFSWithWatch.Tsc_WatchDirectory; - export function checkProgramActualFiles(program: Program, expectedFiles: string[]) { + export function checkProgramActualFiles(program: Program, expectedFiles: ReadonlyArray) { checkArray(`Program actual files`, program.getSourceFiles().map(file => file.fileName), expectedFiles); } - export function checkProgramRootFiles(program: Program, expectedFiles: string[]) { + export function checkProgramRootFiles(program: Program, expectedFiles: ReadonlyArray) { checkArray(`Program rootFileNames`, program.getRootFileNames(), expectedFiles); } - function createWatchOfConfigFile(configFileName: string, host: WatchedSystem, maxNumberOfFilesToIterateForInvalidation?: number) { + export function createWatchOfConfigFileReturningBuilder(configFileName: string, host: WatchedSystem, maxNumberOfFilesToIterateForInvalidation?: number) { + const compilerHost = createWatchCompilerHostOfConfigFile(configFileName, {}, host); + compilerHost.maxNumberOfFilesToIterateForInvalidation = maxNumberOfFilesToIterateForInvalidation; + const watch = createWatchProgram(compilerHost); + return () => watch.getCurrentProgram(); + } + + export 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)); + 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(); } @@ -77,7 +86,7 @@ namespace ts.tscWatch { logsBeforeWatchDiagnostic: string[] | undefined, preErrorsWatchDiagnostic: Diagnostic, logsBeforeErrors: string[] | undefined, - errors: ReadonlyArray, + errors: ReadonlyArray | ReadonlyArray, disableConsoleClears?: boolean | undefined, ...postErrorsWatchDiagnostics: Diagnostic[] ) { @@ -96,8 +105,12 @@ namespace ts.tscWatch { assert.equal(host.screenClears.length, screenClears, "Expected number of screen clears"); host.clearOutput(); - function assertDiagnostic(diagnostic: Diagnostic) { - const expected = formatDiagnostic(diagnostic, host); + 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++; } @@ -130,13 +143,13 @@ namespace ts.tscWatch { } } - function createErrorsFoundCompilerDiagnostic(errors: ReadonlyArray) { + 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, disableConsoleClears?: boolean, logsBeforeErrors?: string[]) { + export function checkOutputErrorsInitial(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, disableConsoleClears?: boolean, logsBeforeErrors?: string[]) { checkOutputErrors( host, /*logsBeforeWatchDiagnostic*/ undefined, @@ -147,7 +160,7 @@ namespace ts.tscWatch { createErrorsFoundCompilerDiagnostic(errors)); } - export function checkOutputErrorsIncremental(host: WatchedSystem, errors: ReadonlyArray, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { + export function checkOutputErrorsIncremental(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { checkOutputErrors( host, logsBeforeWatchDiagnostic, @@ -158,7 +171,7 @@ namespace ts.tscWatch { createErrorsFoundCompilerDiagnostic(errors)); } - function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: ReadonlyArray, expectedExitCode: ExitStatus, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { + function checkOutputErrorsIncrementalWithExit(host: WatchedSystem, errors: ReadonlyArray | ReadonlyArray, expectedExitCode: ExitStatus, disableConsoleClears?: boolean, logsBeforeWatchDiagnostic?: string[], logsBeforeErrors?: string[]) { checkOutputErrors( host, logsBeforeWatchDiagnostic, @@ -439,6 +452,33 @@ namespace ts.tscWatch { 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", @@ -1034,7 +1074,10 @@ namespace ts.tscWatch { const host = createWatchedSystem([file1, configFile, libFile]); const watch = createWatchOfConfigFile(configFile.path, host); - checkProgramActualFiles(watch(), [libFile.path]); + 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", () => { @@ -1060,7 +1103,10 @@ namespace ts.tscWatch { const host = createWatchedSystem([f, config, t1, t2], { currentDirectory: getDirectoryPath(f.path) }); const watch = createWatchOfConfigFile(config.path, host); - checkProgramActualFiles(watch(), [t1.path, t2.path]); + 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", () => { @@ -1186,7 +1232,7 @@ namespace ts.tscWatch { host.reloadFS(files); host.runQueuedTimeoutCallbacks(); checkProgramActualFiles(watch(), files.map(file => file.path)); - checkOutputErrorsIncremental(host, []); + checkOutputErrorsIncremental(host, emptyArray); }); it("watched files when file is deleted and new file is added as part of change", () => { @@ -1252,7 +1298,7 @@ export default test;`; ]); 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) + 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) { @@ -1312,18 +1358,59 @@ export class B assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); }); + it("updates errors when deep import through declaration 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.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; +}` + }; + 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 }) + content: JSON.stringify({ compilerOptions: {} }) }; const files = [aFile, config, libFile]; const host = createWatchedSystem(files, { currentDirectory }); @@ -1331,8 +1418,7 @@ foo().hello` 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.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) @@ -1340,20 +1426,284 @@ foo().hello` 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.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); - delete (compilerOptions.strict); - host.writeFile(config.path, JSON.stringify({ compilerOptions })); + 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 when file transitively exported file changes", () => { + const projectLocation = "/user/username/projects/myproject"; + const config: File = { + path: `${projectLocation}/tsconfig.json`, + content: JSON.stringify({ + files: ["app.ts"], + compilerOptions: { baseUrl: "." } + }) + }; + const app: File = { + path: `${projectLocation}/app.ts`, + content: `import { Data } from "lib2/public"; +export class App { + public constructor() { + new Data().test(); + } +}` + }; + const lib2Public: File = { + path: `${projectLocation}/lib2/public.ts`, + content: `export * from "./data";` + }; + const lib2Data: File = { + path: `${projectLocation}/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: `${projectLocation}/lib1/public.ts`, + content: `export * from "./tools/public";` + }; + const lib1ToolsPublic: File = { + path: `${projectLocation}/lib1/tools/public.ts`, + content: `export * from "./tools.interface";` + }; + const lib1ToolsInterface: File = { + path: `${projectLocation}/lib1/tools/tools.interface.ts`, + content: `export interface ITest { + title: string; +}` + }; + + function verifyTransitiveExports(filesWithoutConfig: ReadonlyArray) { + const files = [config, ...filesWithoutConfig]; + const host = createWatchedSystem(files, { currentDirectory: projectLocation }); + const watch = createWatchOfConfigFile(config.path, host); + checkProgramActualFiles(watch(), filesWithoutConfig.map(f => f.path)); + checkOutputErrorsInitial(host, emptyArray); + + host.writeFile(lib1ToolsInterface.path, lib1ToolsInterface.content.replace("title", "title2")); + host.checkTimeoutQueueLengthAndRun(1); + checkProgramActualFiles(watch(), filesWithoutConfig.map(f => f.path)); + checkOutputErrorsIncremental(host, [ + "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([libFile, app, lib2Public, lib2Data, lib1Public, lib1ToolsPublic, lib1ToolsInterface]); + }); + + it("when there are circular import and exports", () => { + const lib2Data: File = { + path: `${projectLocation}/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: `${projectLocation}/lib2/data2.ts`, + content: `import { Data } from "./data"; +export class Data2 { + public dat?: Data; +}` + }; + verifyTransitiveExports([libFile, app, lib2Public, lib2Data, lib2Data2, lib1Public, lib1ToolsPublic, lib1ToolsInterface]); + }); + }); + + 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]); + } + }); }); describe("tsc-watch emit with outFile or out setting", () => { @@ -2357,6 +2707,46 @@ declare module "fs" { 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("tsc-watch with when module emit is specified as node", () => { diff --git a/src/testRunner/unittests/tsconfigParsing.ts b/src/testRunner/unittests/tsconfigParsing.ts index 6909e260d2a..255129d9fb6 100644 --- a/src/testRunner/unittests/tsconfigParsing.ts +++ b/src/testRunner/unittests/tsconfigParsing.ts @@ -141,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); diff --git a/src/testRunner/unittests/tsserverProjectSystem.ts b/src/testRunner/unittests/tsserverProjectSystem.ts index 7114759b097..cda60e9b5ff 100644 --- a/src/testRunner/unittests/tsserverProjectSystem.ts +++ b/src/testRunner/unittests/tsserverProjectSystem.ts @@ -17,6 +17,14 @@ namespace ts.projectSystem { import safeList = TestFSWithWatch.safeList; import Tsc_WatchDirectory = TestFSWithWatch.Tsc_WatchDirectory; + const outputEventRegex = /Content\-Length: [\d]+\r\n\r\n/; + function mapOutputToJson(s: string) { + return convertToObject( + parseJsonText("json.json", s.replace(outputEventRegex, "")), + [] + ); + } + export const customTypesMap = { path: "/typesMap.json", content: `{ @@ -58,12 +66,13 @@ namespace ts.projectSystem { getLogFileName: () => undefined, }; - function createHasErrorMessageLogger() { + 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: () => { + msg: (s, type) => { + Debug.fail(`Error: ${s}, type: ${type}`); hasErrorMsg = true; } }; @@ -85,6 +94,7 @@ namespace ts.projectSystem { isKnownTypesPackageName = notImplemented; installPackage = notImplemented; + inspectValue = notImplemented; executePendingCommands() { const actionsToRun = this.postExecActions; @@ -116,7 +126,7 @@ namespace ts.projectSystem { this.projectService.updateTypingsForProject(response); } - enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray) { + enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray) { const request = server.createInstallTypingsRequest(project, typeAcquisition, unresolvedImports, this.globalTypingsCacheLocation); this.install(request); } @@ -173,7 +183,7 @@ namespace ts.projectSystem { } export function fileStats(nonZeroStats: Partial): server.FileStats { - return { ts: 0, tsx: 0, dts: 0, js: 0, jsx: 0, deferred: 0, ...nonZeroStats }; + 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 { @@ -321,13 +331,47 @@ namespace ts.projectSystem { typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, - logger: opts.logger || nullLogger, + logger: opts.logger || createHasErrorMessageLogger().logger, canUseEvents: false }; return new TestSession({ ...sessionOptions, ...opts }); } + 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 }; + } + + 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(); + } + } + interface CreateProjectServiceParameters { cancellationToken?: HostCancellationToken; logger?: server.Logger; @@ -358,7 +402,7 @@ namespace ts.projectSystem { } export function createProjectService(host: server.ServerHost, parameters: CreateProjectServiceParameters = {}, options?: Partial) { const cancellationToken = parameters.cancellationToken || server.nullCancellationToken; - const logger = parameters.logger || nullLogger; + 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 } @@ -390,11 +434,11 @@ namespace ts.projectSystem { return values.next().value; } - export function checkProjectActualFiles(project: server.Project, expectedFiles: string[]) { + export function checkProjectActualFiles(project: server.Project, expectedFiles: ReadonlyArray) { checkArray(`${server.ProjectKind[project.projectKind]} project, actual files`, project.getFileNames(), expectedFiles); } - function checkProjectRootFiles(project: server.Project, expectedFiles: string[]) { + function checkProjectRootFiles(project: server.Project, expectedFiles: ReadonlyArray) { checkArray(`${server.ProjectKind[project.projectKind]} project, rootFileNames`, project.getRootFiles(), expectedFiles); } @@ -448,6 +492,14 @@ namespace ts.projectSystem { const toLocation = protocolToLocation(str); return { start: toLocation(span.start), end: toLocation(textSpanEnd(span)) }; } + function protocolRenameSpanFromSubstring( + str: string, + substring: string, + options?: SpanFromSubstringOptions, + prefixSuffixText?: { readonly prefixText?: string, readonly suffixText?: string }, + ): protocol.RenameTextSpan { + return { ...protocolTextSpanFromSubstring(str, substring, options), ...prefixSuffixText }; + } function textSpanFromSubstring(str: string, substring: string, options?: SpanFromSubstringOptions): TextSpan { const start = nthIndexOf(str, substring, options ? options.index : 0); Debug.assert(start !== -1); @@ -456,12 +508,15 @@ namespace ts.projectSystem { function protocolFileLocationFromSubstring(file: File, substring: string): protocol.FileLocationRequestArgs { return { file: file.path, ...protocolLocationFromSubstring(file.content, substring) }; } - function protocolFileSpanFromSubstring(file: File, substring: string, options?: SpanFromSubstringOptions) { + 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); + } interface SpanFromSubstringOptions { readonly index: number; } @@ -1800,6 +1855,63 @@ namespace ts.projectSystem { } }); + 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", @@ -2859,18 +2971,7 @@ namespace ts.projectSystem { host.getFileSize = (filePath: string) => filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); - let lastEvent!: server.ProjectLanguageServiceStateEvent; - const session = createSession(host, { - canUseEvents: true, - eventHandler: e => { - if (e.eventName === server.ConfigFileDiagEvent || e.eventName === server.ProjectsUpdatedInBackgroundEvent || e.eventName === server.ProjectInfoTelemetryEvent || e.eventName === server.OpenFileInfoTelemetryEvent || e.eventName === server.LargeFileReferencedEvent || e.eventName === server.SurveyReady) { - return; - } - assert.equal(e.eventName, server.ProjectLanguageServiceStateEvent); - assert.equal(e.data.project.getProjectName(), config.path, "project name"); - lastEvent = e; - } - }); + const { session, events } = createSessionWithEventTracking(host, server.ProjectLanguageServiceStateEvent); session.executeCommand({ seq: 0, type: "request", @@ -2881,17 +2982,19 @@ namespace ts.projectSystem { checkNumberOfProjects(projectService, { configuredProjects: 1 }); const project = configuredProjectAt(projectService, 0); assert.isFalse(project.languageServiceEnabled, "Language service enabled"); - assert.isTrue(!!lastEvent, "should receive event"); - assert.equal(lastEvent.data.project, project, "project name"); - assert.equal(lastEvent.data.project.getProjectName(), config.path, "config path"); - assert.isFalse(lastEvent.data.languageServiceEnabled, "Language service state"); + 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(lastEvent.data.project, project, "project"); - assert.isTrue(lastEvent.data.languageServiceEnabled, "Language service state"); + 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"); }); it("syntactic features work even if language service is disabled", () => { @@ -2911,17 +3014,7 @@ namespace ts.projectSystem { const originalGetFileSize = host.getFileSize; host.getFileSize = (filePath: string) => filePath === f2.path ? server.maxProgramSizeForNonTsFiles + 1 : originalGetFileSize.call(host, filePath); - let lastEvent!: server.ProjectLanguageServiceStateEvent; - const session = createSession(host, { - canUseEvents: true, - eventHandler: e => { - if (e.eventName === server.ConfigFileDiagEvent || e.eventName === server.ProjectInfoTelemetryEvent || e.eventName === server.OpenFileInfoTelemetryEvent) { - return; - } - assert.equal(e.eventName, server.ProjectLanguageServiceStateEvent); - lastEvent = e; - } - }); + const { session, events } = createSessionWithEventTracking(host, server.ProjectLanguageServiceStateEvent); session.executeCommand({ seq: 0, type: "request", @@ -2933,9 +3026,9 @@ namespace ts.projectSystem { checkNumberOfProjects(projectService, { configuredProjects: 1 }); const project = configuredProjectAt(projectService, 0); assert.isFalse(project.languageServiceEnabled, "Language service enabled"); - assert.isTrue(!!lastEvent, "should receive event"); - assert.equal(lastEvent.data.project, project, "project name"); - assert.isFalse(lastEvent.data.languageServiceEnabled, "Language service state"); + 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); @@ -2997,7 +3090,7 @@ namespace ts.projectSystem { const configProject = configuredProjectAt(projectService, 0); checkProjectActualFiles(configProject, lazyConfiguredProjectsFromExternalProject ? emptyArray : // Since no files opened from this project, its not loaded - [libFile.path, configFile.path]); + [configFile.path]); host.reloadFS([libFile, site]); host.checkTimeoutQueueLengthAndRun(1); @@ -3136,7 +3229,7 @@ namespace ts.projectSystem { 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, 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`); @@ -3204,10 +3297,27 @@ namespace ts.projectSystem { { text: "number", kind: "keyword" } ], documentation: [], - tags: [] + tags: undefined, }); }); + it("dynamic file with reference paths without external project", () => { + const file: File = { + path: "^walkThroughSnippet:/Users/UserName/projects/someProject/out/someFile#1.js", + content: `/// +/// +var x = 10;` + }; + const host = createServerHost([libFile]); + const projectService = createProjectService(host); + projectService.openClientFile(file.path, file.content); + + projectService.checkNumberOfProjects({ inferredProjects: 1 }); + const project = projectService.inferredProjects[0]; + checkProjectRootFiles(project, [file.path]); + checkProjectActualFiles(project, [file.path, libFile.path]); + }); + it("files opened, closed affecting multiple projects", () => { const file: File = { path: "/a/b/projects/config/file.ts", @@ -3323,7 +3433,17 @@ namespace ts.projectSystem { command: protocol.CommandTypes.GetApplicableRefactors, arguments: { file: file2.path, startLine: 1, startOffset, endLine: 1, endOffset: startOffset + 1 } }); + }); + describe("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, []); + }); }); describe("includes deferred files in the project context", () => { @@ -3491,7 +3611,7 @@ namespace ts.projectSystem { host.checkTimeoutQueueLength(2); // Update configured project and projects for open file checkProjectActualFiles(services.configuredProjects.get(config.path)!, filesWithFileA.map(f => f.path)); - // host.fileExists = originalFileExists; + // host.fileExists = originalFileExists; openFile(fileSubA); // This should create inferred project since fileSubA not on the disk checkProjectActualFiles(services.configuredProjects.get(config.path)!, mapDefined(filesWithFileA, f => f === fileA ? undefined : f.path)); @@ -3540,14 +3660,7 @@ namespace ts.projectSystem { }); function createSessionWithEventHandler(host: TestServerHost) { - const surveyEvents: server.SurveyReady[] = []; - const session = createSession(host, { - eventHandler: e => { - if (e.eventName === server.SurveyReady) { - surveyEvents.push(e); - } - } - }); + const { session, events: surveyEvents } = createSessionWithEventTracking(host, server.SurveyReady); return { session, verifySurveyReadyEvent }; @@ -3672,7 +3785,7 @@ namespace ts.projectSystem { path: `${projectRoot}/app1/tsconfig.json`, content: JSON.stringify({ files: ["app.ts", "../core/core.ts"], - compilerOptions: { outFile : "build/output.js" }, + compilerOptions: { outFile: "build/output.js" }, compileOnSave: true }) }; @@ -3796,25 +3909,39 @@ namespace ts.projectSystem { describe("when opening new file that doesnt exist on disk yet", () => { function verifyNonExistentFile(useProjectRoot: boolean) { - const host = createServerHost([libFile]); + 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 folderPath = "/user/someuser/projects/someFolder"; 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: "JS", + 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); @@ -3823,7 +3950,11 @@ namespace ts.projectSystem { assert.isDefined(infoForUnitiledAtRoot); assert.isUndefined(infoForUntitledAtProjectRoot); } - host.checkTimeoutQueueLength(2); + 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(); @@ -3834,19 +3965,26 @@ namespace ts.projectSystem { files: [untitledFile] } }); - host.checkTimeoutQueueLength(3); + host.checkTimeoutQueueLength(1); // Run the last one = get error request host.runQueuedTimeoutCallbacks(newTimeoutId); assert.isFalse(hasError()); - host.checkTimeoutQueueLength(2); + host.checkTimeoutQueueLength(0); checkErrorMessage(session, "syntaxDiag", { file: untitledFile, diagnostics: [] }); session.clearMessages(); host.runQueuedImmediateCallbacks(); assert.isFalse(hasError()); - checkErrorMessage(session, "semanticDiag", { file: untitledFile, diagnostics: [] }); + 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); @@ -4440,8 +4578,7 @@ namespace ts.projectSystem { const defaultSettings = projectService.getFormatCodeOptions(f1.path as server.NormalizedPath); // set global settings - const newGlobalSettings1 = clone(defaultSettings); - newGlobalSettings1.placeOpenBraceOnNewLineForControlBlocks = !newGlobalSettings1.placeOpenBraceOnNewLineForControlBlocks; + const newGlobalSettings1 = { ...defaultSettings, placeOpenBraceOnNewLineForControlBlocks: !defaultSettings.placeOpenBraceOnNewLineForControlBlocks }; projectService.setHostConfiguration({ formatOptions: newGlobalSettings1 }); // get format options for file - should be equal to new global settings @@ -4449,8 +4586,7 @@ namespace ts.projectSystem { assert.deepEqual(s1, newGlobalSettings1, "file settings should be the same with global settings"); // set per file format options - const newPerFileSettings = clone(defaultSettings); - newPerFileSettings.insertSpaceAfterCommaDelimiter = !newPerFileSettings.insertSpaceAfterCommaDelimiter; + 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 @@ -4458,8 +4594,7 @@ namespace ts.projectSystem { 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 = clone(defaultSettings); - newGlobalSettings2.insertSpaceAfterSemicolonInForStatements = !newGlobalSettings2.insertSpaceAfterSemicolonInForStatements; + const newGlobalSettings2 = { ...defaultSettings, insertSpaceAfterSemicolonInForStatements: !defaultSettings.insertSpaceAfterSemicolonInForStatements }; projectService.setHostConfiguration({ formatOptions: newGlobalSettings2 }); // get format options for file - should be equal to new per-file settings @@ -4924,7 +5059,7 @@ namespace ts.projectSystem { checkErrorMessage(session, "suggestionDiag", { file: file.path, diagnostics: [ - createDiagnostic({ line: 1, offset: 12 }, { line: 1, offset: 13 }, Diagnostics._0_is_declared_but_its_value_is_never_read, ["p"], "suggestion", /*reportsUnnecssary*/ true) + createDiagnostic({ line: 1, offset: 12 }, { line: 1, offset: 13 }, Diagnostics._0_is_declared_but_its_value_is_never_read, ["p"], "suggestion", /*reportsUnnecessary*/ true), ], }); checkCompleteEvent(session, 2, expectedSequenceId); @@ -5057,7 +5192,7 @@ namespace ts.projectSystem { function getFileNotFoundDiagnostic(configFile: File, relativeFileName: string): ConfigFileDiagnostic { const findString = `{"path":"./${relativeFileName}"}`; - const d = Diagnostics.File_0_does_not_exist; + const d = Diagnostics.File_0_not_found; const start = configFile.content.indexOf(findString); return { fileName: configFile.path, @@ -6778,9 +6913,9 @@ namespace ts.projectSystem { fileName: "/a.1.ts", textChanges: [ { - start: { line: 0, offset: 0 }, - end: { line: 0, offset: 0 }, - newText: "export const a = 0;", + start: { line: 0, offset: 0 }, + end: { line: 0, offset: 0 }, + newText: "export const a = 0;\n", }, ], } @@ -7335,7 +7470,7 @@ namespace ts.projectSystem { const recursiveWatchedDirectories: string[] = [`${appFolder}`, `${appFolder}/node_modules`].concat(getNodeModuleDirectories(getDirectoryPath(appFolder))); verifyProject(); - let timeoutAfterReloadFs = timeoutDuringPartialInstallation; + let npmInstallComplete = false; // Simulate npm install const filesAndFoldersToAdd: File[] = [ @@ -7364,8 +7499,8 @@ namespace ts.projectSystem { { 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 folder, scheduled project update - verifyAfterPartialOrCompleteNpmInstall(2); + // Since we added/removed in .staging no timeout + verifyAfterPartialOrCompleteNpmInstall(0); // Remove file "/a/b/node_modules/.staging/typescript-8493ea5d/package.json.3017591594" filesAndFoldersToAdd.length--; @@ -7377,7 +7512,7 @@ namespace ts.projectSystem { { 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(2); + verifyAfterPartialOrCompleteNpmInstall(0); filesAndFoldersToAdd.push(...[ { path: "/a/b/node_modules/.staging/rxjs-22375c61/src/scheduler" }, @@ -7386,7 +7521,7 @@ namespace ts.projectSystem { { 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(2); + verifyAfterPartialOrCompleteNpmInstall(0); // remove /a/b/node_modules/.staging/rxjs-22375c61/package.json.2252192041 filesAndFoldersToAdd.length--; @@ -7414,12 +7549,12 @@ namespace ts.projectSystem { // 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 - timeoutAfterReloadFs = true; + npmInstallComplete = true; verifyAfterPartialOrCompleteNpmInstall(2); function verifyAfterPartialOrCompleteNpmInstall(timeoutQueueLengthWhenRunningTimeouts: number) { host.reloadFS(projectFiles.concat(otherFiles, filesAndFoldersToAdd)); - if (timeoutAfterReloadFs) { + if (npmInstallComplete || timeoutDuringPartialInstallation) { host.checkTimeoutQueueLengthAndRun(timeoutQueueLengthWhenRunningTimeouts); } else { @@ -7435,7 +7570,7 @@ namespace ts.projectSystem { const projectFilePaths = map(projectFiles, f => f.path); checkProjectActualFiles(project, projectFilePaths); - const filesWatched = filter(projectFilePaths, p => p !== app.path); + 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); @@ -8008,15 +8143,7 @@ namespace ts.projectSystem { verifyProjectsUpdatedInBackgroundEvent(createSessionWithProjectChangedEventHandler); function createSessionWithProjectChangedEventHandler(host: TestServerHost): ProjectsUpdatedInBackgroundEventVerifier { - const projectChangedEvents: server.ProjectsUpdatedInBackgroundEvent[] = []; - const session = createSession(host, { - eventHandler: e => { - if (e.eventName === server.ProjectsUpdatedInBackgroundEvent) { - projectChangedEvents.push(e); - } - } - }); - + const { session, events: projectChangedEvents } = createSessionWithEventTracking(host, server.ProjectsUpdatedInBackgroundEvent); return { session, verifyProjectsUpdatedInBackgroundEventHandler, @@ -8056,7 +8183,7 @@ namespace ts.projectSystem { function createSessionThatUsesEvents(host: TestServerHost, noGetErrOnBackgroundUpdate?: boolean): ProjectsUpdatedInBackgroundEventVerifier { - const session = createSession(host, { canUseEvents: true, noGetErrOnBackgroundUpdate }); + const { session, getEvents, clearEvents } = createSessionWithDefaultEventHandler(host, server.ProjectsUpdatedInBackgroundEvent, { noGetErrOnBackgroundUpdate }); return { session, @@ -8070,16 +8197,7 @@ namespace ts.projectSystem { openFiles: e.data.openFiles }; }); - const outputEventRegex = /Content\-Length: [\d]+\r\n\r\n/; - const events: protocol.ProjectsUpdatedInBackgroundEvent[] = filter( - map( - host.getOutput(), s => convertToObject( - parseJsonText("json.json", s.replace(outputEventRegex, "")), - [] - ) - ), - e => e.event === server.ProjectsUpdatedInBackgroundEvent - ); + 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]; @@ -8087,7 +8205,7 @@ namespace ts.projectSystem { }); // Verified the events, reset them - session.clearMessages(); + clearEvents(); if (events.length) { host.checkTimeoutQueueLength(noGetErrOnBackgroundUpdate ? 0 : 1); // Error checking queued only if not noGetErrOnBackgroundUpdate @@ -8283,19 +8401,21 @@ namespace ts.projectSystem { const response = executeSessionRequest(session, protocol.CommandTypes.Rename, { file: aFc, ...protocolLocationFromSubstring(cFile.content, "C") }); assert.equal(aFile.content, bFile.content); - const abLocs: protocol.TextSpan[] = [ - protocolTextSpanFromSubstring(aFile.content, "C"), - protocolTextSpanFromSubstring(aFile.content, "C", { index: 1 }), + const abLocs: protocol.RenameTextSpan[] = [ + protocolRenameSpanFromSubstring(aFile.content, "C"), + protocolRenameSpanFromSubstring(aFile.content, "C", { index: 1 }), ]; - const cLocs: protocol.TextSpan[] = [protocolTextSpanFromSubstring(cFile.content, "C")]; + const span = protocolRenameSpanFromSubstring(cFile.content, "C"); + const cLocs: protocol.RenameTextSpan[] = [span]; assert.deepEqual(response, { info: { canRename: true, displayName: "C", + fileToRename: undefined, fullDisplayName: '"/users/username/projects/a/c/fc".C', kind: ScriptElementKind.constElement, kindModifiers: ScriptElementKindModifier.exportedModifier, - localizedErrorMessage: undefined, + triggerSpan: protocolTextSpanFromSubstring(cFile.content, "C"), }, locs: [ { file: aFc, locs: cLocs }, @@ -8658,9 +8778,20 @@ new C();` } function verifyWatchesWithConfigFile(host: TestServerHost, files: File[], openFile: File, extraExpectedDirectories?: ReadonlyArray) { - checkWatchedFiles(host, mapDefined(files, f => f === openFile ? undefined : f.path)); + const expectedRecursiveDirectories = arrayToSet([projectLocation, `${projectLocation}/${nodeModulesAtTypes}`, ...(extraExpectedDirectories || emptyArray)]); + checkWatchedFiles(host, mapDefined(files, f => { + if (f === openFile) { + return undefined; + } + const indexOfNodeModules = f.path.indexOf("/node_modules/"); + if (indexOfNodeModules === -1) { + return f.path; + } + expectedRecursiveDirectories.set(f.path.substr(0, indexOfNodeModules + "/node_modules".length), true); + return undefined; + })); checkWatchedDirectories(host, [], /*recursive*/ false); - checkWatchedDirectories(host, [projectLocation, `${projectLocation}/${nodeModulesAtTypes}`, ...(extraExpectedDirectories || emptyArray)], /*recursive*/ true); + checkWatchedDirectories(host, arrayFrom(expectedRecursiveDirectories.keys()), /*recursive*/ true); } describe("from files in same folder", () => { @@ -8862,7 +8993,7 @@ new C();` verifyTrace(resolutionTrace, expectedTrace); const currentDirectory = getDirectoryPath(file1.path); - const watchedFiles = mapDefined(files, f => f === file1 ? undefined : f.path); + const watchedFiles = mapDefined(files, f => f === file1 || f.path.indexOf("/node_modules/") !== -1 ? undefined : f.path); forEachAncestorDirectory(currentDirectory, d => { watchedFiles.push(combinePaths(d, "tsconfig.json"), combinePaths(d, "jsconfig.json")); }); @@ -8972,6 +9103,53 @@ export const x = 10;` verifyModuleResolution(/*useNodeFile*/ false); }); }); + + 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;` + }; + it("when watching node_modules in inferred project for failed lookup/closed script infos", () => { + const files = [libFile, file1, file2]; + const host = createServerHost(files); + const service = createProjectService(host); + service.openClientFile(file1.path); + checkNumberOfProjects(service, { inferredProjects: 1 }); + const project = service.inferredProjects[0]; + checkProjectActualFiles(project, files.map(f => f.path)); + (project as ResolutionCacheHost).maxNumberOfFilesToIterateForInvalidation = 1; + 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 files = [libFile, file1, file2, config]; + const host = createServerHost(files); + const service = createProjectService(host); + service.openClientFile(file1.path); + checkNumberOfProjects(service, { configuredProjects: 1 }); + const project = Debug.assertDefined(service.configuredProjects.get(config.path)); + checkProjectActualFiles(project, files.map(f => f.path)); + host.checkTimeoutQueueLength(0); + + host.ensureFileOrFolder(npmCacheFile); + host.checkTimeoutQueueLength(0); + }); + }); }); describe("tsserverProjectSystem watchDirectories implementation", () => { @@ -9079,7 +9257,7 @@ export const x = 10;` Debug.assert(!!project.resolveModuleNames); - const edits = project.getLanguageService().getEditsForFileRename("/old.ts", "/new.ts", testFormatOptions, emptyOptions); + const edits = project.getLanguageService().getEditsForFileRename("/old.ts", "/new.ts", testFormatSettings, emptyOptions); assert.deepEqual>(edits, [{ fileName: "/user.ts", textChanges: [{ @@ -9269,14 +9447,7 @@ export const x = 10;` }; files.push(largeFile); const host = createServerHost(files); - const largeFileReferencedEvents: server.LargeFileReferencedEvent[] = []; - const session = createSession(host, { - eventHandler: e => { - if (e.eventName === server.LargeFileReferencedEvent) { - largeFileReferencedEvents.push(e); - } - } - }); + const { session, events: largeFileReferencedEvents } = createSessionWithEventTracking(host, server.LargeFileReferencedEvent); return { session, verifyLargeFile }; @@ -9336,6 +9507,198 @@ export const x = 10;` }); }); + describe("tsserverProjectSystem 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); + } + }); + }); + }); + describe("tsserverProjectSystem syntax operations", () => { function navBarFull(session: TestSession, file: File) { return JSON.stringify(session.executeCommandSeq({ @@ -9448,8 +9811,7 @@ export function Test2() { content: "{}", }; - const host = createServerHost([aTs, bTs, tsconfig]); - const session = createSession(host); + const session = createSession(createServerHost([aTs, bTs, tsconfig])); openFilesForSession([aTs, bTs], session); const requestLocation: protocol.FileLocationRequestArgs = { @@ -9501,7 +9863,7 @@ export function Test2() { kindModifiers: ScriptElementKindModifier.exportedModifier, name: "foo", source: [{ text: "./a", kind: "text" }], - tags: emptyArray, + tags: undefined, }; assert.deepEqual | undefined>(detailsResponse, [ { @@ -9555,6 +9917,58 @@ export function Test2() { }); }); + describe("tsserverProjectSystem rename", () => { + it("works with fileToRename", () => { + const aTs: File = { path: "/a.ts", content: "export const a = 0;" }; + const bTs: File = { path: "/b.ts", content: 'import { a } from "./a";' }; + + const session = createSession(createServerHost([aTs, bTs])); + openFilesForSession([bTs], session); + + const response = executeSessionRequest(session, protocol.CommandTypes.Rename, protocolFileLocationFromSubstring(bTs, 'a";')); + assert.deepEqual(response, { + info: { + canRename: true, + fileToRename: aTs.path, + displayName: aTs.path, + fullDisplayName: aTs.path, + kind: ScriptElementKind.moduleElement, + kindModifiers: "", + triggerSpan: protocolTextSpanFromSubstring(bTs.content, "a", { index: 1 }), + }, + locs: [{ file: bTs.path, locs: [protocolRenameSpanFromSubstring(bTs.content, "./a")] }], + }); + }); + + it("works with prefixText and suffixText", () => { + const aTs: File = { path: "/a.ts", content: "const x = 0; const o = { x };" }; + const session = createSession(createServerHost([aTs])); + openFilesForSession([aTs], session); + + const response = executeSessionRequest(session, protocol.CommandTypes.Rename, protocolFileLocationFromSubstring(aTs, "x")); + assert.deepEqual(response, { + info: { + canRename: true, + fileToRename: undefined, + displayName: "x", + fullDisplayName: "x", + kind: ScriptElementKind.constElement, + kindModifiers: ScriptElementKindModifier.none, + triggerSpan: protocolTextSpanFromSubstring(aTs.content, "x"), + }, + locs: [ + { + file: aTs.path, + locs: [ + protocolRenameSpanFromSubstring(aTs.content, "x"), + protocolRenameSpanFromSubstring(aTs.content, "x", { index: 1 }, { prefixText: "x: " }), + ], + }, + ], + }); + }); + }); + describe("tsserverProjectSystem typeReferenceDirectives", () => { it("when typeReferenceDirective contains UpperCasePackage", () => { const projectLocation = "/user/username/projects/myproject"; @@ -9583,7 +9997,7 @@ declare class TestLib { constructor() { var l = new TestLib(); - + } public test2() { @@ -9612,6 +10026,32 @@ declare class TestLib { host.writeFile(appLib.path, appLib.content.replace("test()", "test2()")); host.checkTimeoutQueueLengthAndRun(2); }); + + it("when typeReferenceDirective is relative path and in a sibling folder", () => { + const projectRootPath = "/user/username/projects/browser-addon"; + const projectPath = `${projectRootPath}/background`; + const file: File = { + path: `${projectPath}/a.ts`, + content: "let x = 10;" + }; + const tsconfig: File = { + path: `${projectPath}/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + types: [ + "../typedefs/filesystem" + ] } + }) + }; + const filesystem: File = { + path: `${projectRootPath}/typedefs/filesystem.d.ts`, + content: `interface LocalFileSystem { someProperty: string; }` + }; + const files = [file, tsconfig, filesystem, libFile]; + const host = createServerHost(files); + const service = createProjectService(host); + service.openClientFile(file.path); + }); }); describe("tsserverProjectSystem project references", () => { @@ -9628,7 +10068,7 @@ declare class TestLib { const configContent = JSON.stringify({ compilerOptions }); const aTsconfig: File = { path: "/a/tsconfig.json", content: configContent }; - const aDtsMapContent: SourceMapSection = { + const aDtsMapContent: RawSourceMap = { version: 3, file: "a.d.ts", sourceRoot: "", @@ -9652,7 +10092,7 @@ declare class TestLib { }; const bTsconfig: File = { path: "/b/tsconfig.json", content: configContent }; - const bDtsMapContent: SourceMapSection = { + const bDtsMapContent: RawSourceMap = { version: 3, file: "b.d.ts", sourceRoot: "", @@ -9677,12 +10117,12 @@ declare class TestLib { const userTs: File = { path: "/user/user.ts", - content: 'import { fnA, instanceA } from "../a/bin/a";\nimport { fnB } from "../b/bin/b";\nexport function fnUser() { fnA(); fnB(); instanceA; }', + 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 { fnA, instanceA } from "../a/a";\nimport { fnB } from "../b/b";\nexport function fnUser() { fnA(); fnB(); instanceA; }', + 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 = { @@ -9739,7 +10179,7 @@ declare class TestLib { function verifyATsConfigOriginalProject(session: TestSession) { checkNumberOfProjects(session.getProjectService(), { inferredProjects: 1, configuredProjects: 1 }); verifyInferredProjectUnchanged(session); - verifyATsConfigProject(session); + verifyATsConfigProject(session); // Close user file should close all the projects closeFilesForSession([userTs], session); verifyOnlyOrphanInferredProject(session); @@ -9772,7 +10212,7 @@ declare class TestLib { const session = makeSampleProjects(); const response = executeSessionRequest(session, protocol.CommandTypes.DefinitionAndBoundSpan, protocolFileLocationFromSubstring(userTs, "fnA()")); assert.deepEqual(response, { - textSpan: protocolTextSpanFromSubstring(userTs.content, "fnA", { index: 1 }), + textSpan: protocolTextSpanFromSubstring(userTs.content, "fnA"), definitions: [protocolFileSpanFromSubstring(aTs, "fnA")], }); verifySingleInferredProject(session); @@ -9782,7 +10222,7 @@ declare class TestLib { const session = makeSampleProjects(/*addUserTsConfig*/ true); const response = executeSessionRequest(session, protocol.CommandTypes.DefinitionAndBoundSpan, protocolFileLocationFromSubstring(userTs, "fnA()")); assert.deepEqual(response, { - textSpan: protocolTextSpanFromSubstring(userTs.content, "fnA", { index: 1 }), + textSpan: protocolTextSpanFromSubstring(userTs.content, "fnA"), definitions: [protocolFileSpanFromSubstring(aTs, "fnA")], }); checkNumberOfProjects(session.getProjectService(), { configuredProjects: 1 }); @@ -9836,7 +10276,7 @@ declare class TestLib { kindModifiers: "export,declare", }, { - ...protocolFileSpanFromSubstring(userTs, "export function fnUser() { fnA(); fnB(); instanceA; }"), + ...protocolFileSpanFromSubstring(userTs, "export function fnUser() { a.fnA(); b.fnB(); a.instanceA; }"), name: "fnUser", matchKind: "prefix", isCaseSensitive: true, @@ -9858,8 +10298,7 @@ declare class TestLib { const referenceATs = (aTs: File): protocol.ReferencesResponseItem => makeReferenceItem(aTs, /*isDefinition*/ true, "fnA", "export function fnA() {}"); const referencesUserTs = (userTs: File): ReadonlyArray => [ - makeReferenceItem(userTs, /*isDefinition*/ true, "fnA", "import { fnA, instanceA } from \"../a/bin/a\";"), - makeReferenceItem(userTs, /*isDefinition*/ false, "fnA", "export function fnUser() { fnA(); fnB(); instanceA; }", { index: 1 }), + makeReferenceItem(userTs, /*isDefinition*/ false, "fnA", "export function fnUser() { a.fnA(); b.fnB(); a.instanceA; }"), ]; it("findAllReferences", () => { @@ -9870,7 +10309,7 @@ declare class TestLib { refs: [...referencesUserTs(userTs), referenceATs(aTs)], symbolName: "fnA", symbolStartOffset: protocolLocationFromSubstring(userTs.content, "fnA()").offset, - symbolDisplayString: "(alias) fnA(): void\nimport fnA", + symbolDisplayString: "function fnA(): void", }); verifyATsConfigOriginalProject(session); @@ -9889,50 +10328,15 @@ declare class TestLib { 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(); - interface ReferencesFullRequest extends protocol.FileLocationRequest { command: protocol.CommandTypes.ReferencesFull; } - interface ReferencesFullResponse extends protocol.Response { body: ReadonlyArray; } const responseFull = executeSessionRequest(session, protocol.CommandTypes.ReferencesFull, protocolFileLocationFromSubstring(userTs, "fnA()")); - function fnAVoid(kind: SymbolDisplayPartKind): SymbolDisplayPart[] { - return [ - keywordPart(SyntaxKind.FunctionKeyword), - spacePart(), - displayPart("fnA", kind), - punctuationPart(SyntaxKind.OpenParenToken), - punctuationPart(SyntaxKind.CloseParenToken), - punctuationPart(SyntaxKind.ColonToken), - spacePart(), - keywordPart(SyntaxKind.VoidKeyword), - ]; - } assert.deepEqual>(responseFull, [ - { - definition: { - ...documentSpanFromSubstring(userTs, "fnA"), - kind: ScriptElementKind.alias, - name: "(alias) function fnA(): void\nimport fnA", - containerKind: ScriptElementKind.unknown, - containerName: "", - displayParts: [ - punctuationPart(SyntaxKind.OpenParenToken), - textPart("alias"), - punctuationPart(SyntaxKind.CloseParenToken), - spacePart(), - ...fnAVoid(SymbolDisplayPartKind.aliasName), - lineBreakPart(), - keywordPart(SyntaxKind.ImportKeyword), - spacePart(), - displayPart("fnA", SymbolDisplayPartKind.aliasName), - ], - }, - references: [ - makeReferenceEntry(userTs, /*isDefinition*/ true, "fnA"), - makeReferenceEntry(userTs, /*isDefinition*/ false, "fnA", { index: 1 }), - ], - }, { definition: { ...documentSpanFromSubstring(aTs, "fnA"), @@ -9940,14 +10344,85 @@ declare class TestLib { name: "function fnA(): void", containerKind: ScriptElementKind.unknown, containerName: "", - displayParts: fnAVoid(SymbolDisplayPartKind.functionName), + 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 }, + }, + ], } ]); - verifyATsConfigOriginalProject(session); }); it("findAllReferences -- target does not exist", () => { @@ -9956,27 +10431,23 @@ declare class TestLib { const response = executeSessionRequest(session, protocol.CommandTypes.References, protocolFileLocationFromSubstring(userTs, "fnB()")); assert.deepEqual(response, { refs: [ - makeReferenceItem(userTs, /*isDefinition*/ true, "fnB", "import { fnB } from \"../b/bin/b\";"), - makeReferenceItem(userTs, /*isDefinition*/ false, "fnB", "export function fnUser() { fnA(); fnB(); instanceA; }", { index: 1 }), 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: "(alias) fnB(): void\nimport fnB", + symbolDisplayString: "function fnB(): void", }); verifySingleInferredProject(session); }); const renameATs = (aTs: File): protocol.SpanGroup => ({ file: aTs.path, - locs: [protocolTextSpanFromSubstring(aTs.content, "fnA")], + locs: [protocolRenameSpanFromSubstring(aTs.content, "fnA")], }); const renameUserTs = (userTs: File): protocol.SpanGroup => ({ file: userTs.path, - locs: [ - protocolTextSpanFromSubstring(userTs.content, "fnA"), - protocolTextSpanFromSubstring(userTs.content, "fnA", { index: 1 }), - ], + locs: [protocolRenameSpanFromSubstring(userTs.content, "fnA")], }); it("renameLocations", () => { @@ -9986,10 +10457,11 @@ declare class TestLib { info: { canRename: true, displayName: "fnA", - fullDisplayName: "fnA", - kind: ScriptElementKind.alias, - kindModifiers: ScriptElementKindModifier.none, - localizedErrorMessage: undefined, + 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)], }); @@ -10004,10 +10476,11 @@ declare class TestLib { info: { canRename: true, displayName: "fnA", + fileToRename: undefined, fullDisplayName: '"/a/a".fnA', kind: ScriptElementKind.functionElement, kindModifiers: ScriptElementKindModifier.exportedModifier, - localizedErrorMessage: undefined, + triggerSpan: protocolTextSpanFromSubstring(aTs.content, "fnA"), }, locs: [renameATs(aTs), renameUserTs(userTs)], }); @@ -10018,9 +10491,8 @@ declare class TestLib { const session = makeSampleProjects(); const response = executeSessionRequest(session, protocol.CommandTypes.RenameLocationsFull, protocolFileLocationFromSubstring(userTs, "fnA()")); assert.deepEqual>(response, [ - documentSpanFromSubstring(userTs, "fnA"), - documentSpanFromSubstring(userTs, "fnA", { index: 1 }), - documentSpanFromSubstring(aTs, "fnA"), + renameLocation(userTs, "fnA"), + renameLocation(aTs, "fnA"), ]); verifyATsConfigOriginalProject(session); }); @@ -10032,23 +10504,21 @@ declare class TestLib { info: { canRename: true, displayName: "fnB", - fullDisplayName: "fnB", - kind: ScriptElementKind.alias, - kindModifiers: ScriptElementKindModifier.none, - localizedErrorMessage: undefined, + fileToRename: undefined, + fullDisplayName: '"/b/bin/b".fnB', + kind: ScriptElementKind.functionElement, + kindModifiers: [ScriptElementKindModifier.exportedModifier, ScriptElementKindModifier.ambientModifier].join(","), + triggerSpan: protocolTextSpanFromSubstring(userTs.content, "fnB"), }, locs: [ { - file: userTs.path, - locs: [ - protocolTextSpanFromSubstring(userTs.content, "fnB"), - protocolTextSpanFromSubstring(userTs.content, "fnB", { index: 1 }), - ], + file: bDts.path, + locs: [protocolRenameSpanFromSubstring(bDts.content, "fnB")], }, { - file: bDts.path, - locs: [protocolTextSpanFromSubstring(bDts.content, "fnB")], - } + file: userTs.path, + locs: [protocolRenameSpanFromSubstring(userTs.content, "fnB")], + }, ], }); verifySingleInferredProject(session); @@ -10070,6 +10540,189 @@ declare class TestLib { ]); 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 + }); + }); + + describe("tsserverProjectSystem with tsbuild projects", () => { + 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 } }] } + ]); + }); + }); + + it("can go to definition correctly", () => { + 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 files = [dependencyTs, dependencyConfig, mainTs, mainConfig, libFile]; + const host = createHost(files, [mainConfig.path]); + const session = createSession(host); + const service = session.getProjectService(); + openFilesForSession([mainTs], session); + checkNumberOfProjects(service, { configuredProjects: 1 }); + checkProjectActualFiles(service.configuredProjects.get(mainConfig.path)!, [mainTs.path, libFile.path, mainConfig.path, `${dependecyLocation}/fns.d.ts`]); + for (let i = 0; i < 5; i++) { + const startSpan = { line: i + 5, offset: 1 }; + const response = session.executeCommandSeq({ + command: protocol.CommandTypes.DefinitionAndBoundSpan, + arguments: { file: mainTs.path, ...startSpan } + }).response as protocol.DefinitionInfoAndBoundSpan; + assert.deepEqual(response, { + definitions: [{ file: dependencyTs.path, start: { line: i + 1, offset: 17 }, end: { line: i + 1, offset: 20 } }], + textSpan: { start: startSpan, end: { line: startSpan.line, offset: startSpan.offset + 3 } } + }); + } + }); }); describe("tsserverProjectSystem duplicate packages", () => { @@ -10136,16 +10789,16 @@ declare class TestLib { const untitledFile = "untitled:^Untitled-1"; executeSessionRequestNoResponse(session, protocol.CommandTypes.Open, { file: untitledFile, - fileContent: "let foo = 1;\nfooo/**/", + fileContent: `/// \nlet foo = 1;\nfooo/**/`, scriptKindName: "TS", projectRootPath: "/proj", }); const response = executeSessionRequest(session, protocol.CommandTypes.GetCodeFixes, { file: untitledFile, - startLine: 2, + startLine: 3, startOffset: 1, - endLine: 2, + endLine: 3, endOffset: 5, errorCodes: [Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], }); @@ -10158,8 +10811,8 @@ declare class TestLib { changes: [{ fileName: untitledFile, textChanges: [{ - start: { line: 2, offset: 1 }, - end: { line: 2, offset: 5 }, + start: { line: 3, offset: 1 }, + end: { line: 3, offset: 5 }, newText: "foo", }], }], @@ -10169,6 +10822,133 @@ declare class TestLib { }); }); + describe("tsserverProjectSystem 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, + }, + ]); + }); + }); + + describe("tsserverProjectSystem 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); + }); + }); + }); + function makeReferenceItem(file: File, isDefinition: boolean, text: string, lineText: string, options?: SpanFromSubstringOptions): protocol.ReferencesResponseItem { return { ...protocolFileSpanFromSubstring(file, text, options), diff --git a/src/testRunner/unittests/typingsInstaller.ts b/src/testRunner/unittests/typingsInstaller.ts index a718a12f548..7e0790b7dbb 100644 --- a/src/testRunner/unittests/typingsInstaller.ts +++ b/src/testRunner/unittests/typingsInstaller.ts @@ -310,7 +310,7 @@ namespace ts.projectSystem { constructor() { super(host, { typesRegistry: createTypesRegistry("jquery") }); } - enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray) { + enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray) { enqueueIsCalled = true; super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); } @@ -409,7 +409,7 @@ namespace ts.projectSystem { constructor() { super(host, { typesRegistry: createTypesRegistry("jquery") }); } - enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray) { + enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray) { super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); } installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void { @@ -451,7 +451,7 @@ namespace ts.projectSystem { constructor() { super(host, { typesRegistry: createTypesRegistry("jquery") }); } - enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: server.SortedReadonlyArray) { + enqueueInstallTypingsRequest(project: server.Project, typeAcquisition: TypeAcquisition, unresolvedImports: SortedReadonlyArray) { super.enqueueInstallTypingsRequest(project, typeAcquisition, unresolvedImports); } installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void { @@ -986,6 +986,50 @@ namespace ts.projectSystem { checkProjectActualFiles(service.inferredProjects[0], [file.path, node.path, commander.path]); }); + it("should redo resolution that resolved to '.js' file after typings are installed", () => { + const file: TestFSWithWatch.File = { + path: "/a/b/app.js", + content: ` + import * as commander from "commander";` + }; + const cachePath = "/a/cache"; + const commanderJS: TestFSWithWatch.File = { + path: "/node_modules/commander/index.js", + content: "module.exports = 0", + }; + + const typeNames: ReadonlyArray = ["commander"]; + const typePath = (name: string): string => `${cachePath}/node_modules/@types/${name}/index.d.ts`; + const host = createServerHost([file, commanderJS]); + const installer = new (class extends Installer { + constructor() { + super(host, { globalTypingsCacheLocation: cachePath, typesRegistry: createTypesRegistry(...typeNames) }); + } + installWorker(_requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction) { + const installedTypings = typeNames.map(name => `@types/${name}`); + const typingFiles = typeNames.map((name): TestFSWithWatch.File => ({ path: typePath(name), content: "" })); + executeCommand(this, host, installedTypings, typingFiles, cb); + } + })(); + const service = createProjectService(host, { typingsInstaller: installer }); + service.openClientFile(file.path); + + checkWatchedFiles(host, [...flatMap(["/a/b", "/a", ""], x => [x + "/tsconfig.json", x + "/jsconfig.json"]), "/a/lib/lib.d.ts"]); + checkWatchedDirectories(host, [], /*recursive*/ false); + // Does not include cachePath because that is handled by typingsInstaller + checkWatchedDirectories(host, ["/node_modules", "/a/b/node_modules", "/a/b/node_modules/@types", "/a/b/bower_components"], /*recursive*/ true); + + service.checkNumberOfProjects({ inferredProjects: 1 }); + checkProjectActualFiles(service.inferredProjects[0], [file.path, commanderJS.path]); + + installer.installAll(/*expectedCount*/1); + for (const name of typeNames) { + assert.isTrue(host.fileExists(typePath(name)), `typings for '${name}' should be created`); + } + host.checkTimeoutQueueLengthAndRun(2); + checkProjectActualFiles(service.inferredProjects[0], [file.path, ...typeNames.map(typePath)]); + }); + it("should pick typing names from non-relative unresolved imports", () => { const f1 = { path: "/a/b/app.js", diff --git a/src/tsc/tsc.ts b/src/tsc/tsc.ts index d3966071265..d3a60f58d05 100644 --- a/src/tsc/tsc.ts +++ b/src/tsc/tsc.ts @@ -53,14 +53,10 @@ namespace ts { } export function executeCommandLine(args: string[]): void { - if (args.length > 0 && ((args[0].toLowerCase() === "--build") || (args[0].toLowerCase() === "-b"))) { - const result = performBuild(args.slice(1)); - // undefined = in watch mode, do not exit - if (result !== undefined) { - return sys.exit(result); - } - else { - return; + if (args.length > 0 && args[0].charCodeAt(0) === CharacterCodes.minus) { + const firstOption = args[0].slice(args[0].charCodeAt(1) === CharacterCodes.minus ? 2 : 1).toLowerCase(); + if (firstOption === "build" || firstOption === "b") { + return performBuild(args.slice(1)); } } @@ -136,6 +132,11 @@ namespace ts { const commandLineOptions = commandLine.options; if (configFileName) { const configParseResult = parseConfigFileWithSystem(configFileName, commandLineOptions, sys, reportDiagnostic)!; // TODO: GH#18217 + if (commandLineOptions.showConfig) { + // tslint:disable-next-line:no-null-keyword + sys.write(JSON.stringify(convertToTSConfig(configParseResult, configFileName, sys), null, 4) + sys.newLine); + return sys.exit(ExitStatus.Success); + } updateReportDiagnostic(configParseResult.options); if (isWatchSet(configParseResult.options)) { reportWatchModeWithoutSysSupport(); @@ -146,6 +147,11 @@ namespace ts { } } else { + if (commandLineOptions.showConfig) { + // tslint:disable-next-line:no-null-keyword + sys.write(JSON.stringify(convertToTSConfig(commandLine, combinePaths(sys.getCurrentDirectory(), "tsconfig.json"), sys), null, 4) + sys.newLine); + return sys.exit(ExitStatus.Success); + } updateReportDiagnostic(commandLineOptions); if (isWatchSet(commandLineOptions)) { reportWatchModeWithoutSysSupport(); @@ -164,58 +170,56 @@ namespace ts { } } - function performBuild(args: string[]): number | undefined { - const { buildOptions, projects: buildProjects, errors } = parseBuildCommand(args); + function performBuild(args: string[]) { + const { buildOptions, projects, errors } = parseBuildCommand(args); if (errors.length > 0) { errors.forEach(reportDiagnostic); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (buildOptions.help) { printVersion(); printHelp(buildOpts, "--build "); - return ExitStatus.Success; + return sys.exit(ExitStatus.Success); } // Update to pretty if host supports it updateReportDiagnostic(); - const projects = mapDefined(buildProjects, project => { - const fileName = resolvePath(sys.getCurrentDirectory(), project); - const refPath = resolveProjectReferencePath(sys, { path: fileName }); - if (!sys.fileExists(refPath)) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.File_0_does_not_exist, fileName)); - return undefined; - } - return refPath; - }); - if (projects.length === 0) { printVersion(); printHelp(buildOpts, "--build "); - return ExitStatus.Success; + return sys.exit(ExitStatus.Success); } if (!sys.getModifiedTime || !sys.setModifiedTime || (buildOptions.clean && !sys.deleteFile)) { reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--build")); - return ExitStatus.DiagnosticsPresent_OutputsSkipped; + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (buildOptions.watch) { reportWatchModeWithoutSysSupport(); } // TODO: change this to host if watch => watchHost otherwiue without wathc - const builder = createSolutionBuilder(createSolutionBuilderWithWatchHost(sys, reportDiagnostic, createBuilderStatusReporter(sys, shouldBePretty()), createWatchStatusReporter()), projects, buildOptions); + const builder = createSolutionBuilder(buildOptions.watch ? + createSolutionBuilderWithWatchHost(sys, reportDiagnostic, createBuilderStatusReporter(sys, shouldBePretty()), createWatchStatusReporter()) : + createSolutionBuilderHost(sys, reportDiagnostic, createBuilderStatusReporter(sys, shouldBePretty()), createReportErrorSummary(buildOptions)), + projects, buildOptions); if (buildOptions.clean) { - return builder.cleanAllProjects(); + return sys.exit(builder.cleanAllProjects()); } if (buildOptions.watch) { builder.buildAllProjects(); - builder.startWatching(); - return undefined; + return (builder as SolutionBuilderWithWatch).startWatching(); } - return builder.buildAllProjects(); + return sys.exit(builder.buildAllProjects()); + } + + function createReportErrorSummary(options: CompilerOptions | BuildOptions): ReportEmitErrorSummary | undefined { + return shouldBePretty(options) ? + errorCount => sys.write(getErrorSummaryText(errorCount, sys.newLine)) : + undefined; } function performCompilation(rootNames: string[], projectReferences: ReadonlyArray | undefined, options: CompilerOptions, configFileParsingDiagnostics?: ReadonlyArray) { @@ -230,19 +234,24 @@ namespace ts { configFileParsingDiagnostics }; const program = createProgram(programOptions); - const exitStatus = emitFilesAndReportErrors(program, reportDiagnostic, s => sys.write(s + sys.newLine)); + const exitStatus = emitFilesAndReportErrors( + program, + reportDiagnostic, + s => sys.write(s + sys.newLine), + createReportErrorSummary(options) + ); reportStatistics(program); return sys.exit(exitStatus); } function updateWatchCompilationHost(watchCompilerHost: WatchCompilerHost) { const compileUsingBuilder = watchCompilerHost.createProgram; - watchCompilerHost.createProgram = (rootNames, options, host, oldProgram, configFileParsingDiagnostics) => { + watchCompilerHost.createProgram = (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) => { 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); }; const emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate!; // TODO: GH#18217 watchCompilerHost.afterProgramCreate = builderProgram => { diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index 9c05bf0cf16..8a5c5b50906 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -231,7 +231,8 @@ namespace ts.server { // buffer, but we have yet to find a way to retrieve that value. private static readonly maxActiveRequestCount = 10; private static readonly requestDelayMillis = 100; - private packageInstalledPromise: { resolve(value: ApplyCodeActionCommandResult): void, reject(reason: any): void } | undefined; + private packageInstalledPromise: { resolve(value: ApplyCodeActionCommandResult): void, reject(reason: unknown): void } | undefined; + private inspectValuePromise: { resolve(value: ValueInfo): void } | undefined; constructor( private readonly telemetryEnabled: boolean, @@ -261,14 +262,19 @@ namespace ts.server { } installPackage(options: InstallPackageOptionsWithProject): Promise { - const rq: InstallPackageRequest = { kind: "installPackage", ...options }; - this.send(rq); + this.send({ kind: "installPackage", ...options }); Debug.assert(this.packageInstalledPromise === undefined); - return new Promise((resolve, reject) => { + return new Promise((resolve, reject) => { this.packageInstalledPromise = { resolve, reject }; }); } + inspectValue(options: InspectValueOptions): Promise { + this.send({ kind: "inspectValue", options }); + Debug.assert(this.inspectValuePromise === undefined); + return new Promise(resolve => { this.inspectValuePromise = { resolve }; }); + } + attach(projectService: ProjectService) { this.projectService = projectService; if (this.logger.hasLevel(LogLevel.requestTime)) { @@ -320,7 +326,7 @@ namespace ts.server { this.send({ projectName: p.getProjectName(), kind: "closeProject" }); } - private send(rq: TypingInstallerRequestUnion): void { + private send(rq: T): void { this.installer.send(rq); } @@ -353,7 +359,7 @@ namespace ts.server { } } - private handleMessage(response: TypesRegistryResponse | PackageInstalledResponse | SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | InitializationFailedResponse) { + private handleMessage(response: TypesRegistryResponse | PackageInstalledResponse | InspectValueResponse | SetTypings | InvalidateCachedTypings | BeginInstallTypes | EndInstallTypes | InitializationFailedResponse) { if (this.logger.hasLevel(LogLevel.verbose)) { this.logger.info(`Received response:${stringifyIndented(response)}`); } @@ -378,6 +384,10 @@ namespace ts.server { this.event(response, "setTypings"); break; } + case ActionValueInspected: + this.inspectValuePromise!.resolve(response.result); + this.inspectValuePromise = undefined; + break; case EventInitializationFailed: { const body: protocol.TypesInstallerInitializationFailedEventBody = { @@ -510,6 +520,7 @@ namespace ts.server { globalPlugins, pluginProbeLocations, allowLocalPluginLoads, + typesMapLocation, }); this.eventPort = eventPort; @@ -891,7 +902,7 @@ namespace ts.server { sys.require = (initialDir: string, moduleName: string): RequireResult => { try { - return { module: require(resolveJavascriptModule(moduleName, initialDir, sys)), error: undefined }; + return { module: require(resolveJSModule(moduleName, initialDir, sys)), error: undefined }; } catch (error) { return { module: undefined, error }; diff --git a/src/typingsInstaller/nodeTypingsInstaller.ts b/src/typingsInstaller/nodeTypingsInstaller.ts index d2c7269f9bf..62bdcfce260 100644 --- a/src/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/typingsInstaller/nodeTypingsInstaller.ts @@ -1,5 +1,3 @@ -// tslint:disable no-unnecessary-type-assertion (TODO: tslint can't find node types) - namespace ts.server.typingsInstaller { const fs: { appendFileSync(file: string, content: string): void @@ -12,19 +10,20 @@ namespace ts.server.typingsInstaller { } = require("path"); class FileLog implements Log { - private logEnabled = true; - constructor(private readonly logFile?: string) { + constructor(private logFile: string | undefined) { } isEnabled = () => { - return this.logEnabled && this.logFile !== undefined; + return typeof this.logFile === "string"; } writeLine = (text: string) => { + if (typeof this.logFile !== "string") return; + try { - fs.appendFileSync(this.logFile!, `[${nowString()}] ${text}${sys.newLine}`); // TODO: GH#18217 + fs.appendFileSync(this.logFile, `[${nowString()}] ${text}${sys.newLine}`); } catch (e) { - this.logEnabled = false; + this.logFile = undefined; } } } @@ -164,6 +163,11 @@ namespace ts.server.typingsInstaller { } break; } + case "inspectValue": { + const response: InspectValueResponse = { kind: ActionValueInspected, result: inspectModule(req.options.fileNameToRequire) }; + this.sendResponse(response); + break; + } default: Debug.assertNever(req); } diff --git a/tests/baselines/reference/ES5For-of27.errors.txt b/tests/baselines/reference/ES5For-of27.errors.txt index 0c839859930..837a11cf7ee 100644 --- a/tests/baselines/reference/ES5For-of27.errors.txt +++ b/tests/baselines/reference/ES5For-of27.errors.txt @@ -1,13 +1,13 @@ -tests/cases/conformance/statements/for-ofStatements/ES5For-of27.ts(1,11): error TS2459: Type 'number' has no property 'x' and no string index signature. -tests/cases/conformance/statements/for-ofStatements/ES5For-of27.ts(1,21): error TS2459: Type 'number' has no property 'y' and no string index signature. +tests/cases/conformance/statements/for-ofStatements/ES5For-of27.ts(1,11): error TS2339: Property 'x' does not exist on type 'Number'. +tests/cases/conformance/statements/for-ofStatements/ES5For-of27.ts(1,21): error TS2339: Property 'y' does not exist on type 'Number'. ==== tests/cases/conformance/statements/for-ofStatements/ES5For-of27.ts (2 errors) ==== for (var {x: a = 0, y: b = 1} of [2, 3]) { ~ -!!! error TS2459: Type 'number' has no property 'x' and no string index signature. +!!! error TS2339: Property 'x' does not exist on type 'Number'. ~ -!!! error TS2459: Type 'number' has no property 'y' and no string index signature. +!!! error TS2339: Property 'y' does not exist on type 'Number'. a; b; } \ No newline at end of file diff --git a/tests/baselines/reference/ES5For-of29.errors.txt b/tests/baselines/reference/ES5For-of29.errors.txt index e669b070222..c23ff1af211 100644 --- a/tests/baselines/reference/ES5For-of29.errors.txt +++ b/tests/baselines/reference/ES5For-of29.errors.txt @@ -1,13 +1,13 @@ -tests/cases/conformance/statements/for-ofStatements/ES5For-of29.ts(1,13): error TS2459: Type 'number' has no property 'x' and no string index signature. -tests/cases/conformance/statements/for-ofStatements/ES5For-of29.ts(1,23): error TS2459: Type 'number' has no property 'y' and no string index signature. +tests/cases/conformance/statements/for-ofStatements/ES5For-of29.ts(1,13): error TS2339: Property 'x' does not exist on type 'Number'. +tests/cases/conformance/statements/for-ofStatements/ES5For-of29.ts(1,23): error TS2339: Property 'y' does not exist on type 'Number'. ==== tests/cases/conformance/statements/for-ofStatements/ES5For-of29.ts (2 errors) ==== for (const {x: a = 0, y: b = 1} of [2, 3]) { ~ -!!! error TS2459: Type 'number' has no property 'x' and no string index signature. +!!! error TS2339: Property 'x' does not exist on type 'Number'. ~ -!!! error TS2459: Type 'number' has no property 'y' and no string index signature. +!!! error TS2339: Property 'y' does not exist on type 'Number'. a; b; } \ No newline at end of file diff --git a/tests/baselines/reference/ES5For-of35.errors.txt b/tests/baselines/reference/ES5For-of35.errors.txt index 8c43d959888..c22dc96e42d 100644 --- a/tests/baselines/reference/ES5For-of35.errors.txt +++ b/tests/baselines/reference/ES5For-of35.errors.txt @@ -1,13 +1,13 @@ -tests/cases/conformance/statements/for-ofStatements/ES5For-of35.ts(1,13): error TS2459: Type 'number' has no property 'x' and no string index signature. -tests/cases/conformance/statements/for-ofStatements/ES5For-of35.ts(1,23): error TS2459: Type 'number' has no property 'y' and no string index signature. +tests/cases/conformance/statements/for-ofStatements/ES5For-of35.ts(1,13): error TS2339: Property 'x' does not exist on type 'Number'. +tests/cases/conformance/statements/for-ofStatements/ES5For-of35.ts(1,23): error TS2339: Property 'y' does not exist on type 'Number'. ==== tests/cases/conformance/statements/for-ofStatements/ES5For-of35.ts (2 errors) ==== for (const {x: a = 0, y: b = 1} of [2, 3]) { ~ -!!! error TS2459: Type 'number' has no property 'x' and no string index signature. +!!! error TS2339: Property 'x' does not exist on type 'Number'. ~ -!!! error TS2459: Type 'number' has no property 'y' and no string index signature. +!!! error TS2339: Property 'y' does not exist on type 'Number'. a; b; } \ No newline at end of file diff --git a/tests/baselines/reference/ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js b/tests/baselines/reference/ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js index e609e3d1e6c..9074e2ad4c8 100644 --- a/tests/baselines/reference/ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js +++ b/tests/baselines/reference/ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js @@ -27,7 +27,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; } diff --git a/tests/baselines/reference/ExportClassWithInaccessibleTypeInTypeParameterConstraint.js b/tests/baselines/reference/ExportClassWithInaccessibleTypeInTypeParameterConstraint.js index 29416ab80b3..7ffab769794 100644 --- a/tests/baselines/reference/ExportClassWithInaccessibleTypeInTypeParameterConstraint.js +++ b/tests/baselines/reference/ExportClassWithInaccessibleTypeInTypeParameterConstraint.js @@ -31,7 +31,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; } diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json index c694d240371..73f9fb3b8b0 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.@link tags.json @@ -7,11 +7,6 @@ "kind": "JSDocTag", "pos": 63, "end": 68, - "atToken": { - "kind": "AtToken", - "pos": 63, - "end": 64 - }, "tagName": { "kind": "Identifier", "pos": 64, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json index f75d1e5fc6b..10ae7a71097 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.Nested @param tags.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 6, "end": 64, - "atToken": { - "kind": "AtToken", - "pos": 6, - "end": 7 - }, "tagName": { "kind": "Identifier", "pos": 7, @@ -31,11 +26,6 @@ "kind": "JSDocParameterTag", "pos": 34, "end": 64, - "atToken": { - "kind": "AtToken", - "pos": 34, - "end": 35 - }, "tagName": { "kind": "Identifier", "pos": 35, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json index cde6addda7c..6859d67c4c2 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argSynonymForParamTag.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 42, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json index f193bc3fe9e..16874177ac9 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.argumentSynonymForParamTag.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 47, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json index a21f9f81c44..9da2d2f2646 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.leadingAsterisk.json @@ -7,11 +7,6 @@ "kind": "JSDocTypeTag", "pos": 8, "end": 22, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.less-than and greater-than characters.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.less-than and greater-than characters.json index 37d4610f987..3e5137d7b4d 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.less-than and greater-than characters.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.less-than and greater-than characters.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 7, "end": 59, - "atToken": { - "kind": "AtToken", - "pos": 7, - "end": 8 - }, "tagName": { "kind": "Identifier", "pos": 8, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json index a21f9f81c44..9da2d2f2646 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noLeadingAsterisk.json @@ -7,11 +7,6 @@ "kind": "JSDocTypeTag", "pos": 8, "end": 22, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json index 204ba39d3dd..92bce57f68c 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noReturnType.json @@ -7,11 +7,6 @@ "kind": "JSDocReturnTag", "pos": 8, "end": 15, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noType.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noType.json deleted file mode 100644 index 06e50488025..00000000000 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.noType.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "kind": "JSDocComment", - "pos": 0, - "end": 18, - "tags": { - "0": { - "kind": "JSDocTypeTag", - "pos": 8, - "end": 14, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, - "tagName": { - "kind": "Identifier", - "pos": 9, - "end": 13, - "escapedText": "type" - }, - "comment": "" - }, - "length": 1, - "pos": 8, - "end": 14 - } -} \ No newline at end of file diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.oneParamTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.oneParamTag.json index f5eee243cf5..be925823222 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.oneParamTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.oneParamTag.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 32, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTag1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTag1.json index cbbb64b5a73..8383a0401dd 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTag1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTag1.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 57, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName1.json index a27e0d158e2..98ea87a26bd 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName1.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 59, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName2.json index d271a3b3483..e381cf9329b 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagBracketedName2.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 64, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType1.json index 7a1c85b25d6..7af573ee0b3 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType1.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 29, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType2.json index 57ab44a68b7..ca20f10e0d3 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramTagNameThenType2.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 44, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramWithoutType.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramWithoutType.json index e85d787cd99..a8fb42ee2ca 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramWithoutType.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.paramWithoutType.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 21, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json index e02a0a38bb4..ab1bbd97998 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag1.json @@ -7,11 +7,6 @@ "kind": "JSDocReturnTag", "pos": 8, "end": 24, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json index fdc4d523104..7df8cea13ea 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnTag2.json @@ -7,11 +7,6 @@ "kind": "JSDocReturnTag", "pos": 8, "end": 24, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json index 70497ee8c1b..17a823c4283 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.returnsTag1.json @@ -7,11 +7,6 @@ "kind": "JSDocReturnTag", "pos": 8, "end": 25, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json index 4d16157d91d..bf15a478146 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag.json @@ -7,11 +7,6 @@ "kind": "JSDocTemplateTag", "pos": 8, "end": 19, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json index 3f5f2a54ec7..2b635be0577 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag2.json @@ -7,11 +7,6 @@ "kind": "JSDocTemplateTag", "pos": 8, "end": 21, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json index 193c5c0eb01..5a9127ccfdf 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag3.json @@ -7,11 +7,6 @@ "kind": "JSDocTemplateTag", "pos": 8, "end": 22, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json index 193c5c0eb01..5a9127ccfdf 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag4.json @@ -7,11 +7,6 @@ "kind": "JSDocTemplateTag", "pos": 8, "end": 22, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json index fca64bcb430..eec9555c363 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag5.json @@ -7,11 +7,6 @@ "kind": "JSDocTemplateTag", "pos": 8, "end": 23, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json index 90158499b17..778af6902a9 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.templateTag6.json @@ -7,11 +7,6 @@ "kind": "JSDocTemplateTag", "pos": 8, "end": 24, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTag2.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTag2.json index 3a5e71ef8b1..38997b2e70f 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTag2.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTag2.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 34, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, @@ -41,11 +36,6 @@ "kind": "JSDocParameterTag", "pos": 34, "end": 58, - "atToken": { - "kind": "AtToken", - "pos": 34, - "end": 35 - }, "tagName": { "kind": "Identifier", "pos": 35, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTagOnSameLine.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTagOnSameLine.json index 51868df260b..f74d57ad4d6 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTagOnSameLine.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.twoParamTagOnSameLine.json @@ -7,11 +7,6 @@ "kind": "JSDocParameterTag", "pos": 8, "end": 30, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, @@ -41,11 +36,6 @@ "kind": "JSDocParameterTag", "pos": 30, "end": 54, - "atToken": { - "kind": "AtToken", - "pos": 30, - "end": 31 - }, "tagName": { "kind": "Identifier", "pos": 31, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json index a21f9f81c44..9da2d2f2646 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typeTag.json @@ -7,11 +7,6 @@ "kind": "JSDocTypeTag", "pos": 8, "end": 22, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json index 7b3050cffa2..dcc611bff2d 100644 --- a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.typedefTagWithChildrenTags.json @@ -7,11 +7,6 @@ "kind": "JSDocTypedefTag", "pos": 8, "end": 100, - "atToken": { - "kind": "AtToken", - "pos": 8, - "end": 9 - }, "tagName": { "kind": "Identifier", "pos": 9, @@ -39,11 +34,6 @@ "kind": "JSDocPropertyTag", "pos": 47, "end": 74, - "atToken": { - "kind": "AtToken", - "pos": 47, - "end": 48 - }, "tagName": { "kind": "Identifier", "pos": 48, @@ -73,11 +63,6 @@ "kind": "JSDocPropertyTag", "pos": 74, "end": 100, - "atToken": { - "kind": "AtToken", - "pos": 74, - "end": 75 - }, "tagName": { "kind": "Identifier", "pos": 75, diff --git a/tests/baselines/reference/TypeGuardWithEnumUnion.types b/tests/baselines/reference/TypeGuardWithEnumUnion.types index 9f51791f209..a568034f8b8 100644 --- a/tests/baselines/reference/TypeGuardWithEnumUnion.types +++ b/tests/baselines/reference/TypeGuardWithEnumUnion.types @@ -11,7 +11,7 @@ function f1(x: Color | string) { if (typeof x === "number") { >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | Color >"number" : "number" @@ -38,7 +38,7 @@ function f2(x: Color | string | string[]) { if (typeof x === "object") { >typeof x === "object" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | Color | string[] >"object" : "object" @@ -51,7 +51,7 @@ function f2(x: Color | string | string[]) { } if (typeof x === "number") { >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | Color | string[] >"number" : "number" @@ -72,7 +72,7 @@ function f2(x: Color | string | string[]) { } if (typeof x === "string") { >typeof x === "string" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : string | Color | string[] >"string" : "string" diff --git a/tests/baselines/reference/YieldStarExpression1_es6.errors.txt b/tests/baselines/reference/YieldStarExpression1_es6.errors.txt index 9ba5e44f9aa..265013d6bad 100644 --- a/tests/baselines/reference/YieldStarExpression1_es6.errors.txt +++ b/tests/baselines/reference/YieldStarExpression1_es6.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/es6/yieldExpressions/YieldStarExpression1_es6.ts(1,1): error TS2304: Cannot find name 'yield'. -tests/cases/conformance/es6/yieldExpressions/YieldStarExpression1_es6.ts(1,9): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/es6/yieldExpressions/YieldStarExpression1_es6.ts(1,9): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/es6/yieldExpressions/YieldStarExpression1_es6.ts (2 errors) ==== @@ -7,4 +7,4 @@ tests/cases/conformance/es6/yieldExpressions/YieldStarExpression1_es6.ts(1,9): e ~~~~~ !!! error TS2304: Cannot find name 'yield'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/abstractClassInLocalScope.js b/tests/baselines/reference/abstractClassInLocalScope.js index afcefadb705..4e7b9f87095 100644 --- a/tests/baselines/reference/abstractClassInLocalScope.js +++ b/tests/baselines/reference/abstractClassInLocalScope.js @@ -14,7 +14,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; } diff --git a/tests/baselines/reference/abstractClassInLocalScopeIsAbstract.js b/tests/baselines/reference/abstractClassInLocalScopeIsAbstract.js index ec27e0d91fd..60af14e625b 100644 --- a/tests/baselines/reference/abstractClassInLocalScopeIsAbstract.js +++ b/tests/baselines/reference/abstractClassInLocalScopeIsAbstract.js @@ -14,7 +14,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; } diff --git a/tests/baselines/reference/abstractProperty.js b/tests/baselines/reference/abstractProperty.js index ca9bf0c3742..a7d63d55452 100644 --- a/tests/baselines/reference/abstractProperty.js +++ b/tests/baselines/reference/abstractProperty.js @@ -28,7 +28,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; } diff --git a/tests/baselines/reference/abstractPropertyInConstructor.errors.txt b/tests/baselines/reference/abstractPropertyInConstructor.errors.txt index 5337bfc538a..869ec3b1e65 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.errors.txt +++ b/tests/baselines/reference/abstractPropertyInConstructor.errors.txt @@ -2,9 +2,10 @@ tests/cases/compiler/abstractPropertyInConstructor.ts(4,24): error TS2715: Abstr tests/cases/compiler/abstractPropertyInConstructor.ts(7,18): error TS2715: Abstract property 'prop' in class 'AbstractClass' cannot be accessed in the constructor. tests/cases/compiler/abstractPropertyInConstructor.ts(9,14): error TS2715: Abstract property 'cb' in class 'AbstractClass' cannot be accessed in the constructor. tests/cases/compiler/abstractPropertyInConstructor.ts(25,18): error TS2715: Abstract property 'prop' in class 'AbstractClass' cannot be accessed in the constructor. +tests/cases/compiler/abstractPropertyInConstructor.ts(39,22): error TS2715: Abstract property 'prop' in class 'AbstractClass' cannot be accessed in the constructor. -==== tests/cases/compiler/abstractPropertyInConstructor.ts (4 errors) ==== +==== tests/cases/compiler/abstractPropertyInConstructor.ts (5 errors) ==== abstract class AbstractClass { constructor(str: string, other: AbstractClass) { this.method(parseInt(str)); @@ -45,6 +46,38 @@ tests/cases/compiler/abstractPropertyInConstructor.ts(25,18): error TS2715: Abst } } + abstract class DerivedAbstractClass extends AbstractClass { + cb = (s: string) => {}; + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { + super(str, other); + // there is no implementation of 'prop' in any base class + this.cb(this.prop.toLowerCase()); + ~~~~ +!!! error TS2715: Abstract property 'prop' in class 'AbstractClass' cannot be accessed in the constructor. + + this.method(1); + + // OK, references are to another instance + other.cb(other.prop); + yetAnother.cb(yetAnother.prop); + } + } + + class Implementation extends DerivedAbstractClass { + prop = ""; + cb = (s: string) => {}; + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { + super(str, other, yetAnother); + this.cb(this.prop); + } + + method(n: number) { + this.cb(this.prop + n); + } + } + class User { constructor(a: AbstractClass) { a.prop; diff --git a/tests/baselines/reference/abstractPropertyInConstructor.js b/tests/baselines/reference/abstractPropertyInConstructor.js index 782419ac67b..ab830664d51 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.js +++ b/tests/baselines/reference/abstractPropertyInConstructor.js @@ -31,6 +31,36 @@ abstract class AbstractClass { } } +abstract class DerivedAbstractClass extends AbstractClass { + cb = (s: string) => {}; + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { + super(str, other); + // there is no implementation of 'prop' in any base class + this.cb(this.prop.toLowerCase()); + + this.method(1); + + // OK, references are to another instance + other.cb(other.prop); + yetAnother.cb(yetAnother.prop); + } +} + +class Implementation extends DerivedAbstractClass { + prop = ""; + cb = (s: string) => {}; + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { + super(str, other, yetAnother); + this.cb(this.prop); + } + + method(n: number) { + this.cb(this.prop + n); + } +} + class User { constructor(a: AbstractClass) { a.prop; @@ -42,6 +72,19 @@ class User { //// [abstractPropertyInConstructor.js] +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return 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 AbstractClass = /** @class */ (function () { function AbstractClass(str, other) { var _this = this; @@ -65,6 +108,35 @@ var AbstractClass = /** @class */ (function () { }; return AbstractClass; }()); +var DerivedAbstractClass = /** @class */ (function (_super) { + __extends(DerivedAbstractClass, _super); + function DerivedAbstractClass(str, other, yetAnother) { + var _this = _super.call(this, str, other) || this; + _this.cb = function (s) { }; + // there is no implementation of 'prop' in any base class + _this.cb(_this.prop.toLowerCase()); + _this.method(1); + // OK, references are to another instance + other.cb(other.prop); + yetAnother.cb(yetAnother.prop); + return _this; + } + return DerivedAbstractClass; +}(AbstractClass)); +var Implementation = /** @class */ (function (_super) { + __extends(Implementation, _super); + function Implementation(str, other, yetAnother) { + var _this = _super.call(this, str, other, yetAnother) || this; + _this.prop = ""; + _this.cb = function (s) { }; + _this.cb(_this.prop); + return _this; + } + Implementation.prototype.method = function (n) { + this.cb(this.prop + n); + }; + return Implementation; +}(DerivedAbstractClass)); var User = /** @class */ (function () { function User(a) { a.prop; diff --git a/tests/baselines/reference/abstractPropertyInConstructor.symbols b/tests/baselines/reference/abstractPropertyInConstructor.symbols index 71f897118c8..628ee5c8576 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.symbols +++ b/tests/baselines/reference/abstractPropertyInConstructor.symbols @@ -92,31 +92,134 @@ abstract class AbstractClass { } } +abstract class DerivedAbstractClass extends AbstractClass { +>DerivedAbstractClass : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) +>AbstractClass : Symbol(AbstractClass, Decl(abstractPropertyInConstructor.ts, 0, 0)) + + cb = (s: string) => {}; +>cb : Symbol(DerivedAbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 32, 59)) +>s : Symbol(s, Decl(abstractPropertyInConstructor.ts, 33, 10)) + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { +>str : Symbol(str, Decl(abstractPropertyInConstructor.ts, 35, 16)) +>other : Symbol(other, Decl(abstractPropertyInConstructor.ts, 35, 28)) +>AbstractClass : Symbol(AbstractClass, Decl(abstractPropertyInConstructor.ts, 0, 0)) +>yetAnother : Symbol(yetAnother, Decl(abstractPropertyInConstructor.ts, 35, 50)) +>DerivedAbstractClass : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) + + super(str, other); +>super : Symbol(AbstractClass, Decl(abstractPropertyInConstructor.ts, 0, 0)) +>str : Symbol(str, Decl(abstractPropertyInConstructor.ts, 35, 16)) +>other : Symbol(other, Decl(abstractPropertyInConstructor.ts, 35, 28)) + + // there is no implementation of 'prop' in any base class + this.cb(this.prop.toLowerCase()); +>this.cb : Symbol(DerivedAbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 32, 59)) +>this : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) +>cb : Symbol(DerivedAbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 32, 59)) +>this.prop.toLowerCase : Symbol(String.toLowerCase, Decl(lib.es5.d.ts, --, --)) +>this.prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) +>this : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) +>prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) +>toLowerCase : Symbol(String.toLowerCase, Decl(lib.es5.d.ts, --, --)) + + this.method(1); +>this.method : Symbol(AbstractClass.method, Decl(abstractPropertyInConstructor.ts, 20, 37)) +>this : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) +>method : Symbol(AbstractClass.method, Decl(abstractPropertyInConstructor.ts, 20, 37)) + + // OK, references are to another instance + other.cb(other.prop); +>other.cb : Symbol(AbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 19, 26)) +>other : Symbol(other, Decl(abstractPropertyInConstructor.ts, 35, 28)) +>cb : Symbol(AbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 19, 26)) +>other.prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) +>other : Symbol(other, Decl(abstractPropertyInConstructor.ts, 35, 28)) +>prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) + + yetAnother.cb(yetAnother.prop); +>yetAnother.cb : Symbol(DerivedAbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 32, 59)) +>yetAnother : Symbol(yetAnother, Decl(abstractPropertyInConstructor.ts, 35, 50)) +>cb : Symbol(DerivedAbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 32, 59)) +>yetAnother.prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) +>yetAnother : Symbol(yetAnother, Decl(abstractPropertyInConstructor.ts, 35, 50)) +>prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) + } +} + +class Implementation extends DerivedAbstractClass { +>Implementation : Symbol(Implementation, Decl(abstractPropertyInConstructor.ts, 46, 1)) +>DerivedAbstractClass : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) + + prop = ""; +>prop : Symbol(Implementation.prop, Decl(abstractPropertyInConstructor.ts, 48, 51)) + + cb = (s: string) => {}; +>cb : Symbol(Implementation.cb, Decl(abstractPropertyInConstructor.ts, 49, 14)) +>s : Symbol(s, Decl(abstractPropertyInConstructor.ts, 50, 10)) + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { +>str : Symbol(str, Decl(abstractPropertyInConstructor.ts, 52, 16)) +>other : Symbol(other, Decl(abstractPropertyInConstructor.ts, 52, 28)) +>AbstractClass : Symbol(AbstractClass, Decl(abstractPropertyInConstructor.ts, 0, 0)) +>yetAnother : Symbol(yetAnother, Decl(abstractPropertyInConstructor.ts, 52, 50)) +>DerivedAbstractClass : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) + + super(str, other, yetAnother); +>super : Symbol(DerivedAbstractClass, Decl(abstractPropertyInConstructor.ts, 30, 1)) +>str : Symbol(str, Decl(abstractPropertyInConstructor.ts, 52, 16)) +>other : Symbol(other, Decl(abstractPropertyInConstructor.ts, 52, 28)) +>yetAnother : Symbol(yetAnother, Decl(abstractPropertyInConstructor.ts, 52, 50)) + + this.cb(this.prop); +>this.cb : Symbol(Implementation.cb, Decl(abstractPropertyInConstructor.ts, 49, 14)) +>this : Symbol(Implementation, Decl(abstractPropertyInConstructor.ts, 46, 1)) +>cb : Symbol(Implementation.cb, Decl(abstractPropertyInConstructor.ts, 49, 14)) +>this.prop : Symbol(Implementation.prop, Decl(abstractPropertyInConstructor.ts, 48, 51)) +>this : Symbol(Implementation, Decl(abstractPropertyInConstructor.ts, 46, 1)) +>prop : Symbol(Implementation.prop, Decl(abstractPropertyInConstructor.ts, 48, 51)) + } + + method(n: number) { +>method : Symbol(Implementation.method, Decl(abstractPropertyInConstructor.ts, 55, 5)) +>n : Symbol(n, Decl(abstractPropertyInConstructor.ts, 57, 11)) + + this.cb(this.prop + n); +>this.cb : Symbol(Implementation.cb, Decl(abstractPropertyInConstructor.ts, 49, 14)) +>this : Symbol(Implementation, Decl(abstractPropertyInConstructor.ts, 46, 1)) +>cb : Symbol(Implementation.cb, Decl(abstractPropertyInConstructor.ts, 49, 14)) +>this.prop : Symbol(Implementation.prop, Decl(abstractPropertyInConstructor.ts, 48, 51)) +>this : Symbol(Implementation, Decl(abstractPropertyInConstructor.ts, 46, 1)) +>prop : Symbol(Implementation.prop, Decl(abstractPropertyInConstructor.ts, 48, 51)) +>n : Symbol(n, Decl(abstractPropertyInConstructor.ts, 57, 11)) + } +} + class User { ->User : Symbol(User, Decl(abstractPropertyInConstructor.ts, 30, 1)) +>User : Symbol(User, Decl(abstractPropertyInConstructor.ts, 60, 1)) constructor(a: AbstractClass) { ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 63, 16)) >AbstractClass : Symbol(AbstractClass, Decl(abstractPropertyInConstructor.ts, 0, 0)) a.prop; >a.prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 63, 16)) >prop : Symbol(AbstractClass.prop, Decl(abstractPropertyInConstructor.ts, 17, 5)) a.cb("hi"); >a.cb : Symbol(AbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 19, 26)) ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 63, 16)) >cb : Symbol(AbstractClass.cb, Decl(abstractPropertyInConstructor.ts, 19, 26)) a.method(12); >a.method : Symbol(AbstractClass.method, Decl(abstractPropertyInConstructor.ts, 20, 37)) ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 63, 16)) >method : Symbol(AbstractClass.method, Decl(abstractPropertyInConstructor.ts, 20, 37)) a.method2(); >a.method2 : Symbol(AbstractClass.method2, Decl(abstractPropertyInConstructor.ts, 25, 25)) ->a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 33, 16)) +>a : Symbol(a, Decl(abstractPropertyInConstructor.ts, 63, 16)) >method2 : Symbol(AbstractClass.method2, Decl(abstractPropertyInConstructor.ts, 25, 25)) } } diff --git a/tests/baselines/reference/abstractPropertyInConstructor.types b/tests/baselines/reference/abstractPropertyInConstructor.types index 465e0fb2f04..8c8bd40aff0 100644 --- a/tests/baselines/reference/abstractPropertyInConstructor.types +++ b/tests/baselines/reference/abstractPropertyInConstructor.types @@ -104,6 +104,119 @@ abstract class AbstractClass { } } +abstract class DerivedAbstractClass extends AbstractClass { +>DerivedAbstractClass : DerivedAbstractClass +>AbstractClass : AbstractClass + + cb = (s: string) => {}; +>cb : (s: string) => void +>(s: string) => {} : (s: string) => void +>s : string + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { +>str : string +>other : AbstractClass +>yetAnother : DerivedAbstractClass + + super(str, other); +>super(str, other) : void +>super : typeof AbstractClass +>str : string +>other : AbstractClass + + // there is no implementation of 'prop' in any base class + this.cb(this.prop.toLowerCase()); +>this.cb(this.prop.toLowerCase()) : void +>this.cb : (s: string) => void +>this : this +>cb : (s: string) => void +>this.prop.toLowerCase() : string +>this.prop.toLowerCase : () => string +>this.prop : string +>this : this +>prop : string +>toLowerCase : () => string + + this.method(1); +>this.method(1) : void +>this.method : (num: number) => void +>this : this +>method : (num: number) => void +>1 : 1 + + // OK, references are to another instance + other.cb(other.prop); +>other.cb(other.prop) : void +>other.cb : (s: string) => void +>other : AbstractClass +>cb : (s: string) => void +>other.prop : string +>other : AbstractClass +>prop : string + + yetAnother.cb(yetAnother.prop); +>yetAnother.cb(yetAnother.prop) : void +>yetAnother.cb : (s: string) => void +>yetAnother : DerivedAbstractClass +>cb : (s: string) => void +>yetAnother.prop : string +>yetAnother : DerivedAbstractClass +>prop : string + } +} + +class Implementation extends DerivedAbstractClass { +>Implementation : Implementation +>DerivedAbstractClass : DerivedAbstractClass + + prop = ""; +>prop : string +>"" : "" + + cb = (s: string) => {}; +>cb : (s: string) => void +>(s: string) => {} : (s: string) => void +>s : string + + constructor(str: string, other: AbstractClass, yetAnother: DerivedAbstractClass) { +>str : string +>other : AbstractClass +>yetAnother : DerivedAbstractClass + + super(str, other, yetAnother); +>super(str, other, yetAnother) : void +>super : typeof DerivedAbstractClass +>str : string +>other : AbstractClass +>yetAnother : DerivedAbstractClass + + this.cb(this.prop); +>this.cb(this.prop) : void +>this.cb : (s: string) => void +>this : this +>cb : (s: string) => void +>this.prop : string +>this : this +>prop : string + } + + method(n: number) { +>method : (n: number) => void +>n : number + + this.cb(this.prop + n); +>this.cb(this.prop + n) : void +>this.cb : (s: string) => void +>this : this +>cb : (s: string) => void +>this.prop + n : string +>this.prop : string +>this : this +>prop : string +>n : number + } +} + class User { >User : User diff --git a/tests/baselines/reference/abstractPropertyNegative.errors.txt b/tests/baselines/reference/abstractPropertyNegative.errors.txt index be1c85374fb..fd09b024213 100644 --- a/tests/baselines/reference/abstractPropertyNegative.errors.txt +++ b/tests/baselines/reference/abstractPropertyNegative.errors.txt @@ -6,7 +6,7 @@ tests/cases/compiler/abstractPropertyNegative.ts(13,7): error TS2515: Non-abstra tests/cases/compiler/abstractPropertyNegative.ts(13,7): error TS2515: Non-abstract class 'C' does not implement inherited abstract member 'readonlyProp' from class 'B'. tests/cases/compiler/abstractPropertyNegative.ts(15,5): error TS1244: Abstract methods can only appear within an abstract class. tests/cases/compiler/abstractPropertyNegative.ts(16,37): error TS1005: '{' expected. -tests/cases/compiler/abstractPropertyNegative.ts(19,3): error TS2540: Cannot assign to 'ro' because it is a constant or a read-only property. +tests/cases/compiler/abstractPropertyNegative.ts(19,3): error TS2540: Cannot assign to 'ro' because it is a read-only property. tests/cases/compiler/abstractPropertyNegative.ts(25,5): error TS2416: Property 'num' in type 'WrongTypePropertyImpl' is not assignable to the same property in base type 'WrongTypeProperty'. Type 'string' is not assignable to type 'number'. tests/cases/compiler/abstractPropertyNegative.ts(31,9): error TS2416: Property 'num' in type 'WrongTypeAccessorImpl' is not assignable to the same property in base type 'WrongTypeAccessor'. @@ -56,7 +56,7 @@ tests/cases/compiler/abstractPropertyNegative.ts(41,18): error TS2676: Accessors let c = new C(); c.ro = "error: lhs of assignment can't be readonly"; ~~ -!!! error TS2540: Cannot assign to 'ro' because it is a constant or a read-only property. +!!! error TS2540: Cannot assign to 'ro' because it is a read-only property. abstract class WrongTypeProperty { abstract num: number; diff --git a/tests/baselines/reference/abstractPropertyNegative.js b/tests/baselines/reference/abstractPropertyNegative.js index 4db1f89ff0d..df07c9f7a3e 100644 --- a/tests/baselines/reference/abstractPropertyNegative.js +++ b/tests/baselines/reference/abstractPropertyNegative.js @@ -50,7 +50,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; } diff --git a/tests/baselines/reference/accessOverriddenBaseClassMember1.js b/tests/baselines/reference/accessOverriddenBaseClassMember1.js index 3f290cc5369..6512ba01d67 100644 --- a/tests/baselines/reference/accessOverriddenBaseClassMember1.js +++ b/tests/baselines/reference/accessOverriddenBaseClassMember1.js @@ -22,7 +22,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; } diff --git a/tests/baselines/reference/accessors_spec_section-4.5_inference.js b/tests/baselines/reference/accessors_spec_section-4.5_inference.js index 5ba098f7c2d..9be63d5e41a 100644 --- a/tests/baselines/reference/accessors_spec_section-4.5_inference.js +++ b/tests/baselines/reference/accessors_spec_section-4.5_inference.js @@ -31,7 +31,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; } diff --git a/tests/baselines/reference/aliasDoesNotDuplicateSignatures.symbols b/tests/baselines/reference/aliasDoesNotDuplicateSignatures.symbols index 21ae7940f96..912798f4a1b 100644 --- a/tests/baselines/reference/aliasDoesNotDuplicateSignatures.symbols +++ b/tests/baselines/reference/aliasDoesNotDuplicateSignatures.symbols @@ -6,7 +6,7 @@ declare namespace demoNS { >f : Symbol(f, Decl(demo.d.ts, 0, 26)) } declare module 'demoModule' { ->'demoModule' : Symbol('demoModule', Decl(demo.d.ts, 2, 1)) +>'demoModule' : Symbol("demoModule", Decl(demo.d.ts, 2, 1)) import alias = demoNS; >alias : Symbol(alias, Decl(demo.d.ts, 3, 29)) diff --git a/tests/baselines/reference/aliasUsageInAccessorsOfClass.js b/tests/baselines/reference/aliasUsageInAccessorsOfClass.js index 34d2bf2ff49..107466601d3 100644 --- a/tests/baselines/reference/aliasUsageInAccessorsOfClass.js +++ b/tests/baselines/reference/aliasUsageInAccessorsOfClass.js @@ -44,7 +44,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; } diff --git a/tests/baselines/reference/aliasUsageInArray.js b/tests/baselines/reference/aliasUsageInArray.js index 38535edd441..4282290a392 100644 --- a/tests/baselines/reference/aliasUsageInArray.js +++ b/tests/baselines/reference/aliasUsageInArray.js @@ -38,7 +38,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; } diff --git a/tests/baselines/reference/aliasUsageInFunctionExpression.js b/tests/baselines/reference/aliasUsageInFunctionExpression.js index e573e530123..18ec4ed2c0a 100644 --- a/tests/baselines/reference/aliasUsageInFunctionExpression.js +++ b/tests/baselines/reference/aliasUsageInFunctionExpression.js @@ -37,7 +37,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; } diff --git a/tests/baselines/reference/aliasUsageInGenericFunction.js b/tests/baselines/reference/aliasUsageInGenericFunction.js index db3a85835c5..9ec03624f1a 100644 --- a/tests/baselines/reference/aliasUsageInGenericFunction.js +++ b/tests/baselines/reference/aliasUsageInGenericFunction.js @@ -41,7 +41,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; } diff --git a/tests/baselines/reference/aliasUsageInIndexerOfClass.js b/tests/baselines/reference/aliasUsageInIndexerOfClass.js index 282db192221..beb62454069 100644 --- a/tests/baselines/reference/aliasUsageInIndexerOfClass.js +++ b/tests/baselines/reference/aliasUsageInIndexerOfClass.js @@ -43,7 +43,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; } diff --git a/tests/baselines/reference/aliasUsageInObjectLiteral.js b/tests/baselines/reference/aliasUsageInObjectLiteral.js index 1c794441f5c..aa70bdd700a 100644 --- a/tests/baselines/reference/aliasUsageInObjectLiteral.js +++ b/tests/baselines/reference/aliasUsageInObjectLiteral.js @@ -38,7 +38,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; } diff --git a/tests/baselines/reference/aliasUsageInOrExpression.js b/tests/baselines/reference/aliasUsageInOrExpression.js index 75bc90302c5..e0969ae9901 100644 --- a/tests/baselines/reference/aliasUsageInOrExpression.js +++ b/tests/baselines/reference/aliasUsageInOrExpression.js @@ -41,7 +41,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; } diff --git a/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.js b/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.js index 1faf2b813f3..8b6485aa2c4 100644 --- a/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.js +++ b/tests/baselines/reference/aliasUsageInTypeArgumentOfExtendsClause.js @@ -41,7 +41,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; } @@ -66,7 +66,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; } diff --git a/tests/baselines/reference/aliasUsageInVarAssignment.js b/tests/baselines/reference/aliasUsageInVarAssignment.js index bf7871a27ac..e51718537f4 100644 --- a/tests/baselines/reference/aliasUsageInVarAssignment.js +++ b/tests/baselines/reference/aliasUsageInVarAssignment.js @@ -37,7 +37,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; } diff --git a/tests/baselines/reference/allowImportClausesToMergeWithTypes.symbols b/tests/baselines/reference/allowImportClausesToMergeWithTypes.symbols index 2195912a395..a87db081e1d 100644 --- a/tests/baselines/reference/allowImportClausesToMergeWithTypes.symbols +++ b/tests/baselines/reference/allowImportClausesToMergeWithTypes.symbols @@ -25,7 +25,7 @@ zzz; >zzz : Symbol(zzz, Decl(a.ts, 0, 0), Decl(a.ts, 4, 6)) export { zzz as default }; ->zzz : Symbol(zzz, Decl(a.ts, 0, 0), Decl(a.ts, 9, 8)) +>zzz : Symbol(zzz, Decl(a.ts, 0, 0), Decl(a.ts, 4, 6)) >default : Symbol(zzz, Decl(a.ts, 0, 0), Decl(a.ts, 9, 8)) === tests/cases/compiler/index.ts === diff --git a/tests/baselines/reference/allowSyntheticDefaultImports7.symbols b/tests/baselines/reference/allowSyntheticDefaultImports7.symbols index 51155dd69df..f8930425112 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports7.symbols +++ b/tests/baselines/reference/allowSyntheticDefaultImports7.symbols @@ -7,7 +7,7 @@ export function bar(); === tests/cases/compiler/a.ts === import { default as Foo } from "./b"; ->default : Symbol(Foo, Decl(a.ts, 0, 8)) +>default : Symbol(Foo, Decl(b.d.ts, 0, 0)) >Foo : Symbol(Foo, Decl(a.ts, 0, 8)) Foo.bar(); diff --git a/tests/baselines/reference/allowSyntheticDefaultImports8.errors.txt b/tests/baselines/reference/allowSyntheticDefaultImports8.errors.txt index acb584f8fd9..ea5a7ddf30e 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports8.errors.txt +++ b/tests/baselines/reference/allowSyntheticDefaultImports8.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/a.ts(1,10): error TS2305: Module '"tests/cases/compiler/b"' has no exported member 'default'. +tests/cases/compiler/a.ts(1,10): error TS2305: Module '"./b"' has no exported member 'default'. ==== tests/cases/compiler/b.d.ts (0 errors) ==== @@ -9,6 +9,6 @@ tests/cases/compiler/a.ts(1,10): error TS2305: Module '"tests/cases/compiler/b"' ==== tests/cases/compiler/a.ts (1 errors) ==== import { default as Foo } from "./b"; ~~~~~~~ -!!! error TS2305: Module '"tests/cases/compiler/b"' has no exported member 'default'. +!!! error TS2305: Module '"./b"' has no exported member 'default'. Foo.bar(); Foo.foo(); \ No newline at end of file diff --git a/tests/baselines/reference/allowSyntheticDefaultImports8.symbols b/tests/baselines/reference/allowSyntheticDefaultImports8.symbols index cf5eece0999..bd55792c1ec 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports8.symbols +++ b/tests/baselines/reference/allowSyntheticDefaultImports8.symbols @@ -7,7 +7,6 @@ export function bar(); === tests/cases/compiler/a.ts === import { default as Foo } from "./b"; ->default : Symbol(Foo, Decl(a.ts, 0, 8)) >Foo : Symbol(Foo, Decl(a.ts, 0, 8)) Foo.bar(); diff --git a/tests/baselines/reference/allowSyntheticDefaultImports9.symbols b/tests/baselines/reference/allowSyntheticDefaultImports9.symbols index 51155dd69df..f8930425112 100644 --- a/tests/baselines/reference/allowSyntheticDefaultImports9.symbols +++ b/tests/baselines/reference/allowSyntheticDefaultImports9.symbols @@ -7,7 +7,7 @@ export function bar(); === tests/cases/compiler/a.ts === import { default as Foo } from "./b"; ->default : Symbol(Foo, Decl(a.ts, 0, 8)) +>default : Symbol(Foo, Decl(b.d.ts, 0, 0)) >Foo : Symbol(Foo, Decl(a.ts, 0, 8)) Foo.bar(); diff --git a/tests/baselines/reference/ambientConstLiterals.js b/tests/baselines/reference/ambientConstLiterals.js index b0b222128ac..c5c0fbaafbc 100644 --- a/tests/baselines/reference/ambientConstLiterals.js +++ b/tests/baselines/reference/ambientConstLiterals.js @@ -63,7 +63,7 @@ declare const c3 = "abc"; declare const c4 = 123; declare const c5 = 123; declare const c6 = -123; -declare const c7: boolean; +declare const c7 = true; declare const c8 = E.A; declare const c8b = E["non identifier"]; declare const c9: { diff --git a/tests/baselines/reference/ambientDeclarations.symbols b/tests/baselines/reference/ambientDeclarations.symbols index 1436c698cff..b4a6c394a91 100644 --- a/tests/baselines/reference/ambientDeclarations.symbols +++ b/tests/baselines/reference/ambientDeclarations.symbols @@ -160,7 +160,7 @@ var q = M1.fn(); // Ambient external module in the global module // Ambient external module with a string literal name that is a top level external module name declare module 'external1' { ->'external1' : Symbol('external1', Decl(ambientDeclarations.ts, 67, 16)) +>'external1' : Symbol("external1", Decl(ambientDeclarations.ts, 67, 16)) var q; >q : Symbol(q, Decl(ambientDeclarations.ts, 72, 7)) diff --git a/tests/baselines/reference/ambientDeclarationsExternal.symbols b/tests/baselines/reference/ambientDeclarationsExternal.symbols index 49f0775e136..f0d2ec28221 100644 --- a/tests/baselines/reference/ambientDeclarationsExternal.symbols +++ b/tests/baselines/reference/ambientDeclarationsExternal.symbols @@ -20,7 +20,7 @@ var n: number; === tests/cases/conformance/ambient/decls.ts === // Ambient external module with export assignment declare module 'equ' { ->'equ' : Symbol('equ', Decl(decls.ts, 0, 0)) +>'equ' : Symbol("equ", Decl(decls.ts, 0, 0)) var x; >x : Symbol(x, Decl(decls.ts, 2, 7)) @@ -30,7 +30,7 @@ declare module 'equ' { } declare module 'equ2' { ->'equ2' : Symbol('equ2', Decl(decls.ts, 4, 1)) +>'equ2' : Symbol("equ2", Decl(decls.ts, 4, 1)) var x: number; >x : Symbol(x, Decl(decls.ts, 7, 7)) diff --git a/tests/baselines/reference/ambientErrors.symbols b/tests/baselines/reference/ambientErrors.symbols index 90efbe8383a..308cce2b734 100644 --- a/tests/baselines/reference/ambientErrors.symbols +++ b/tests/baselines/reference/ambientErrors.symbols @@ -90,16 +90,16 @@ module M2 { >M2 : Symbol(M2, Decl(ambientErrors.ts, 42, 1)) declare module 'nope' { } ->'nope' : Symbol('nope', Decl(ambientErrors.ts, 45, 11)) +>'nope' : Symbol("nope", Decl(ambientErrors.ts, 45, 11)) } // Ambient external module with a string literal name that isn't a top level external module name declare module '../foo' { } ->'../foo' : Symbol('../foo', Decl(ambientErrors.ts, 47, 1)) +>'../foo' : Symbol("../foo", Decl(ambientErrors.ts, 47, 1)) // Ambient external module with export assignment and other exported members declare module 'bar' { ->'bar' : Symbol('bar', Decl(ambientErrors.ts, 50, 27)) +>'bar' : Symbol("bar", Decl(ambientErrors.ts, 50, 27)) var n; >n : Symbol(n, Decl(ambientErrors.ts, 54, 7)) diff --git a/tests/baselines/reference/ambientExportDefaultErrors.types b/tests/baselines/reference/ambientExportDefaultErrors.types index 4da013dcf58..21e18cc978a 100644 --- a/tests/baselines/reference/ambientExportDefaultErrors.types +++ b/tests/baselines/reference/ambientExportDefaultErrors.types @@ -29,7 +29,7 @@ declare module "indirect" { >"indirect" : typeof import("indirect") export default typeof Foo.default; ->typeof Foo.default : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof Foo.default : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >Foo.default : number >Foo : typeof Foo >default : number @@ -41,7 +41,7 @@ declare module "indirect2" { >"indirect2" : typeof import("indirect2") export = typeof Foo2; ->typeof Foo2 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof Foo2 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >Foo2 : number } diff --git a/tests/baselines/reference/ambientExternalModuleWithInternalImportDeclaration.symbols b/tests/baselines/reference/ambientExternalModuleWithInternalImportDeclaration.symbols index 621c7b3ebfc..75fb494da11 100644 --- a/tests/baselines/reference/ambientExternalModuleWithInternalImportDeclaration.symbols +++ b/tests/baselines/reference/ambientExternalModuleWithInternalImportDeclaration.symbols @@ -9,7 +9,7 @@ var c = new A(); === tests/cases/compiler/ambientExternalModuleWithInternalImportDeclaration_0.ts === declare module 'M' { ->'M' : Symbol('M', Decl(ambientExternalModuleWithInternalImportDeclaration_0.ts, 0, 0)) +>'M' : Symbol("M", Decl(ambientExternalModuleWithInternalImportDeclaration_0.ts, 0, 0)) module C { >C : Symbol(C, Decl(ambientExternalModuleWithInternalImportDeclaration_0.ts, 0, 20), Decl(ambientExternalModuleWithInternalImportDeclaration_0.ts, 3, 5)) diff --git a/tests/baselines/reference/ambientExternalModuleWithoutInternalImportDeclaration.symbols b/tests/baselines/reference/ambientExternalModuleWithoutInternalImportDeclaration.symbols index 6827122959d..625e5392893 100644 --- a/tests/baselines/reference/ambientExternalModuleWithoutInternalImportDeclaration.symbols +++ b/tests/baselines/reference/ambientExternalModuleWithoutInternalImportDeclaration.symbols @@ -9,7 +9,7 @@ var c = new A(); === tests/cases/compiler/ambientExternalModuleWithoutInternalImportDeclaration_0.ts === declare module 'M' { ->'M' : Symbol('M', Decl(ambientExternalModuleWithoutInternalImportDeclaration_0.ts, 0, 0)) +>'M' : Symbol("M", Decl(ambientExternalModuleWithoutInternalImportDeclaration_0.ts, 0, 0)) module C { >C : Symbol(C, Decl(ambientExternalModuleWithoutInternalImportDeclaration_0.ts, 0, 20), Decl(ambientExternalModuleWithoutInternalImportDeclaration_0.ts, 3, 5)) diff --git a/tests/baselines/reference/ambientWithStatements.errors.txt b/tests/baselines/reference/ambientWithStatements.errors.txt index 3e134970a1f..c7cb28a0f46 100644 --- a/tests/baselines/reference/ambientWithStatements.errors.txt +++ b/tests/baselines/reference/ambientWithStatements.errors.txt @@ -1,11 +1,10 @@ tests/cases/compiler/ambientWithStatements.ts(2,5): error TS1036: Statements are not allowed in ambient contexts. tests/cases/compiler/ambientWithStatements.ts(3,5): error TS1104: A 'continue' statement can only be used within an enclosing iteration statement. -tests/cases/compiler/ambientWithStatements.ts(7,15): error TS2531: Object is possibly 'null'. tests/cases/compiler/ambientWithStatements.ts(11,5): error TS1108: A 'return' statement can only be used within a function body. tests/cases/compiler/ambientWithStatements.ts(25,5): error TS2410: The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'. -==== tests/cases/compiler/ambientWithStatements.ts (5 errors) ==== +==== tests/cases/compiler/ambientWithStatements.ts (4 errors) ==== declare module M { break; ~~~~~ @@ -17,8 +16,6 @@ tests/cases/compiler/ambientWithStatements.ts(25,5): error TS2410: The 'with' st do { } while (true); var x; for (x in null) { } - ~~~~ -!!! error TS2531: Object is possibly 'null'. if (true) { } else { } 1; L: var y; diff --git a/tests/baselines/reference/ambiguousOverloadResolution.js b/tests/baselines/reference/ambiguousOverloadResolution.js index 6e00d7b2374..56bef268fb4 100644 --- a/tests/baselines/reference/ambiguousOverloadResolution.js +++ b/tests/baselines/reference/ambiguousOverloadResolution.js @@ -15,7 +15,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; } diff --git a/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.js b/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.js index 9d95712af40..a4b9d732c0b 100644 --- a/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.js +++ b/tests/baselines/reference/amdDeclarationEmitNoExtraDeclare.js @@ -28,7 +28,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; } diff --git a/tests/baselines/reference/amdModuleBundleNoDuplicateDeclarationEmitComments.js b/tests/baselines/reference/amdModuleBundleNoDuplicateDeclarationEmitComments.js new file mode 100644 index 00000000000..f2e5bc636b4 --- /dev/null +++ b/tests/baselines/reference/amdModuleBundleNoDuplicateDeclarationEmitComments.js @@ -0,0 +1,45 @@ +//// [tests/cases/compiler/amdModuleBundleNoDuplicateDeclarationEmitComments.ts] //// + +//// [file1.ts] +/// +export class Foo {} +//// [file2.ts] +/// +export class Bar {} + +//// [out.js] +define("mynamespace::SomeModuleA", ["require", "exports"], function (require, exports) { + "use strict"; + exports.__esModule = true; + /// + var Foo = /** @class */ (function () { + function Foo() { + } + return Foo; + }()); + exports.Foo = Foo; +}); +define("mynamespace::SomeModuleB", ["require", "exports"], function (require, exports) { + "use strict"; + exports.__esModule = true; + /// + var Bar = /** @class */ (function () { + function Bar() { + } + return Bar; + }()); + exports.Bar = Bar; +}); + + +//// [out.d.ts] +/// +declare module "mynamespace::SomeModuleA" { + export class Foo { + } +} +/// +declare module "mynamespace::SomeModuleB" { + export class Bar { + } +} diff --git a/tests/baselines/reference/amdModuleBundleNoDuplicateDeclarationEmitComments.symbols b/tests/baselines/reference/amdModuleBundleNoDuplicateDeclarationEmitComments.symbols new file mode 100644 index 00000000000..69eaee002f2 --- /dev/null +++ b/tests/baselines/reference/amdModuleBundleNoDuplicateDeclarationEmitComments.symbols @@ -0,0 +1,10 @@ +=== tests/cases/compiler/file1.ts === +/// +export class Foo {} +>Foo : Symbol(Foo, Decl(file1.ts, 0, 0)) + +=== tests/cases/compiler/file2.ts === +/// +export class Bar {} +>Bar : Symbol(Bar, Decl(file2.ts, 0, 0)) + diff --git a/tests/baselines/reference/amdModuleBundleNoDuplicateDeclarationEmitComments.types b/tests/baselines/reference/amdModuleBundleNoDuplicateDeclarationEmitComments.types new file mode 100644 index 00000000000..d90ff85e5fb --- /dev/null +++ b/tests/baselines/reference/amdModuleBundleNoDuplicateDeclarationEmitComments.types @@ -0,0 +1,10 @@ +=== tests/cases/compiler/file1.ts === +/// +export class Foo {} +>Foo : Foo + +=== tests/cases/compiler/file2.ts === +/// +export class Bar {} +>Bar : Bar + diff --git a/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.js b/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.js index 2b535bf45fd..9579d7c5a4a 100644 --- a/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.js +++ b/tests/baselines/reference/anonymousClassDeclarationDoesntPrintWithReadonly.js @@ -15,7 +15,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; } diff --git a/tests/baselines/reference/anonymousClassExpression1.types b/tests/baselines/reference/anonymousClassExpression1.types index 3bc01960492..2e761d10afd 100644 --- a/tests/baselines/reference/anonymousClassExpression1.types +++ b/tests/baselines/reference/anonymousClassExpression1.types @@ -4,7 +4,7 @@ function f() { return typeof class {} === "function"; >typeof class {} === "function" : boolean ->typeof class {} : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof class {} : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >class {} : typeof (Anonymous class) >"function" : "function" } diff --git a/tests/baselines/reference/anonymousModules.errors.txt b/tests/baselines/reference/anonymousModules.errors.txt index b81513cfbbd..24468352d03 100644 --- a/tests/baselines/reference/anonymousModules.errors.txt +++ b/tests/baselines/reference/anonymousModules.errors.txt @@ -1,22 +1,22 @@ -tests/cases/compiler/anonymousModules.ts(1,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/anonymousModules.ts(1,1): error TS2580: Cannot find name 'module'. 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. tests/cases/compiler/anonymousModules.ts(1,8): error TS1005: ';' expected. -tests/cases/compiler/anonymousModules.ts(4,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/anonymousModules.ts(4,2): error TS2580: Cannot find name 'module'. 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. tests/cases/compiler/anonymousModules.ts(4,9): error TS1005: ';' expected. -tests/cases/compiler/anonymousModules.ts(10,2): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +tests/cases/compiler/anonymousModules.ts(10,2): error TS2580: Cannot find name 'module'. 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. tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected. ==== tests/cases/compiler/anonymousModules.ts (6 errors) ==== module { ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. 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. ~ !!! error TS1005: ';' expected. export var foo = 1; module { ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. 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. ~ !!! error TS1005: ';' expected. export var bar = 1; @@ -26,7 +26,7 @@ tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected. module { ~~~~~~ -!!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. +!!! error TS2580: Cannot find name 'module'. 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. ~ !!! error TS1005: ';' expected. var x = bar; diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 9465a512a1f..c3076883b46 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.1"; + const versionMajorMinor = "3.2"; /** 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; } @@ -723,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; @@ -995,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; @@ -1082,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 { @@ -1542,7 +1550,6 @@ declare namespace ts { } interface JSDocTag extends Node { parent: JSDoc | JSDocTypeLiteral; - atToken: AtToken; tagName: Identifier; comment?: string; } @@ -1572,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 { @@ -1754,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 @@ -1811,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. */ @@ -1839,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, @@ -1921,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. @@ -1939,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[]; @@ -1978,7 +1976,8 @@ declare namespace ts { AllowEmptyTuple = 524288, AllowUniqueESSymbolType = 1048576, AllowEmptyIndexInfoType = 2097152, - IgnoreErrors = 3112960, + AllowNodeModulesRelativePaths = 67108864, + IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, InInitialEntityName = 16777216, @@ -2158,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 { @@ -2206,7 +2208,7 @@ declare namespace ts { aliasTypeArguments?: ReadonlyArray; } interface LiteralType extends Type { - value: string | number; + value: string | number | PseudoBigInt; freshType: LiteralType; regularType: LiteralType; } @@ -2219,6 +2221,9 @@ declare namespace ts { interface NumberLiteralType extends LiteralType { value: number; } + interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } interface EnumType extends Type { } enum ObjectFlags { @@ -2237,6 +2242,7 @@ declare namespace ts { JsxAttributes = 4096, MarkerType = 8192, JSLiteral = 16384, + FreshLiteral = 32768, ClassOrInterface = 3 } interface ObjectType extends Type { @@ -2493,6 +2499,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2584,7 +2591,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2668,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; @@ -2686,11 +2694,11 @@ 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; } @@ -2745,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. */ @@ -2938,60 +2947,62 @@ 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; @@ -3003,6 +3014,11 @@ declare namespace ts { 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; declare function clearTimeout(handle: any): void; @@ -3119,7 +3135,7 @@ declare namespace ts { /** 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; @@ -3285,6 +3301,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; @@ -3462,6 +3479,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; @@ -3604,7 +3622,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. @@ -3619,14 +3637,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; @@ -3634,18 +3652,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; @@ -4146,7 +4165,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; @@ -4183,14 +4202,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 { @@ -4315,23 +4335,23 @@ 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; + 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 */ @@ -4381,9 +4401,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[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; } /** * Host to create watch with root files and options @@ -4393,6 +4413,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4427,8 +4449,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 */ @@ -4442,15 +4464,13 @@ 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; @@ -4648,9 +4668,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. @@ -4658,7 +4678,11 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; + writeFile?(fileName: string, content: string): void; } + type WithMetadata = T & { + metadata?: unknown; + }; interface LanguageService { cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; @@ -4676,7 +4700,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; @@ -4684,16 +4708,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; @@ -4715,9 +4739,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 */ @@ -4879,9 +4903,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. */ @@ -4947,6 +4978,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5024,24 +5057,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; @@ -5099,20 +5133,24 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; } - interface RenameInfo { - canRename: boolean; + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; /** * File or directory to rename. * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. */ fileToRename?: string; - localizedErrorMessage?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; @@ -5230,8 +5268,9 @@ declare namespace ts { Whitespace = 4, Identifier = 5, NumberLiteral = 6, - StringLiteral = 7, - RegExpLiteral = 8 + BigIntLiteral = 7, + StringLiteral = 8, + RegExpLiteral = 9 } interface ClassificationResult { finalLexState: EndOfLineState; @@ -5343,13 +5382,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", @@ -5394,7 +5440,8 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24 + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 } } declare namespace ts { @@ -5486,6 +5533,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"; @@ -5575,7 +5626,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; }; @@ -5656,7 +5706,8 @@ declare namespace ts.server.protocol { GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", OrganizeImports = "organizeImports", - GetEditsForFileRename = "getEditsForFileRename" + GetEditsForFileRename = "getEditsForFileRename", + ConfigurePlugin = "configurePlugin" } /** * A TypeScript Server message @@ -5731,6 +5782,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. @@ -6376,7 +6431,7 @@ declare namespace ts.server.protocol { /** * The file locations referencing the symbol. */ - refs: ReferencesResponseItem[]; + refs: ReadonlyArray; /** * The name of the symbol. */ @@ -6422,20 +6477,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; /** * File or directory to rename. * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. */ fileToRename?: string; - /** - * Error message if item can not be renamed. - */ - localizedErrorMessage?: string; /** * Display name of the item to be renamed. */ @@ -6452,6 +6504,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'. @@ -6460,7 +6521,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 { /** @@ -6595,6 +6660,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. */ @@ -7432,6 +7505,7 @@ declare namespace ts.server.protocol { */ interface DiagnosticEvent extends Event { body?: DiagnosticEventBody; + event: DiagnosticEventKind; } interface ConfigFileDiagnosticEventBody { /** @@ -7485,6 +7559,26 @@ 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; @@ -8021,6 +8115,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; @@ -8085,7 +8184,7 @@ declare namespace ts.server { getCompilerOptions(): CompilerOptions; getNewLine(): string; getProjectVersion(): string; - getProjectReferences(): ReadonlyArray; + getProjectReferences(): ReadonlyArray | undefined; getScriptFileNames(): string[]; private getOrCreateScriptInfoAndAttachToProject; getScriptKind(fileName: string): ScriptKind; @@ -8097,10 +8196,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; @@ -8158,11 +8258,11 @@ declare namespace ts.server { filesToString(writeProjectFileNames: boolean): string; setCompilerOptions(compilerOptions: CompilerOptions): void; protected removeRoot(info: ScriptInfo): void; - protected enableGlobalPlugins(options: CompilerOptions): 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, @@ -8201,9 +8301,8 @@ declare namespace ts.server { */ 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 */ @@ -8236,6 +8335,8 @@ 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"; @@ -8248,6 +8349,19 @@ 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: { @@ -8323,16 +8437,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 | SurveyReady | 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]: { @@ -8382,6 +8502,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 @@ -8430,7 +8551,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; @@ -8447,6 +8568,7 @@ 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. */ @@ -8552,6 +8674,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; @@ -8618,6 +8744,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 { @@ -8659,6 +8786,7 @@ declare namespace ts.server { globalPlugins?: ReadonlyArray; pluginProbeLocations?: ReadonlyArray; allowLocalPluginLoads?: boolean; + typesMapLocation?: string; } class Session implements EventSender { private readonly gcTimer; @@ -8681,6 +8809,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 */ @@ -8725,7 +8854,7 @@ declare namespace ts.server { private getProjects; private getDefaultProject; private getRenameLocations; - private static mapRenameInfo; + private mapRenameInfo; private toSpanGroups; private getReferences; /** @@ -8772,7 +8901,7 @@ declare namespace ts.server { private getFullNavigateToItems; private getSupportedCodeFixes; private isLocation; - private extractPositionAndRange; + private extractPositionOrRange; private getApplicableRefactors; private getEditsForRefactor; private organizeImports; @@ -8788,6 +8917,7 @@ declare namespace ts.server { private convertTextChangeToCodeEdit; private getBraceMatching; private getDiagnosticsForProject; + private configurePlugin; getCanonicalFileName(fileName: string): string; exit(): void; private notRequired; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 66ba75bbd93..f4cebf2da7f 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -14,7 +14,7 @@ and limitations under the License. ***************************************************************************** */ declare namespace ts { - const versionMajorMinor = "3.1"; + const versionMajorMinor = "3.2"; /** 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; } @@ -723,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; @@ -995,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; @@ -1082,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 { @@ -1542,7 +1550,6 @@ declare namespace ts { } interface JSDocTag extends Node { parent: JSDoc | JSDocTypeLiteral; - atToken: AtToken; tagName: Identifier; comment?: string; } @@ -1572,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 { @@ -1754,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 @@ -1811,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. */ @@ -1839,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, @@ -1921,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. @@ -1939,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[]; @@ -1978,7 +1976,8 @@ declare namespace ts { AllowEmptyTuple = 524288, AllowUniqueESSymbolType = 1048576, AllowEmptyIndexInfoType = 2097152, - IgnoreErrors = 3112960, + AllowNodeModulesRelativePaths = 67108864, + IgnoreErrors = 70221824, InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, InInitialEntityName = 16777216, @@ -2158,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 { @@ -2206,7 +2208,7 @@ declare namespace ts { aliasTypeArguments?: ReadonlyArray; } interface LiteralType extends Type { - value: string | number; + value: string | number | PseudoBigInt; freshType: LiteralType; regularType: LiteralType; } @@ -2219,6 +2221,9 @@ declare namespace ts { interface NumberLiteralType extends LiteralType { value: number; } + interface BigIntLiteralType extends LiteralType { + value: PseudoBigInt; + } interface EnumType extends Type { } enum ObjectFlags { @@ -2237,6 +2242,7 @@ declare namespace ts { JsxAttributes = 4096, MarkerType = 8192, JSLiteral = 16384, + FreshLiteral = 32768, ClassOrInterface = 3 } interface ObjectType extends Type { @@ -2493,6 +2499,7 @@ declare namespace ts { sourceRoot?: string; strict?: boolean; strictFunctionTypes?: boolean; + strictBindCallApply?: boolean; strictNullChecks?: boolean; strictPropertyInitialization?: boolean; stripInternal?: boolean; @@ -2584,7 +2591,6 @@ declare namespace ts { } interface ExpandResult { fileNames: string[]; - projectReferences: ReadonlyArray | undefined; wildcardDirectories: MapLike; } interface CreateProgramOptions { @@ -2668,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; @@ -2686,11 +2694,11 @@ 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; } @@ -2745,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. */ @@ -2938,60 +2947,62 @@ 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; @@ -3003,6 +3014,11 @@ declare namespace ts { 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; declare function clearTimeout(handle: any): void; @@ -3119,7 +3135,7 @@ declare namespace ts { /** 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; @@ -3285,6 +3301,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; @@ -3462,6 +3479,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; @@ -3604,7 +3622,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. @@ -3619,14 +3637,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; @@ -3634,18 +3652,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; @@ -4146,7 +4165,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; @@ -4183,14 +4202,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 { @@ -4315,23 +4335,23 @@ 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; + 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 */ @@ -4381,9 +4401,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[]; + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; } /** * Host to create watch with root files and options @@ -4393,6 +4413,8 @@ declare namespace ts { rootFiles: string[]; /** Compiler options */ options: CompilerOptions; + /** Project References */ + projectReferences?: ReadonlyArray; } /** * Host to create watch with config file @@ -4427,8 +4449,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 */ @@ -4442,15 +4464,13 @@ 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; @@ -4648,9 +4668,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. @@ -4658,7 +4678,11 @@ declare namespace ts { getCustomTransformers?(): CustomTransformers | undefined; isKnownTypesPackageName?(name: string): boolean; installPackage?(options: InstallPackageOptions): Promise; + writeFile?(fileName: string, content: string): void; } + type WithMetadata = T & { + metadata?: unknown; + }; interface LanguageService { cleanupSemanticCache(): void; getSyntacticDiagnostics(fileName: string): DiagnosticWithLocation[]; @@ -4676,7 +4700,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; @@ -4684,16 +4708,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; @@ -4715,9 +4739,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 */ @@ -4879,9 +4903,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. */ @@ -4947,6 +4978,8 @@ declare namespace ts { originalFileName?: string; } interface RenameLocation extends DocumentSpan { + readonly prefixText?: string; + readonly suffixText?: string; } interface ReferenceEntry extends DocumentSpan { isWriteAccess: boolean; @@ -5024,24 +5057,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; @@ -5099,20 +5133,24 @@ declare namespace ts { documentation?: SymbolDisplayPart[]; tags?: JSDocTagInfo[]; } - interface RenameInfo { - canRename: boolean; + type RenameInfo = RenameInfoSuccess | RenameInfoFailure; + interface RenameInfoSuccess { + canRename: true; /** * File or directory to rename. * If set, `getEditsForFileRename` should be called instead of `findRenameLocations`. */ fileToRename?: string; - localizedErrorMessage?: string; displayName: string; fullDisplayName: string; kind: ScriptElementKind; kindModifiers: string; triggerSpan: TextSpan; } + interface RenameInfoFailure { + canRename: false; + localizedErrorMessage: string; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; @@ -5230,8 +5268,9 @@ declare namespace ts { Whitespace = 4, Identifier = 5, NumberLiteral = 6, - StringLiteral = 7, - RegExpLiteral = 8 + BigIntLiteral = 7, + StringLiteral = 8, + RegExpLiteral = 9 } interface ClassificationResult { finalLexState: EndOfLineState; @@ -5343,13 +5382,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", @@ -5394,7 +5440,8 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24 + jsxAttributeStringLiteralValue = 24, + bigintLiteral = 25 } } declare namespace ts { @@ -5486,6 +5533,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/tests/baselines/reference/apparentTypeSubtyping.js b/tests/baselines/reference/apparentTypeSubtyping.js index 6b153002813..2e9987f1e0d 100644 --- a/tests/baselines/reference/apparentTypeSubtyping.js +++ b/tests/baselines/reference/apparentTypeSubtyping.js @@ -30,7 +30,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; } diff --git a/tests/baselines/reference/apparentTypeSupertype.js b/tests/baselines/reference/apparentTypeSupertype.js index 63e6345e5ba..82443d22197 100644 --- a/tests/baselines/reference/apparentTypeSupertype.js +++ b/tests/baselines/reference/apparentTypeSupertype.js @@ -20,7 +20,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; } diff --git a/tests/baselines/reference/argumentExpressionContextualTyping.errors.txt b/tests/baselines/reference/argumentExpressionContextualTyping.errors.txt index 87c3a6d0b37..c983abfa1be 100644 --- a/tests/baselines/reference/argumentExpressionContextualTyping.errors.txt +++ b/tests/baselines/reference/argumentExpressionContextualTyping.errors.txt @@ -1,12 +1,11 @@ tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts(16,5): error TS2345: Argument of type '(string | number | boolean)[]' is not assignable to parameter of type '[string, number, boolean]'. - Property '0' is missing in type '(string | number | boolean)[]'. + Type '(string | number | boolean)[]' is missing the following properties from type '[string, number, boolean]': 0, 1, 2 tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts(17,5): error TS2345: Argument of type '[string, number, true, ...(string | number | boolean)[]]' is not assignable to parameter of type '[string, number, boolean]'. Types of property 'length' are incompatible. Type 'number' is not assignable to type '3'. tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts(18,5): error TS2345: Argument of type '{ x: (string | number)[]; y: { c: boolean; d: string; e: number; }; }' is not assignable to parameter of type '{ x: [any, any]; y: { c: any; d: any; e: any; }; }'. Types of property 'x' are incompatible. - Type '(string | number)[]' is not assignable to type '[any, any]'. - Property '0' is missing in type '(string | number)[]'. + Type '(string | number)[]' is missing the following properties from type '[any, any]': 0, 1 ==== tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts (3 errors) ==== @@ -28,7 +27,7 @@ tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextua baz(array); // Error ~~~~~ !!! error TS2345: Argument of type '(string | number | boolean)[]' is not assignable to parameter of type '[string, number, boolean]'. -!!! error TS2345: Property '0' is missing in type '(string | number | boolean)[]'. +!!! error TS2345: Type '(string | number | boolean)[]' is missing the following properties from type '[string, number, boolean]': 0, 1, 2 baz(["string", 1, true, ...array]); // Error ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '[string, number, true, ...(string | number | boolean)[]]' is not assignable to parameter of type '[string, number, boolean]'. @@ -38,5 +37,4 @@ tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextua ~ !!! error TS2345: Argument of type '{ x: (string | number)[]; y: { c: boolean; d: string; e: number; }; }' is not assignable to parameter of type '{ x: [any, any]; y: { c: any; d: any; e: any; }; }'. !!! error TS2345: Types of property 'x' are incompatible. -!!! error TS2345: Type '(string | number)[]' is not assignable to type '[any, any]'. -!!! error TS2345: Property '0' is missing in type '(string | number)[]'. \ No newline at end of file +!!! error TS2345: Type '(string | number)[]' is missing the following properties from type '[any, any]': 0, 1 \ No newline at end of file diff --git a/tests/baselines/reference/arithmeticOnInvalidTypes.errors.txt b/tests/baselines/reference/arithmeticOnInvalidTypes.errors.txt index 2c042af6f86..ac526ccc5a9 100644 --- a/tests/baselines/reference/arithmeticOnInvalidTypes.errors.txt +++ b/tests/baselines/reference/arithmeticOnInvalidTypes.errors.txt @@ -1,10 +1,10 @@ tests/cases/compiler/arithmeticOnInvalidTypes.ts(3,9): error TS2365: Operator '+' cannot be applied to types 'Number' and 'Number'. -tests/cases/compiler/arithmeticOnInvalidTypes.ts(4,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes.ts(4,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes.ts(5,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes.ts(5,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes.ts(6,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes.ts(6,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes.ts(4,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes.ts(4,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes.ts(5,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes.ts(5,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes.ts(6,10): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes.ts(6,14): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/compiler/arithmeticOnInvalidTypes.ts (7 errors) ==== @@ -15,16 +15,16 @@ tests/cases/compiler/arithmeticOnInvalidTypes.ts(6,14): error TS2363: The right- !!! error TS2365: Operator '+' cannot be applied to types 'Number' and 'Number'. var z2 = x - y; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var z3 = x * y; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var z4 = x / y; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/arithmeticOnInvalidTypes2.errors.txt b/tests/baselines/reference/arithmeticOnInvalidTypes2.errors.txt index d5b74e5abc7..f4dd0cd7852 100644 --- a/tests/baselines/reference/arithmeticOnInvalidTypes2.errors.txt +++ b/tests/baselines/reference/arithmeticOnInvalidTypes2.errors.txt @@ -1,10 +1,10 @@ tests/cases/compiler/arithmeticOnInvalidTypes2.ts(2,14): error TS2365: Operator '+' cannot be applied to types 'T' and 'T'. -tests/cases/compiler/arithmeticOnInvalidTypes2.ts(3,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes2.ts(3,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes2.ts(4,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes2.ts(4,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes2.ts(5,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/arithmeticOnInvalidTypes2.ts(5,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes2.ts(3,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes2.ts(3,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes2.ts(4,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes2.ts(4,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes2.ts(5,14): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/arithmeticOnInvalidTypes2.ts(5,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/compiler/arithmeticOnInvalidTypes2.ts (7 errors) ==== @@ -14,18 +14,18 @@ tests/cases/compiler/arithmeticOnInvalidTypes2.ts(5,18): error TS2363: The right !!! error TS2365: Operator '+' cannot be applied to types 'T' and 'T'. var z2 = a - b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var z3 = a * b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var z4 = a / b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. return a; }; \ No newline at end of file diff --git a/tests/baselines/reference/arithmeticOperatorWithInvalidOperands.errors.txt b/tests/baselines/reference/arithmeticOperatorWithInvalidOperands.errors.txt index 0d376912b8d..cfcd2cded79 100644 --- a/tests/baselines/reference/arithmeticOperatorWithInvalidOperands.errors.txt +++ b/tests/baselines/reference/arithmeticOperatorWithInvalidOperands.errors.txt @@ -1,560 +1,560 @@ -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(15,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(17,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(18,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(19,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(22,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(24,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(24,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(25,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(25,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(26,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(26,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(29,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(31,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(32,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(33,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(35,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(36,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(36,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(37,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(38,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(39,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(40,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(42,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(43,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(43,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(44,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(45,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(45,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(46,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(46,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(47,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(50,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(50,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(51,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(52,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(52,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(53,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(53,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(54,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(54,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(57,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(59,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(60,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(61,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(67,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(68,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(72,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(74,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(75,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(76,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(78,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(79,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(79,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(80,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(81,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(81,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(82,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(82,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(83,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(83,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(86,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(88,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(89,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(90,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(92,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(93,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(93,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(94,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(95,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(95,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(96,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(96,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(97,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(97,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(99,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(100,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(100,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(101,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(102,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(102,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(103,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(103,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(104,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(104,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(106,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(107,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(107,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(108,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(109,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(109,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(110,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(110,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(111,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(111,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(114,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(116,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(117,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(118,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(121,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(123,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(124,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(125,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(129,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(131,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(132,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(133,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(135,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(136,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(136,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(137,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(138,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(138,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(139,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(139,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(140,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(140,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(143,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(145,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(146,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(147,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(149,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(150,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(150,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(151,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(152,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(152,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(153,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(153,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(154,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(154,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(156,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(157,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(157,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(158,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(159,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(159,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(160,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(160,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(161,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(161,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(163,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(164,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(164,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(165,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(166,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(166,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(167,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(167,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(168,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(168,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(171,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(173,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(174,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(175,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(178,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(180,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(181,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(182,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(186,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(188,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(189,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(190,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(192,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(193,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(193,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(194,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(195,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(195,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(196,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(196,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(197,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(197,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(200,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(202,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(203,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(204,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(206,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(207,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(207,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(208,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(209,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(209,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(210,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(210,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(211,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(211,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(213,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(214,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(214,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(215,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(216,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(216,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(217,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(217,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(218,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(218,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(220,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(221,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(221,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(222,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(223,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(223,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(224,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(224,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(225,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(225,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(228,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(230,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(231,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(232,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(235,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(237,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(238,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(239,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(243,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(245,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(246,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(247,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(249,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(250,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(250,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(251,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(252,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(252,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(253,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(253,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(254,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(254,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(257,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(259,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(260,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(261,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(263,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(264,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(264,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(265,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(266,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(266,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(267,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(267,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(268,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(268,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(270,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(271,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(271,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(272,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(273,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(273,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(274,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(274,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(275,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(275,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(277,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(278,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(278,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(279,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(280,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(280,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(281,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(281,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(282,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(282,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(285,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(287,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(288,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(289,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(292,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(294,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(295,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(296,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(300,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(302,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(303,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(304,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(306,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(307,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(307,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(308,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(309,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(309,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(310,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(310,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(311,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(311,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(314,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(316,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(317,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(318,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(320,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(321,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(321,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(322,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(323,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(323,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(324,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(324,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(325,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(325,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(327,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(328,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(328,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(329,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(330,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(330,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(331,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(331,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(332,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(332,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(334,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(335,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(335,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(336,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(337,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(337,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(338,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(338,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(339,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(339,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(342,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(344,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(345,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(346,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(349,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(351,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(352,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(353,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(357,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(359,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(360,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(361,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(363,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(364,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(364,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(365,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(366,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(366,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(367,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(367,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(368,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(368,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(371,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(373,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(374,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(375,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(377,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(378,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(378,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(379,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(380,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(380,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(381,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(381,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(382,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(382,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(384,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(385,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(385,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(386,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(387,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(387,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(388,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(388,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(389,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(389,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(391,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(392,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(392,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(393,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(394,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(394,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(395,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(395,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(396,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(396,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(399,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(401,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(402,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(403,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(406,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(408,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(409,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(410,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(414,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(416,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(417,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(418,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(420,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(15,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(17,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(18,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(19,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(22,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(24,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(24,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(25,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(25,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(26,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(26,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(29,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(31,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(32,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(33,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(35,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(36,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(36,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(37,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(38,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(39,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(40,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(42,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(43,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(43,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(44,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(45,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(45,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(46,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(46,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(47,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(50,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(50,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(51,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(52,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(52,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(53,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(53,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(54,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(54,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(57,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(59,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(60,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(61,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(67,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(68,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(72,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(74,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(75,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(76,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(78,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(79,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(79,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(80,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(81,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(81,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(82,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(82,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(83,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(83,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(86,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(88,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(89,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(90,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(92,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(93,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(93,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(94,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(95,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(95,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(96,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(96,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(97,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(97,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(99,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(100,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(100,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(101,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(102,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(102,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(103,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(103,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(104,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(104,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(106,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(107,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(107,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(108,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(109,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(109,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(110,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(110,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(111,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(111,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(114,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(116,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(117,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(118,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(121,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(123,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(124,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(125,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(129,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(131,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(132,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(133,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(135,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(136,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(136,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(137,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(138,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(138,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(139,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(139,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(140,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(140,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(143,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(145,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(146,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(147,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(149,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(150,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(150,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(151,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(152,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(152,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(153,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(153,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(154,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(154,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(156,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(157,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(157,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(158,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(159,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(159,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(160,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(160,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(161,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(161,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(163,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(164,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(164,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(165,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(166,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(166,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(167,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(167,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(168,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(168,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(171,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(173,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(174,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(175,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(178,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(180,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(181,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(182,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(186,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(188,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(189,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(190,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(192,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(193,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(193,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(194,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(195,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(195,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(196,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(196,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(197,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(197,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(200,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(202,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(203,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(204,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(206,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(207,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(207,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(208,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(209,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(209,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(210,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(210,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(211,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(211,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(213,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(214,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(214,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(215,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(216,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(216,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(217,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(217,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(218,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(218,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(220,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(221,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(221,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(222,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(223,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(223,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(224,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(224,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(225,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(225,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(228,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(230,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(231,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(232,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(235,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(237,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(238,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(239,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(243,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(245,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(246,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(247,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(249,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(250,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(250,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(251,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(252,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(252,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(253,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(253,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(254,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(254,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(257,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(259,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(260,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(261,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(263,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(264,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(264,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(265,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(266,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(266,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(267,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(267,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(268,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(268,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(270,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(271,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(271,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(272,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(273,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(273,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(274,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(274,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(275,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(275,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(277,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(278,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(278,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(279,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(280,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(280,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(281,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(281,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(282,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(282,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(285,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(287,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(288,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(289,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(292,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(294,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(295,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(296,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(300,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(302,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(303,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(304,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(306,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(307,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(307,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(308,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(309,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(309,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(310,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(310,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(311,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(311,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(314,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(316,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(317,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(318,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(320,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(321,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(321,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(322,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(323,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(323,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(324,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(324,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(325,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(325,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(327,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(328,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(328,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(329,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(330,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(330,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(331,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(331,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(332,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(332,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(334,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(335,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(335,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(336,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(337,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(337,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(338,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(338,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(339,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(339,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(342,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(344,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(345,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(346,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(349,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(351,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(352,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(353,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(357,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(359,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(360,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(361,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(363,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(364,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(364,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(365,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(366,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(366,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(367,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(367,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(368,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(368,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(371,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(373,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(374,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(375,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(377,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(378,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(378,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(379,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(380,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(380,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(381,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(381,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(382,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(382,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(384,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(385,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(385,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(386,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(387,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(387,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(388,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(388,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(389,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(389,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(391,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(392,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(392,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(393,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(394,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(394,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(395,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(395,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(396,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(396,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(399,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(401,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(402,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(403,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(406,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(408,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(409,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(410,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(414,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(416,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(417,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(418,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(420,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(421,12): error TS2447: The '&' operator is not allowed for boolean types. Consider using '&&' instead. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(422,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(423,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(423,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(424,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(424,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(425,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(425,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(428,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(430,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(431,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(432,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(434,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(435,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(435,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(436,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(437,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(437,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(438,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(438,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(439,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(439,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(441,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(442,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(442,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(443,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(444,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(444,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(445,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(445,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(446,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(446,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(448,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(449,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(449,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(450,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(451,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(451,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(452,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(452,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(453,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(453,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(456,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(458,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(459,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(460,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(463,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(465,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(466,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(467,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(471,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(473,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(474,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(475,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(477,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(422,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(423,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(423,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(424,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(424,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(425,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(425,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(428,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(430,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(431,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(432,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(434,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(435,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(435,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(436,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(437,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(437,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(438,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(438,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(439,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(439,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(441,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(442,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(442,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(443,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(444,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(444,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(445,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(445,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(446,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(446,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(448,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(449,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(449,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(450,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(451,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(451,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(452,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(452,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(453,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(453,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(456,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(458,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(459,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(460,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(463,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(465,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(466,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(467,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(471,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(473,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(474,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(475,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(477,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(478,12): error TS2447: The '^' operator is not allowed for boolean types. Consider using '!==' instead. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(479,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(480,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(480,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(481,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(481,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(482,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(482,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(485,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(487,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(488,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(489,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(491,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(492,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(492,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(493,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(494,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(494,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(495,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(495,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(496,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(496,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(498,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(499,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(499,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(500,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(501,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(501,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(502,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(502,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(503,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(503,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(505,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(506,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(506,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(507,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(508,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(508,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(509,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(509,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(510,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(510,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(513,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(515,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(516,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(517,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(520,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(522,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(523,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(524,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(528,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(530,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(531,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(532,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(534,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(479,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(480,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(480,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(481,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(481,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(482,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(482,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(485,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(487,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(488,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(489,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(491,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(492,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(492,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(493,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(494,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(494,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(495,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(495,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(496,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(496,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(498,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(499,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(499,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(500,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(501,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(501,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(502,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(502,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(503,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(503,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(505,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(506,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(506,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(507,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(508,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(508,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(509,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(509,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(510,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(510,16): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(513,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(515,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(516,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(517,18): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(520,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(522,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(523,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(524,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(528,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(530,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(531,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(532,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(534,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(535,13): error TS2447: The '|' operator is not allowed for boolean types. Consider using '||' instead. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(536,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(537,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(537,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(538,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(538,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(539,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(539,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(542,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(544,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(545,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(546,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(548,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(549,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(549,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(550,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(551,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(551,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(552,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(552,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(553,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(553,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(555,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(556,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(556,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(557,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(558,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(558,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(559,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(559,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(560,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(560,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(562,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(563,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(563,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(564,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(565,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(565,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(566,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(566,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(567,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(567,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(570,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(572,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(573,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(574,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(577,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(579,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(580,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(581,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(536,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(537,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(537,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(538,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(538,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(539,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(539,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(542,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(544,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(545,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(546,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(548,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(549,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(549,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(550,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(551,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(551,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(552,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(552,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(553,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(553,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(555,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(556,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(556,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(557,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(558,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(558,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(559,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(559,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(560,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(560,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(562,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(563,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(563,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(564,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(565,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(565,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(566,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(566,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(567,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(567,17): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(570,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(572,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(573,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(574,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(577,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(579,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(580,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts(581,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithInvalidOperands.ts (557 errors) ==== @@ -574,1682 +574,1682 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti var r1a1 = a * a; //ok var r1a2 = a * b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a3 = a * c; //ok var r1a4 = a * d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a5 = a * e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a6 = a * f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b1 = b * a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b2 = b * b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b3 = b * c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b4 = b * d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b5 = b * e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b6 = b * f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c1 = c * a; //ok var r1c2 = c * b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c3 = c * c; //ok var r1c4 = c * d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c5 = c * e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c6 = c * f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d1 = d * a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d2 = d * b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d3 = d * c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d4 = d * d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d5 = d * e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d6 = d * f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e1 = e * a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e2 = e * b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e3 = e * c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e4 = e * d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e5 = e * e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e6 = e * f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f1 = f * a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f2 = f * b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f3 = f * c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f4 = f * d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f5 = f * e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f6 = f * f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1g1 = E.a * a; //ok var r1g2 = E.a * b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1g3 = E.a * c; //ok var r1g4 = E.a * d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1g5 = E.a * e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1g6 = E.a * f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1h1 = a * E.b; //ok var r1h2 = b * E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1h3 = c * E.b; //ok var r1h4 = d * E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1h5 = e * E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1h6 = f * E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator / var r2a1 = a / a; //ok var r2a2 = a / b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a3 = a / c; //ok var r2a4 = a / d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a5 = a / e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a6 = a / f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b1 = b / a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b2 = b / b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b3 = b / c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b4 = b / d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b5 = b / e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b6 = b / f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c1 = c / a; //ok var r2c2 = c / b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c3 = c / c; //ok var r2c4 = c / d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c5 = c / e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c6 = c / f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d1 = d / a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d2 = d / b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d3 = d / c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d4 = d / d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d5 = d / e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d6 = d / f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e1 = e / a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e2 = e / b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e3 = e / c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e4 = e / d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e5 = e / e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e6 = e / f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2f1 = f / a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2f2 = f / b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2f3 = f / c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2f4 = f / d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2f5 = f / e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2f6 = f / f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2g1 = E.a / a; //ok var r2g2 = E.a / b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2g3 = E.a / c; //ok var r2g4 = E.a / d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2g5 = E.a / e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2g6 = E.a / f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2h1 = a / E.b; //ok var r2h2 = b / E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2h3 = c / E.b; //ok var r2h4 = d / E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2h5 = e / E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2h6 = f / E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator % var r3a1 = a % a; //ok var r3a2 = a % b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a3 = a % c; //ok var r3a4 = a % d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a5 = a % e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a6 = a % f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b1 = b % a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b2 = b % b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b3 = b % c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b4 = b % d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b5 = b % e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b6 = b % f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c1 = c % a; //ok var r3c2 = c % b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c3 = c % c; //ok var r3c4 = c % d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c5 = c % e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c6 = c % f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d1 = d % a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d2 = d % b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d3 = d % c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d4 = d % d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d5 = d % e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d6 = d % f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3e1 = e % a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3e2 = e % b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3e3 = e % c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3e4 = e % d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3e5 = e % e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3e6 = e % f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3f1 = f % a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3f2 = f % b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3f3 = f % c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3f4 = f % d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3f5 = f % e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3f6 = f % f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3g1 = E.a % a; //ok var r3g2 = E.a % b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3g3 = E.a % c; //ok var r3g4 = E.a % d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3g5 = E.a % e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3g6 = E.a % f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3h1 = a % E.b; //ok var r3h2 = b % E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3h3 = c % E.b; //ok var r3h4 = d % E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3h5 = e % E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3h6 = f % E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator - var r4a1 = a - a; //ok var r4a2 = a - b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a3 = a - c; //ok var r4a4 = a - d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a5 = a - e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a6 = a - f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b1 = b - a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b2 = b - b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b3 = b - c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b4 = b - d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b5 = b - e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b6 = b - f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c1 = c - a; //ok var r4c2 = c - b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c3 = c - c; //ok var r4c4 = c - d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c5 = c - e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c6 = c - f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d1 = d - a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d2 = d - b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d3 = d - c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d4 = d - d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d5 = d - e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d6 = d - f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4e1 = e - a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4e2 = e - b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4e3 = e - c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4e4 = e - d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4e5 = e - e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4e6 = e - f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4f1 = f - a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4f2 = f - b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4f3 = f - c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4f4 = f - d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4f5 = f - e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4f6 = f - f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4g1 = E.a - a; //ok var r4g2 = E.a - b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4g3 = E.a - c; //ok var r4g4 = E.a - d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4g5 = E.a - e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4g6 = E.a - f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4h1 = a - E.b; //ok var r4h2 = b - E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4h3 = c - E.b; //ok var r4h4 = d - E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4h5 = e - E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4h6 = f - E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator << var r5a1 = a << a; //ok var r5a2 = a << b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a3 = a << c; //ok var r5a4 = a << d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a5 = a << e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a6 = a << f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b1 = b << a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b2 = b << b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b3 = b << c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b4 = b << d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b5 = b << e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b6 = b << f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c1 = c << a; //ok var r5c2 = c << b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c3 = c << c; //ok var r5c4 = c << d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c5 = c << e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c6 = c << f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d1 = d << a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d2 = d << b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d3 = d << c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d4 = d << d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d5 = d << e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d6 = d << f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5e1 = e << a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5e2 = e << b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5e3 = e << c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5e4 = e << d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5e5 = e << e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5e6 = e << f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5f1 = f << a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5f2 = f << b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5f3 = f << c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5f4 = f << d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5f5 = f << e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5f6 = f << f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5g1 = E.a << a; //ok var r5g2 = E.a << b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5g3 = E.a << c; //ok var r5g4 = E.a << d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5g5 = E.a << e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5g6 = E.a << f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5h1 = a << E.b; //ok var r5h2 = b << E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5h3 = c << E.b; //ok var r5h4 = d << E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5h5 = e << E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5h6 = f << E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator >> var r6a1 = a >> a; //ok var r6a2 = a >> b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a3 = a >> c; //ok var r6a4 = a >> d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a5 = a >> e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a6 = a >> f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b1 = b >> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b2 = b >> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b3 = b >> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b4 = b >> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b5 = b >> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b6 = b >> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c1 = c >> a; //ok var r6c2 = c >> b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c3 = c >> c; //ok var r6c4 = c >> d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c5 = c >> e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c6 = c >> f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d1 = d >> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d2 = d >> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d3 = d >> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d4 = d >> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d5 = d >> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d6 = d >> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6e1 = e >> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6e2 = e >> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6e3 = e >> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6e4 = e >> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6e5 = e >> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6e6 = e >> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6f1 = f >> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6f2 = f >> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6f3 = f >> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6f4 = f >> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6f5 = f >> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6f6 = f >> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6g1 = E.a >> a; //ok var r6g2 = E.a >> b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6g3 = E.a >> c; //ok var r6g4 = E.a >> d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6g5 = E.a >> e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6g6 = E.a >> f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6h1 = a >> E.b; //ok var r6h2 = b >> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6h3 = c >> E.b; //ok var r6h4 = d >> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6h5 = e >> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6h6 = f >> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator >>> var r7a1 = a >>> a; //ok var r7a2 = a >>> b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a3 = a >>> c; //ok var r7a4 = a >>> d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a5 = a >>> e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a6 = a >>> f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b1 = b >>> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b2 = b >>> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b3 = b >>> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b4 = b >>> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b5 = b >>> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b6 = b >>> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c1 = c >>> a; //ok var r7c2 = c >>> b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c3 = c >>> c; //ok var r7c4 = c >>> d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c5 = c >>> e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c6 = c >>> f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d1 = d >>> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d2 = d >>> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d3 = d >>> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d4 = d >>> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d5 = d >>> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d6 = d >>> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7e1 = e >>> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7e2 = e >>> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7e3 = e >>> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7e4 = e >>> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7e5 = e >>> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7e6 = e >>> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7f1 = f >>> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7f2 = f >>> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7f3 = f >>> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7f4 = f >>> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7f5 = f >>> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7f6 = f >>> f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7g1 = E.a >>> a; //ok var r7g2 = E.a >>> b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7g3 = E.a >>> c; //ok var r7g4 = E.a >>> d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7g5 = E.a >>> e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7g6 = E.a >>> f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7h1 = a >>> E.b; //ok var r7h2 = b >>> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7h3 = c >>> E.b; //ok var r7h4 = d >>> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7h5 = e >>> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7h6 = f >>> E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator & var r8a1 = a & a; //ok var r8a2 = a & b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a3 = a & c; //ok var r8a4 = a & d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a5 = a & e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a6 = a & f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b1 = b & a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b2 = b & b; ~~~~~ !!! error TS2447: The '&' operator is not allowed for boolean types. Consider using '&&' instead. var r8b3 = b & c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b4 = b & d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b5 = b & e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b6 = b & f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c1 = c & a; //ok var r8c2 = c & b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c3 = c & c; //ok var r8c4 = c & d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c5 = c & e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c6 = c & f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d1 = d & a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d2 = d & b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d3 = d & c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d4 = d & d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d5 = d & e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d6 = d & f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8e1 = e & a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8e2 = e & b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8e3 = e & c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8e4 = e & d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8e5 = e & e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8e6 = e & f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8f1 = f & a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8f2 = f & b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8f3 = f & c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8f4 = f & d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8f5 = f & e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8f6 = f & f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8g1 = E.a & a; //ok var r8g2 = E.a & b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8g3 = E.a & c; //ok var r8g4 = E.a & d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8g5 = E.a & e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8g6 = E.a & f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8h1 = a & E.b; //ok var r8h2 = b & E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8h3 = c & E.b; //ok var r8h4 = d & E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8h5 = e & E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8h6 = f & E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator ^ var r9a1 = a ^ a; //ok var r9a2 = a ^ b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a3 = a ^ c; //ok var r9a4 = a ^ d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a5 = a ^ e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a6 = a ^ f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b1 = b ^ a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b2 = b ^ b; ~~~~~ !!! error TS2447: The '^' operator is not allowed for boolean types. Consider using '!==' instead. var r9b3 = b ^ c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b4 = b ^ d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b5 = b ^ e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b6 = b ^ f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c1 = c ^ a; //ok var r9c2 = c ^ b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c3 = c ^ c; //ok var r9c4 = c ^ d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c5 = c ^ e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c6 = c ^ f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d1 = d ^ a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d2 = d ^ b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d3 = d ^ c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d4 = d ^ d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d5 = d ^ e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d6 = d ^ f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9e1 = e ^ a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9e2 = e ^ b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9e3 = e ^ c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9e4 = e ^ d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9e5 = e ^ e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9e6 = e ^ f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9f1 = f ^ a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9f2 = f ^ b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9f3 = f ^ c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9f4 = f ^ d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9f5 = f ^ e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9f6 = f ^ f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9g1 = E.a ^ a; //ok var r9g2 = E.a ^ b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9g3 = E.a ^ c; //ok var r9g4 = E.a ^ d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9g5 = E.a ^ e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9g6 = E.a ^ f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9h1 = a ^ E.b; //ok var r9h2 = b ^ E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9h3 = c ^ E.b; //ok var r9h4 = d ^ E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9h5 = e ^ E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9h6 = f ^ E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // operator | var r10a1 = a | a; //ok var r10a2 = a | b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a3 = a | c; //ok var r10a4 = a | d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a5 = a | e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a6 = a | f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b1 = b | a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b2 = b | b; ~~~~~ !!! error TS2447: The '|' operator is not allowed for boolean types. Consider using '||' instead. var r10b3 = b | c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b4 = b | d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b5 = b | e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b6 = b | f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c1 = c | a; //ok var r10c2 = c | b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c3 = c | c; //ok var r10c4 = c | d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c5 = c | e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c6 = c | f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d1 = d | a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d2 = d | b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d3 = d | c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d4 = d | d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d5 = d | e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d6 = d | f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10e1 = e | a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10e2 = e | b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10e3 = e | c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10e4 = e | d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10e5 = e | e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10e6 = e | f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10f1 = f | a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10f2 = f | b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10f3 = f | c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10f4 = f | d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10f5 = f | e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10f6 = f | f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10g1 = E.a | a; //ok var r10g2 = E.a | b; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10g3 = E.a | c; //ok var r10g4 = E.a | d; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10g5 = E.a | e; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10g6 = E.a | f; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10h1 = a | E.b; //ok var r10h2 = b | E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10h3 = c | E.b; //ok var r10h4 = d | E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10h5 = e | E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10h6 = f | E.b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. \ No newline at end of file +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/arithmeticOperatorWithNullValueAndInvalidOperands.errors.txt b/tests/baselines/reference/arithmeticOperatorWithNullValueAndInvalidOperands.errors.txt index 16a0264a805..e352fbf9060 100644 --- a/tests/baselines/reference/arithmeticOperatorWithNullValueAndInvalidOperands.errors.txt +++ b/tests/baselines/reference/arithmeticOperatorWithNullValueAndInvalidOperands.errors.txt @@ -1,242 +1,242 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(9,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(9,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(9,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(10,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(10,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(10,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(11,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(11,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(13,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(11,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(13,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(13,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(14,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(14,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(14,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(15,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(15,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(15,16): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(17,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(17,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(17,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(18,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(18,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(18,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(19,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(19,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(19,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(21,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(22,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(23,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(26,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(26,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(26,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(27,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(27,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(27,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(28,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(28,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(30,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(28,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(30,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(30,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(31,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(31,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(31,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(32,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(32,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(32,16): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(34,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(34,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(34,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(35,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(35,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(35,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(36,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(36,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(36,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(38,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(39,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(40,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(43,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(43,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(43,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(44,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(44,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(44,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(45,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(45,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(45,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(47,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(48,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(48,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(48,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(49,16): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(51,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(51,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(51,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(52,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(52,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(52,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(53,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(53,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(55,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(53,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(55,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(55,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(56,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(56,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(56,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(57,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(57,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(57,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(60,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(60,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(60,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(61,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(61,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(61,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(62,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(62,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(62,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(64,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(65,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(65,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(65,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(66,16): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(68,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(68,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(68,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(69,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(69,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(69,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(70,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(70,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(72,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(70,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(72,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(72,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(73,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(73,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(73,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(74,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(74,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(74,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(77,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(77,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(77,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(78,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(78,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(78,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(79,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(79,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(81,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(79,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(81,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(81,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(82,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(82,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(82,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(83,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(83,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(83,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(85,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(85,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(85,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(86,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(86,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(86,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(87,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(87,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(89,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(87,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(89,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(89,20): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(90,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(90,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(90,18): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(91,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(91,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(91,18): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(94,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(94,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(94,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(95,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(95,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(95,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(96,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(96,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(98,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(96,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(98,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(98,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(99,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(99,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(99,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(100,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(100,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(100,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(102,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(102,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(102,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(103,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(103,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(103,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(104,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(104,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(106,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(104,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(106,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(106,20): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(107,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(107,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(107,18): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(108,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(108,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(108,18): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(111,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(111,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(111,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(112,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(112,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(112,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(113,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(113,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(115,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(113,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(115,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(115,18): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(116,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(116,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(116,18): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(117,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(117,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(117,18): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(119,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(119,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(119,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(120,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(120,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(120,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(121,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(121,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(123,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(121,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(123,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(123,21): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(124,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(124,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(124,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(125,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(125,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(125,19): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(128,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(128,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(128,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(129,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(129,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(129,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(130,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(130,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(132,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(130,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(132,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(132,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(133,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(133,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(133,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(134,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(134,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(134,16): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(136,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(136,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(136,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(137,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(137,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(137,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(138,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(138,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(140,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(138,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(140,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(140,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(141,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(141,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(141,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(142,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(142,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(142,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(145,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(145,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(145,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(146,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(146,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(146,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(147,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(147,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(149,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(147,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(149,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(149,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(150,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(150,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(150,16): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(151,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(151,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(151,16): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(153,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(153,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(153,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(154,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(154,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(154,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(155,12): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(155,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(157,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(155,19): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(157,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(157,19): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(158,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(158,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(158,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(159,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(159,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(159,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(162,13): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(162,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(162,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(163,13): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(163,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(163,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(164,13): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(164,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(166,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(164,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(166,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(166,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(167,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(167,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(167,17): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(168,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(168,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(168,17): error TS2531: Object is possibly 'null'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(170,13): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(170,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(170,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(171,13): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(171,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(171,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(172,13): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(172,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(174,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(172,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(174,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(174,20): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(175,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(175,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(175,18): error TS2531: Object is possibly 'null'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(176,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(176,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithNullValueAndInvalidOperands.ts(176,18): error TS2531: Object is possibly 'null'. @@ -253,31 +253,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a2 = null * b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a3 = null * c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b1 = a * null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r1b2 = b * null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r1b3 = c * null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -285,31 +285,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c2 = null * ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c3 = null * {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d1 = true * null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r1d2 = '' * null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r1d3 = {} * null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -318,31 +318,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a2 = null / b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a3 = null / c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b1 = a / null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r2b2 = b / null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r2b3 = c / null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -350,31 +350,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c2 = null / ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c3 = null / {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d1 = true / null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r2d2 = '' / null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r2d3 = {} / null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -383,31 +383,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a2 = null % b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a3 = null % c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b1 = a % null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r3b2 = b % null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r3b3 = c % null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -415,31 +415,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c2 = null % ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c3 = null % {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d1 = true % null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r3d2 = '' % null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r3d3 = {} % null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -448,31 +448,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a2 = null - b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a3 = null - c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b1 = a - null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r4b2 = b - null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r4b3 = c - null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -480,31 +480,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c2 = null - ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c3 = null - {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d1 = true - null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r4d2 = '' - null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r4d3 = {} - null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -513,31 +513,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a2 = null << b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a3 = null << c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b1 = a << null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r5b2 = b << null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r5b3 = c << null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -545,31 +545,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c2 = null << ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c3 = null << {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d1 = true << null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r5d2 = '' << null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r5d3 = {} << null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -578,31 +578,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a2 = null >> b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a3 = null >> c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b1 = a >> null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r6b2 = b >> null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r6b3 = c >> null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -610,31 +610,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c2 = null >> ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c3 = null >> {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d1 = true >> null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r6d2 = '' >> null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r6d3 = {} >> null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -643,31 +643,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a2 = null >>> b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a3 = null >>> c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b1 = a >>> null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r7b2 = b >>> null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r7b3 = c >>> null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -675,31 +675,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c2 = null >>> ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c3 = null >>> {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d1 = true >>> null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r7d2 = '' >>> null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r7d3 = {} >>> null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -708,31 +708,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a2 = null & b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a3 = null & c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b1 = a & null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r8b2 = b & null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r8b3 = c & null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -740,31 +740,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c2 = null & ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c3 = null & {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d1 = true & null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r8d2 = '' & null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r8d3 = {} & null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -773,31 +773,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a2 = null ^ b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a3 = null ^ c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b1 = a ^ null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r9b2 = b ^ null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r9b3 = c ^ null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -805,31 +805,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c2 = null ^ ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c3 = null ^ {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d1 = true ^ null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r9d2 = '' ^ null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r9d3 = {} ^ null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -838,31 +838,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a2 = null | b; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a3 = null | c; ~~~~ !!! error TS2531: Object is possibly 'null'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b1 = a | null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r10b2 = b | null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r10b3 = c | null; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. @@ -870,30 +870,30 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~ !!! error TS2531: Object is possibly 'null'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c2 = null | ''; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c3 = null | {}; ~~~~ !!! error TS2531: Object is possibly 'null'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d1 = true | null; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r10d2 = '' | null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. var r10d3 = {} | null; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~ !!! error TS2531: Object is possibly 'null'. \ No newline at end of file diff --git a/tests/baselines/reference/arithmeticOperatorWithTypeParameter.errors.txt b/tests/baselines/reference/arithmeticOperatorWithTypeParameter.errors.txt index a1de1f0c795..fc939a5216e 100644 --- a/tests/baselines/reference/arithmeticOperatorWithTypeParameter.errors.txt +++ b/tests/baselines/reference/arithmeticOperatorWithTypeParameter.errors.txt @@ -1,183 +1,183 @@ -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(9,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(10,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(11,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(12,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(13,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(14,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(15,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(16,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(17,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(18,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(20,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(21,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(22,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(23,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(24,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(25,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(26,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(27,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(28,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(29,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(31,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(31,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(32,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(32,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(33,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(33,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(34,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(34,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(35,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(35,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(36,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(36,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(37,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(37,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(38,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(38,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(39,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(39,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(40,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(40,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(42,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(42,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(43,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(43,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(44,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(44,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(45,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(45,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(46,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(46,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(47,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(47,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(48,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(48,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(49,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(49,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(50,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(50,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(51,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(51,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(53,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(54,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(55,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(56,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(57,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(58,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(59,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(60,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(61,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(62,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(64,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(65,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(66,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(67,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(68,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(69,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(70,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(71,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(72,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(73,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(75,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(75,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(76,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(76,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(77,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(77,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(78,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(78,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(79,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(79,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(80,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(80,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(81,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(81,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(82,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(82,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(83,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(83,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(84,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(84,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(86,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(86,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(87,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(87,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(88,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(88,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(89,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(89,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(90,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(90,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(91,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(91,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(92,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(92,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(93,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(93,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(94,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(94,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(95,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(95,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(97,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(97,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(98,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(98,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(99,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(99,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(100,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(100,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(101,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(101,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(102,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(102,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(103,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(103,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(104,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(104,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(105,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(105,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(106,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(106,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(108,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(108,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(109,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(109,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(110,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(110,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(111,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(111,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(112,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(112,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(113,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(113,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(114,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(114,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(115,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(115,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(116,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(116,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(117,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(117,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(119,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(119,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(120,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(120,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(121,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(121,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(122,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(122,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(123,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(123,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(124,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(124,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(125,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(125,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(126,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(126,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(127,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(127,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(128,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(128,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(9,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(10,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(11,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(12,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(13,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(14,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(15,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(16,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(17,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(18,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(20,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(21,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(22,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(23,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(24,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(25,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(26,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(27,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(28,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(29,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(31,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(31,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(32,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(32,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(33,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(33,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(34,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(34,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(35,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(35,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(36,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(36,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(37,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(37,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(38,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(38,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(39,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(39,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(40,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(40,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(42,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(42,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(43,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(43,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(44,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(44,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(45,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(45,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(46,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(46,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(47,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(47,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(48,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(48,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(49,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(49,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(50,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(50,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(51,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(51,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(53,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(54,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(55,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(56,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(57,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(58,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(59,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(60,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(61,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(62,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(64,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(65,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(66,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(67,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(68,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(69,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(70,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(71,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(72,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(73,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(75,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(75,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(76,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(76,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(77,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(77,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(78,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(78,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(79,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(79,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(80,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(80,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(81,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(81,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(82,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(82,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(83,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(83,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(84,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(84,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(86,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(86,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(87,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(87,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(88,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(88,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(89,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(89,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(90,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(90,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(91,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(91,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(92,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(92,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(93,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(93,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(94,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(94,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(95,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(95,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(97,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(97,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(98,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(98,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(99,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(99,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(100,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(100,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(101,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(101,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(102,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(102,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(103,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(103,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(104,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(104,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(105,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(105,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(106,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(106,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(108,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(108,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(109,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(109,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(110,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(110,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(111,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(111,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(112,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(112,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(113,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(113,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(114,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(114,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(115,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(115,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(116,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(116,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(117,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(117,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(119,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(119,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(120,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(120,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(121,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(121,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(122,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(122,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(123,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(123,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(124,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(124,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(125,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(125,22): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(126,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(126,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(127,16): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(127,20): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(128,17): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts(128,21): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithTypeParameter.ts (180 errors) ==== @@ -191,482 +191,482 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti var r1a1 = a * t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a2 = a / t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a3 = a % t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a4 = a - t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a5 = a << t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a6 = a >> t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a7 = a >>> t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a8 = a & t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a9 = a ^ t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a10 = a | t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a1 = t * a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a2 = t / a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a3 = t % a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a4 = t - a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a5 = t << a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a6 = t >> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a7 = t >>> a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a8 = t & a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a9 = t ^ a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a10 = t | a; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b1 = b * t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b2 = b / t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b3 = b % t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b4 = b - t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b5 = b << t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b6 = b >> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b7 = b >>> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b8 = b & t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b9 = b ^ t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b10 = b | t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b1 = t * b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b2 = t / b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b3 = t % b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b4 = t - b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b5 = t << b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b6 = t >> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b7 = t >>> b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b8 = t & b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b9 = t ^ b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b10 = t | b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c1 = c * t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c2 = c / t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c3 = c % t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c4 = c - t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c5 = c << t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c6 = c >> t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c7 = c >>> t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c8 = c & t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c9 = c ^ t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c10 = c | t; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c1 = t * c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c2 = t / c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c3 = t % c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c4 = t - c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c5 = t << c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c6 = t >> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c7 = t >>> c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c8 = t & c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c9 = t ^ c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c10 = t | c; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d1 = d * t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d2 = d / t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d3 = d % t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d4 = d - t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d5 = d << t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d6 = d >> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d7 = d >>> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d8 = d & t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d9 = d ^ t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d10 = d | t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d1 = t * d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d2 = t / d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d3 = t % d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d4 = t - d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d5 = t << d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d6 = t >> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d7 = t >>> d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d8 = t & d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d9 = t ^ d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d10 = t | d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e1 = e * t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e2 = e / t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e3 = e % t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e4 = e - t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e5 = e << t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e6 = e >> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e7 = e >>> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e8 = e & t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e9 = e ^ t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1e10 = e | t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e1 = t * e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e2 = t / e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e3 = t % e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e4 = t - e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e5 = t << e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e6 = t >> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e7 = t >>> e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e8 = t & e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e9 = t ^ e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2e10 = t | e; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f1 = t * t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f2 = t / t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f3 = t % t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f4 = t - t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f5 = t << t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f6 = t >> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f7 = t >>> t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f8 = t & t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f9 = t ^ t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1f10 = t | t; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. } \ No newline at end of file diff --git a/tests/baselines/reference/arithmeticOperatorWithUndefinedValueAndInvalidOperands.errors.txt b/tests/baselines/reference/arithmeticOperatorWithUndefinedValueAndInvalidOperands.errors.txt index 8a9d014f2c2..0482a511077 100644 --- a/tests/baselines/reference/arithmeticOperatorWithUndefinedValueAndInvalidOperands.errors.txt +++ b/tests/baselines/reference/arithmeticOperatorWithUndefinedValueAndInvalidOperands.errors.txt @@ -1,242 +1,242 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(9,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(9,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(9,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(10,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(10,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(10,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(11,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(11,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(13,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(11,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(13,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(13,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(14,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(14,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(14,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(15,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(15,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(15,16): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(17,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(17,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(17,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(18,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(18,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(18,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(19,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(19,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(19,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(21,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(21,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(22,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(22,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(23,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(23,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(26,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(26,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(26,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(27,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(27,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(27,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(28,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(28,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(30,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(28,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(30,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(30,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(31,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(31,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(31,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(32,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(32,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(32,16): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(34,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(34,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(34,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(35,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(35,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(35,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(36,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(36,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(36,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(38,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(38,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(39,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(39,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(40,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(40,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(43,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(43,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(43,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(44,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(44,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(44,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(45,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(45,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(45,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(47,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(47,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(48,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(48,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(48,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(49,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(49,16): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(51,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(51,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(51,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(52,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(52,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(52,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(53,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(53,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(55,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(53,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(55,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(55,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(56,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(56,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(56,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(57,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(57,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(57,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(60,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(60,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(60,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(61,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(61,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(61,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(62,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(62,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(62,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(64,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(64,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(65,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(65,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(65,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(66,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(66,16): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(68,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(68,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(68,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(69,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(69,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(69,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(70,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(70,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(72,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(70,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(72,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(72,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(73,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(73,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(73,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(74,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(74,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(74,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(77,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(77,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(77,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(78,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(78,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(78,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(79,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(79,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(81,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(79,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(81,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(81,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(82,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(82,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(82,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(83,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(83,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(83,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(85,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(85,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(85,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(86,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(86,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(86,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(87,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(87,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(89,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(87,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(89,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(89,20): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(90,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(90,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(90,18): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(91,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(91,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(91,18): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(94,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(94,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(94,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(95,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(95,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(95,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(96,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(96,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(98,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(96,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(98,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(98,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(99,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(99,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(99,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(100,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(100,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(100,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(102,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(102,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(102,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(103,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(103,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(103,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(104,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(104,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(106,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(104,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(106,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(106,20): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(107,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(107,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(107,18): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(108,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(108,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(108,18): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(111,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(111,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(111,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(112,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(112,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(112,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(113,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(113,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(115,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(113,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(115,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(115,18): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(116,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(116,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(116,18): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(117,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(117,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(117,18): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(119,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(119,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(119,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(120,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(120,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(120,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(121,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(121,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(123,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(121,26): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(123,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(123,21): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(124,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(124,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(124,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(125,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(125,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(125,19): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(128,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(128,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(128,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(129,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(129,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(129,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(130,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(130,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(132,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(130,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(132,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(132,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(133,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(133,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(133,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(134,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(134,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(134,16): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(136,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(136,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(136,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(137,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(137,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(137,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(138,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(138,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(140,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(138,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(140,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(140,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(141,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(141,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(141,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(142,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(142,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(142,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(145,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(145,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(145,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(146,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(146,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(146,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(147,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(147,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(149,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(147,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(149,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(149,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(150,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(150,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(150,16): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(151,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(151,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(151,16): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(153,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(153,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(153,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(154,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(154,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(154,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(155,12): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(155,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(157,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(155,24): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(157,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(157,19): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(158,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(158,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(158,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(159,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(159,12): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(159,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(162,13): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(162,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(162,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(163,13): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(163,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(163,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(164,13): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(164,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(166,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(164,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(166,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(166,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(167,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(167,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(167,17): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(168,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(168,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(168,17): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(170,13): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(170,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(170,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(171,13): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(171,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(171,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(172,13): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(172,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(174,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(172,25): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(174,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(174,20): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(175,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(175,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(175,18): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(176,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(176,13): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeticOperatorWithUndefinedValueAndInvalidOperands.ts(176,18): error TS2532: Object is possibly 'undefined'. @@ -253,31 +253,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a2 = undefined * b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1a3 = undefined * c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1b1 = a * undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r1b2 = b * undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r1b3 = c * undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -285,31 +285,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c2 = undefined * ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1c3 = undefined * {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r1d1 = true * undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r1d2 = '' * undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r1d3 = {} * undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -318,31 +318,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a2 = undefined / b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2a3 = undefined / c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2b1 = a / undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r2b2 = b / undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r2b3 = c / undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -350,31 +350,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c2 = undefined / ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2c3 = undefined / {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r2d1 = true / undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r2d2 = '' / undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r2d3 = {} / undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -383,31 +383,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a2 = undefined % b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3a3 = undefined % c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3b1 = a % undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r3b2 = b % undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r3b3 = c % undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -415,31 +415,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c2 = undefined % ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3c3 = undefined % {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r3d1 = true % undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r3d2 = '' % undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r3d3 = {} % undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -448,31 +448,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a2 = undefined - b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4a3 = undefined - c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4b1 = a - undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r4b2 = b - undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r4b3 = c - undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -480,31 +480,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c2 = undefined - ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4c3 = undefined - {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r4d1 = true - undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r4d2 = '' - undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r4d3 = {} - undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -513,31 +513,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a2 = undefined << b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5a3 = undefined << c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5b1 = a << undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r5b2 = b << undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r5b3 = c << undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -545,31 +545,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c2 = undefined << ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5c3 = undefined << {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r5d1 = true << undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r5d2 = '' << undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r5d3 = {} << undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -578,31 +578,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a2 = undefined >> b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6a3 = undefined >> c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6b1 = a >> undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r6b2 = b >> undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r6b3 = c >> undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -610,31 +610,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c2 = undefined >> ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6c3 = undefined >> {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r6d1 = true >> undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r6d2 = '' >> undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r6d3 = {} >> undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -643,31 +643,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a2 = undefined >>> b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7a3 = undefined >>> c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7b1 = a >>> undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r7b2 = b >>> undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r7b3 = c >>> undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -675,31 +675,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c2 = undefined >>> ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7c3 = undefined >>> {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r7d1 = true >>> undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r7d2 = '' >>> undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r7d3 = {} >>> undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -708,31 +708,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a2 = undefined & b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8a3 = undefined & c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8b1 = a & undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r8b2 = b & undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r8b3 = c & undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -740,31 +740,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c2 = undefined & ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8c3 = undefined & {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r8d1 = true & undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r8d2 = '' & undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r8d3 = {} & undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -773,31 +773,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a2 = undefined ^ b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9a3 = undefined ^ c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9b1 = a ^ undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r9b2 = b ^ undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r9b3 = c ^ undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -805,31 +805,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c2 = undefined ^ ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9c3 = undefined ^ {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r9d1 = true ^ undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r9d2 = '' ^ undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r9d3 = {} ^ undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -838,31 +838,31 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a2 = undefined | b; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10a3 = undefined | c; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10b1 = a | undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r10b2 = b | undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r10b3 = c | undefined; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. @@ -870,30 +870,30 @@ tests/cases/conformance/expressions/binaryOperators/arithmeticOperator/arithmeti ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c2 = undefined | ''; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10c3 = undefined | {}; ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. ~~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var r10d1 = true | undefined; ~~~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r10d2 = '' | undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. var r10d3 = {} | undefined; ~~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ~~~~~~~~~ !!! error TS2532: Object is possibly 'undefined'. \ No newline at end of file diff --git a/tests/baselines/reference/arityAndOrderCompatibility01.errors.txt b/tests/baselines/reference/arityAndOrderCompatibility01.errors.txt index f30dabd5689..50678ea4bb3 100644 --- a/tests/baselines/reference/arityAndOrderCompatibility01.errors.txt +++ b/tests/baselines/reference/arityAndOrderCompatibility01.errors.txt @@ -2,41 +2,32 @@ tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(15,12): erro tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(16,12): error TS2460: Type 'StrNum' has no property '2'. tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(17,5): error TS2461: Type '{ 0: string; 1: number; length: 2; }' is not an array type. tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(17,12): error TS2460: Type '{ 0: string; 1: number; length: 2; }' has no property '2'. -tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(18,5): error TS2322: Type '[string, number]' is not assignable to type '[number, number, number]'. - Property '2' is missing in type '[string, number]'. -tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(19,5): error TS2322: Type 'StrNum' is not assignable to type '[number, number, number]'. - Property '2' is missing in type 'StrNum'. -tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(20,5): error TS2322: Type '{ 0: string; 1: number; length: 2; }' is not assignable to type '[number, number, number]'. - Property '2' is missing in type '{ 0: string; 1: number; length: 2; }'. -tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(21,5): error TS2322: Type '[string, number]' is not assignable to type '[string, number, number]'. - Property '2' is missing in type '[string, number]'. -tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(22,5): error TS2322: Type 'StrNum' is not assignable to type '[string, number, number]'. - Property '2' is missing in type 'StrNum'. -tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(23,5): error TS2322: Type '{ 0: string; 1: number; length: 2; }' is not assignable to type '[string, number, number]'. - Property '2' is missing in type '{ 0: string; 1: number; length: 2; }'. +tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(18,5): error TS2741: Property '2' is missing in type '[string, number]' but required in type '[number, number, number]'. +tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(19,5): error TS2741: Property '2' is missing in type 'StrNum' but required in type '[number, number, number]'. +tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(20,5): error TS2740: Type '{ 0: string; 1: number; length: 2; }' is missing the following properties from type '[number, number, number]': 2, pop, push, concat, and 16 more. +tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(21,5): error TS2741: Property '2' is missing in type '[string, number]' but required in type '[string, number, number]'. +tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(22,5): error TS2741: Property '2' is missing in type 'StrNum' but required in type '[string, number, number]'. +tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(23,5): error TS2740: Type '{ 0: string; 1: number; length: 2; }' is missing the following properties from type '[string, number, number]': 2, pop, push, concat, and 16 more. tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(24,5): error TS2322: Type '[string, number]' is not assignable to type '[number]'. Types of property '0' are incompatible. Type 'string' is not assignable to type 'number'. tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(25,5): error TS2322: Type 'StrNum' is not assignable to type '[number]'. Types of property '0' are incompatible. Type 'string' is not assignable to type 'number'. -tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(26,5): error TS2322: Type '{ 0: string; 1: number; length: 2; }' is not assignable to type '[number]'. - Property 'pop' is missing in type '{ 0: string; 1: number; length: 2; }'. +tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(26,5): error TS2740: Type '{ 0: string; 1: number; length: 2; }' is missing the following properties from type '[number]': pop, push, concat, join, and 15 more. tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(27,5): error TS2322: Type '[string, number]' is not assignable to type '[string]'. Types of property 'length' are incompatible. Type '2' is not assignable to type '1'. tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(28,5): error TS2322: Type 'StrNum' is not assignable to type '[string]'. Types of property 'length' are incompatible. Type '2' is not assignable to type '1'. -tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(29,5): error TS2322: Type '{ 0: string; 1: number; length: 2; }' is not assignable to type '[string]'. - Property 'pop' is missing in type '{ 0: string; 1: number; length: 2; }'. +tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(29,5): error TS2740: Type '{ 0: string; 1: number; length: 2; }' is missing the following properties from type '[string]': pop, push, concat, join, and 15 more. tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(30,5): error TS2322: Type '[string, number]' is not assignable to type '[number, string]'. Type 'string' is not assignable to type 'number'. tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(31,5): error TS2322: Type 'StrNum' is not assignable to type '[number, string]'. Types of property '0' are incompatible. Type 'string' is not assignable to type 'number'. -tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(32,5): error TS2322: Type '{ 0: string; 1: number; length: 2; }' is not assignable to type '[number, string]'. - Property 'pop' is missing in type '{ 0: string; 1: number; length: 2; }'. +tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(32,5): error TS2740: Type '{ 0: string; 1: number; length: 2; }' is missing the following properties from type '[number, string]': pop, push, concat, join, and 15 more. ==== tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts (19 errors) ==== @@ -67,28 +58,22 @@ tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(32,5): error !!! error TS2460: Type '{ 0: string; 1: number; length: 2; }' has no property '2'. var j1: [number, number, number] = x; ~~ -!!! error TS2322: Type '[string, number]' is not assignable to type '[number, number, number]'. -!!! error TS2322: Property '2' is missing in type '[string, number]'. +!!! error TS2741: Property '2' is missing in type '[string, number]' but required in type '[number, number, number]'. var j2: [number, number, number] = y; ~~ -!!! error TS2322: Type 'StrNum' is not assignable to type '[number, number, number]'. -!!! error TS2322: Property '2' is missing in type 'StrNum'. +!!! error TS2741: Property '2' is missing in type 'StrNum' but required in type '[number, number, number]'. var j3: [number, number, number] = z; ~~ -!!! error TS2322: Type '{ 0: string; 1: number; length: 2; }' is not assignable to type '[number, number, number]'. -!!! error TS2322: Property '2' is missing in type '{ 0: string; 1: number; length: 2; }'. +!!! error TS2740: Type '{ 0: string; 1: number; length: 2; }' is missing the following properties from type '[number, number, number]': 2, pop, push, concat, and 16 more. var k1: [string, number, number] = x; ~~ -!!! error TS2322: Type '[string, number]' is not assignable to type '[string, number, number]'. -!!! error TS2322: Property '2' is missing in type '[string, number]'. +!!! error TS2741: Property '2' is missing in type '[string, number]' but required in type '[string, number, number]'. var k2: [string, number, number] = y; ~~ -!!! error TS2322: Type 'StrNum' is not assignable to type '[string, number, number]'. -!!! error TS2322: Property '2' is missing in type 'StrNum'. +!!! error TS2741: Property '2' is missing in type 'StrNum' but required in type '[string, number, number]'. var k3: [string, number, number] = z; ~~ -!!! error TS2322: Type '{ 0: string; 1: number; length: 2; }' is not assignable to type '[string, number, number]'. -!!! error TS2322: Property '2' is missing in type '{ 0: string; 1: number; length: 2; }'. +!!! error TS2740: Type '{ 0: string; 1: number; length: 2; }' is missing the following properties from type '[string, number, number]': 2, pop, push, concat, and 16 more. var l1: [number] = x; ~~ !!! error TS2322: Type '[string, number]' is not assignable to type '[number]'. @@ -101,8 +86,7 @@ tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(32,5): error !!! error TS2322: Type 'string' is not assignable to type 'number'. var l3: [number] = z; ~~ -!!! error TS2322: Type '{ 0: string; 1: number; length: 2; }' is not assignable to type '[number]'. -!!! error TS2322: Property 'pop' is missing in type '{ 0: string; 1: number; length: 2; }'. +!!! error TS2740: Type '{ 0: string; 1: number; length: 2; }' is missing the following properties from type '[number]': pop, push, concat, join, and 15 more. var m1: [string] = x; ~~ !!! error TS2322: Type '[string, number]' is not assignable to type '[string]'. @@ -115,8 +99,7 @@ tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(32,5): error !!! error TS2322: Type '2' is not assignable to type '1'. var m3: [string] = z; ~~ -!!! error TS2322: Type '{ 0: string; 1: number; length: 2; }' is not assignable to type '[string]'. -!!! error TS2322: Property 'pop' is missing in type '{ 0: string; 1: number; length: 2; }'. +!!! error TS2740: Type '{ 0: string; 1: number; length: 2; }' is missing the following properties from type '[string]': pop, push, concat, join, and 15 more. var n1: [number, string] = x; ~~ !!! error TS2322: Type '[string, number]' is not assignable to type '[number, string]'. @@ -128,8 +111,7 @@ tests/cases/conformance/types/tuple/arityAndOrderCompatibility01.ts(32,5): error !!! error TS2322: Type 'string' is not assignable to type 'number'. var n3: [number, string] = z; ~~ -!!! error TS2322: Type '{ 0: string; 1: number; length: 2; }' is not assignable to type '[number, string]'. -!!! error TS2322: Property 'pop' is missing in type '{ 0: string; 1: number; length: 2; }'. +!!! error TS2740: Type '{ 0: string; 1: number; length: 2; }' is missing the following properties from type '[number, string]': pop, push, concat, join, and 15 more. var o1: [string, number] = x; var o2: [string, number] = y; var o3: [string, number] = y; diff --git a/tests/baselines/reference/arrayAssignmentTest1.errors.txt b/tests/baselines/reference/arrayAssignmentTest1.errors.txt index e07306b19b2..4ee34fcf736 100644 --- a/tests/baselines/reference/arrayAssignmentTest1.errors.txt +++ b/tests/baselines/reference/arrayAssignmentTest1.errors.txt @@ -1,50 +1,31 @@ -tests/cases/compiler/arrayAssignmentTest1.ts(46,5): error TS2322: Type 'undefined[]' is not assignable to type 'I1'. - Property 'IM1' is missing in type 'undefined[]'. -tests/cases/compiler/arrayAssignmentTest1.ts(47,5): error TS2322: Type 'undefined[]' is not assignable to type 'C1'. - Property 'IM1' is missing in type 'undefined[]'. -tests/cases/compiler/arrayAssignmentTest1.ts(48,5): error TS2322: Type 'undefined[]' is not assignable to type 'C2'. - Property 'C2M1' is missing in type 'undefined[]'. -tests/cases/compiler/arrayAssignmentTest1.ts(49,5): error TS2322: Type 'undefined[]' is not assignable to type 'C3'. - Property 'CM3M1' is missing in type 'undefined[]'. +tests/cases/compiler/arrayAssignmentTest1.ts(46,5): error TS2741: Property 'IM1' is missing in type 'undefined[]' but required in type 'I1'. +tests/cases/compiler/arrayAssignmentTest1.ts(47,5): error TS2739: Type 'undefined[]' is missing the following properties from type 'C1': IM1, C1M1 +tests/cases/compiler/arrayAssignmentTest1.ts(48,5): error TS2739: Type 'undefined[]' is missing the following properties from type 'C2': C2M1, IM1, C1M1 +tests/cases/compiler/arrayAssignmentTest1.ts(49,5): error TS2741: Property 'CM3M1' is missing in type 'undefined[]' but required in type 'C3'. tests/cases/compiler/arrayAssignmentTest1.ts(60,1): error TS2322: Type 'C3[]' is not assignable to type 'I1[]'. - Type 'C3' is not assignable to type 'I1'. - Property 'IM1' is missing in type 'C3'. + Property 'IM1' is missing in type 'C3' but required in type 'I1'. tests/cases/compiler/arrayAssignmentTest1.ts(64,1): error TS2322: Type 'I1[]' is not assignable to type 'C1[]'. - Type 'I1' is not assignable to type 'C1'. - Property 'C1M1' is missing in type 'I1'. + Property 'C1M1' is missing in type 'I1' but required in type 'C1'. tests/cases/compiler/arrayAssignmentTest1.ts(65,1): error TS2322: Type 'C3[]' is not assignable to type 'C1[]'. - Type 'C3' is not assignable to type 'C1'. - Property 'IM1' is missing in type 'C3'. + Type 'C3' is missing the following properties from type 'C1': IM1, C1M1 tests/cases/compiler/arrayAssignmentTest1.ts(68,1): error TS2322: Type 'C1[]' is not assignable to type 'C2[]'. - Type 'C1' is not assignable to type 'C2'. - Property 'C2M1' is missing in type 'C1'. + Property 'C2M1' is missing in type 'C1' but required in type 'C2'. tests/cases/compiler/arrayAssignmentTest1.ts(69,1): error TS2322: Type 'I1[]' is not assignable to type 'C2[]'. - Type 'I1' is not assignable to type 'C2'. - Property 'C2M1' is missing in type 'I1'. + Type 'I1' is missing the following properties from type 'C2': C2M1, C1M1 tests/cases/compiler/arrayAssignmentTest1.ts(70,1): error TS2322: Type 'C3[]' is not assignable to type 'C2[]'. - Type 'C3' is not assignable to type 'C2'. - Property 'C2M1' is missing in type 'C3'. + Type 'C3' is missing the following properties from type 'C2': C2M1, IM1, C1M1 tests/cases/compiler/arrayAssignmentTest1.ts(75,1): error TS2322: Type 'C2[]' is not assignable to type 'C3[]'. - Type 'C2' is not assignable to type 'C3'. - Property 'CM3M1' is missing in type 'C2'. + Property 'CM3M1' is missing in type 'C2' but required in type 'C3'. tests/cases/compiler/arrayAssignmentTest1.ts(76,1): error TS2322: Type 'C1[]' is not assignable to type 'C3[]'. - Type 'C1' is not assignable to type 'C3'. - Property 'CM3M1' is missing in type 'C1'. + Property 'CM3M1' is missing in type 'C1' but required in type 'C3'. tests/cases/compiler/arrayAssignmentTest1.ts(77,1): error TS2322: Type 'I1[]' is not assignable to type 'C3[]'. - Type 'I1' is not assignable to type 'C3'. - Property 'CM3M1' is missing in type 'I1'. -tests/cases/compiler/arrayAssignmentTest1.ts(79,1): error TS2322: Type '() => C1' is not assignable to type 'any[]'. - Property 'pop' is missing in type '() => C1'. -tests/cases/compiler/arrayAssignmentTest1.ts(80,1): error TS2322: Type '{ one: number; }' is not assignable to type 'any[]'. - Property 'length' is missing in type '{ one: number; }'. -tests/cases/compiler/arrayAssignmentTest1.ts(82,1): error TS2322: Type 'C1' is not assignable to type 'any[]'. - Property 'length' is missing in type 'C1'. -tests/cases/compiler/arrayAssignmentTest1.ts(83,1): error TS2322: Type 'C2' is not assignable to type 'any[]'. - Property 'length' is missing in type 'C2'. -tests/cases/compiler/arrayAssignmentTest1.ts(84,1): error TS2322: Type 'C3' is not assignable to type 'any[]'. - Property 'length' is missing in type 'C3'. -tests/cases/compiler/arrayAssignmentTest1.ts(85,1): error TS2322: Type 'I1' is not assignable to type 'any[]'. - Property 'length' is missing in type 'I1'. + Property 'CM3M1' is missing in type 'I1' but required in type 'C3'. +tests/cases/compiler/arrayAssignmentTest1.ts(79,1): error TS2740: Type '() => C1' is missing the following properties from type 'any[]': pop, push, concat, join, and 15 more. +tests/cases/compiler/arrayAssignmentTest1.ts(80,1): error TS2740: Type '{ one: number; }' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. +tests/cases/compiler/arrayAssignmentTest1.ts(82,1): error TS2740: Type 'C1' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. +tests/cases/compiler/arrayAssignmentTest1.ts(83,1): error TS2740: Type 'C2' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. +tests/cases/compiler/arrayAssignmentTest1.ts(84,1): error TS2740: Type 'C3' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. +tests/cases/compiler/arrayAssignmentTest1.ts(85,1): error TS2740: Type 'I1' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. ==== tests/cases/compiler/arrayAssignmentTest1.ts (19 errors) ==== @@ -95,20 +76,18 @@ tests/cases/compiler/arrayAssignmentTest1.ts(85,1): error TS2322: Type 'I1' is n var i1_error: I1 = []; // should be an error - is ~~~~~~~~ -!!! error TS2322: Type 'undefined[]' is not assignable to type 'I1'. -!!! error TS2322: Property 'IM1' is missing in type 'undefined[]'. +!!! error TS2741: Property 'IM1' is missing in type 'undefined[]' but required in type 'I1'. +!!! related TS2728 tests/cases/compiler/arrayAssignmentTest1.ts:2:2: 'IM1' is declared here. var c1_error: C1 = []; // should be an error - is ~~~~~~~~ -!!! error TS2322: Type 'undefined[]' is not assignable to type 'C1'. -!!! error TS2322: Property 'IM1' is missing in type 'undefined[]'. +!!! error TS2739: Type 'undefined[]' is missing the following properties from type 'C1': IM1, C1M1 var c2_error: C2 = []; // should be an error - is ~~~~~~~~ -!!! error TS2322: Type 'undefined[]' is not assignable to type 'C2'. -!!! error TS2322: Property 'C2M1' is missing in type 'undefined[]'. +!!! error TS2739: Type 'undefined[]' is missing the following properties from type 'C2': C2M1, IM1, C1M1 var c3_error: C3 = []; // should be an error - is ~~~~~~~~ -!!! error TS2322: Type 'undefined[]' is not assignable to type 'C3'. -!!! error TS2322: Property 'CM3M1' is missing in type 'undefined[]'. +!!! error TS2741: Property 'CM3M1' is missing in type 'undefined[]' but required in type 'C3'. +!!! related TS2728 tests/cases/compiler/arrayAssignmentTest1.ts:14:5: 'CM3M1' is declared here. arr_any = arr_i1; // should be ok - is @@ -122,38 +101,35 @@ tests/cases/compiler/arrayAssignmentTest1.ts(85,1): error TS2322: Type 'I1' is n arr_i1 = arr_c3; // should be an error - is ~~~~~~ !!! error TS2322: Type 'C3[]' is not assignable to type 'I1[]'. -!!! error TS2322: Type 'C3' is not assignable to type 'I1'. -!!! error TS2322: Property 'IM1' is missing in type 'C3'. +!!! error TS2322: Property 'IM1' is missing in type 'C3' but required in type 'I1'. +!!! related TS2728 tests/cases/compiler/arrayAssignmentTest1.ts:2:2: 'IM1' is declared here. arr_c1 = arr_c1; // should be ok - subtype relationship - is arr_c1 = arr_c2; // should be ok - subtype relationship - is arr_c1 = arr_i1; // should be an error - is ~~~~~~ !!! error TS2322: Type 'I1[]' is not assignable to type 'C1[]'. -!!! error TS2322: Type 'I1' is not assignable to type 'C1'. -!!! error TS2322: Property 'C1M1' is missing in type 'I1'. +!!! error TS2322: Property 'C1M1' is missing in type 'I1' but required in type 'C1'. +!!! related TS2728 tests/cases/compiler/arrayAssignmentTest1.ts:7:2: 'C1M1' is declared here. arr_c1 = arr_c3; // should be an error - is ~~~~~~ !!! error TS2322: Type 'C3[]' is not assignable to type 'C1[]'. -!!! error TS2322: Type 'C3' is not assignable to type 'C1'. -!!! error TS2322: Property 'IM1' is missing in type 'C3'. +!!! error TS2322: Type 'C3' is missing the following properties from type 'C1': IM1, C1M1 arr_c2 = arr_c2; // should be ok - subtype relationship - is arr_c2 = arr_c1; // should be an error - subtype relationship - is ~~~~~~ !!! error TS2322: Type 'C1[]' is not assignable to type 'C2[]'. -!!! error TS2322: Type 'C1' is not assignable to type 'C2'. -!!! error TS2322: Property 'C2M1' is missing in type 'C1'. +!!! error TS2322: Property 'C2M1' is missing in type 'C1' but required in type 'C2'. +!!! related TS2728 tests/cases/compiler/arrayAssignmentTest1.ts:10:5: 'C2M1' is declared here. arr_c2 = arr_i1; // should be an error - subtype relationship - is ~~~~~~ !!! error TS2322: Type 'I1[]' is not assignable to type 'C2[]'. -!!! error TS2322: Type 'I1' is not assignable to type 'C2'. -!!! error TS2322: Property 'C2M1' is missing in type 'I1'. +!!! error TS2322: Type 'I1' is missing the following properties from type 'C2': C2M1, C1M1 arr_c2 = arr_c3; // should be an error - is ~~~~~~ !!! error TS2322: Type 'C3[]' is not assignable to type 'C2[]'. -!!! error TS2322: Type 'C3' is not assignable to type 'C2'. -!!! error TS2322: Property 'C2M1' is missing in type 'C3'. +!!! error TS2322: Type 'C3' is missing the following properties from type 'C2': C2M1, IM1, C1M1 // "clean up bug" occurs at this point // if you move these three expressions to another file, they raise an error @@ -161,41 +137,35 @@ tests/cases/compiler/arrayAssignmentTest1.ts(85,1): error TS2322: Type 'I1' is n arr_c3 = arr_c2_2; // should be an error - is ~~~~~~ !!! error TS2322: Type 'C2[]' is not assignable to type 'C3[]'. -!!! error TS2322: Type 'C2' is not assignable to type 'C3'. -!!! error TS2322: Property 'CM3M1' is missing in type 'C2'. +!!! error TS2322: Property 'CM3M1' is missing in type 'C2' but required in type 'C3'. +!!! related TS2728 tests/cases/compiler/arrayAssignmentTest1.ts:14:5: 'CM3M1' is declared here. arr_c3 = arr_c1_2; // should be an error - is ~~~~~~ !!! error TS2322: Type 'C1[]' is not assignable to type 'C3[]'. -!!! error TS2322: Type 'C1' is not assignable to type 'C3'. -!!! error TS2322: Property 'CM3M1' is missing in type 'C1'. +!!! error TS2322: Property 'CM3M1' is missing in type 'C1' but required in type 'C3'. +!!! related TS2728 tests/cases/compiler/arrayAssignmentTest1.ts:14:5: 'CM3M1' is declared here. arr_c3 = arr_i1_2; // should be an error - is ~~~~~~ !!! error TS2322: Type 'I1[]' is not assignable to type 'C3[]'. -!!! error TS2322: Type 'I1' is not assignable to type 'C3'. -!!! error TS2322: Property 'CM3M1' is missing in type 'I1'. +!!! error TS2322: Property 'CM3M1' is missing in type 'I1' but required in type 'C3'. +!!! related TS2728 tests/cases/compiler/arrayAssignmentTest1.ts:14:5: 'CM3M1' is declared here. arr_any = f1; // should be an error - is ~~~~~~~ -!!! error TS2322: Type '() => C1' is not assignable to type 'any[]'. -!!! error TS2322: Property 'pop' is missing in type '() => C1'. +!!! error TS2740: Type '() => C1' is missing the following properties from type 'any[]': pop, push, concat, join, and 15 more. arr_any = o1; // should be an error - is ~~~~~~~ -!!! error TS2322: Type '{ one: number; }' is not assignable to type 'any[]'. -!!! error TS2322: Property 'length' is missing in type '{ one: number; }'. +!!! error TS2740: Type '{ one: number; }' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. arr_any = a1; // should be ok - is arr_any = c1; // should be an error - is ~~~~~~~ -!!! error TS2322: Type 'C1' is not assignable to type 'any[]'. -!!! error TS2322: Property 'length' is missing in type 'C1'. +!!! error TS2740: Type 'C1' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. arr_any = c2; // should be an error - is ~~~~~~~ -!!! error TS2322: Type 'C2' is not assignable to type 'any[]'. -!!! error TS2322: Property 'length' is missing in type 'C2'. +!!! error TS2740: Type 'C2' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. arr_any = c3; // should be an error - is ~~~~~~~ -!!! error TS2322: Type 'C3' is not assignable to type 'any[]'. -!!! error TS2322: Property 'length' is missing in type 'C3'. +!!! error TS2740: Type 'C3' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. arr_any = i1; // should be an error - is ~~~~~~~ -!!! error TS2322: Type 'I1' is not assignable to type 'any[]'. -!!! error TS2322: Property 'length' is missing in type 'I1'. \ No newline at end of file +!!! error TS2740: Type 'I1' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. \ No newline at end of file diff --git a/tests/baselines/reference/arrayAssignmentTest1.js b/tests/baselines/reference/arrayAssignmentTest1.js index cf848855e5d..baf1e8bfa3a 100644 --- a/tests/baselines/reference/arrayAssignmentTest1.js +++ b/tests/baselines/reference/arrayAssignmentTest1.js @@ -92,7 +92,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; } diff --git a/tests/baselines/reference/arrayAssignmentTest2.errors.txt b/tests/baselines/reference/arrayAssignmentTest2.errors.txt index eca2f8ad6f5..4333dd119d6 100644 --- a/tests/baselines/reference/arrayAssignmentTest2.errors.txt +++ b/tests/baselines/reference/arrayAssignmentTest2.errors.txt @@ -1,26 +1,16 @@ tests/cases/compiler/arrayAssignmentTest2.ts(47,1): error TS2322: Type 'C2[]' is not assignable to type 'C3[]'. - Type 'C2' is not assignable to type 'C3'. - Property 'CM3M1' is missing in type 'C2'. + Property 'CM3M1' is missing in type 'C2' but required in type 'C3'. tests/cases/compiler/arrayAssignmentTest2.ts(48,1): error TS2322: Type 'C1[]' is not assignable to type 'C3[]'. - Type 'C1' is not assignable to type 'C3'. - Property 'CM3M1' is missing in type 'C1'. + Property 'CM3M1' is missing in type 'C1' but required in type 'C3'. tests/cases/compiler/arrayAssignmentTest2.ts(49,1): error TS2322: Type 'I1[]' is not assignable to type 'C3[]'. - Type 'I1' is not assignable to type 'C3'. - Property 'CM3M1' is missing in type 'I1'. -tests/cases/compiler/arrayAssignmentTest2.ts(51,1): error TS2322: Type '() => C1' is not assignable to type 'any[]'. - Property 'pop' is missing in type '() => C1'. -tests/cases/compiler/arrayAssignmentTest2.ts(52,1): error TS2322: Type '() => any' is not assignable to type 'any[]'. - Property 'pop' is missing in type '() => any'. -tests/cases/compiler/arrayAssignmentTest2.ts(53,1): error TS2322: Type '{ one: number; }' is not assignable to type 'any[]'. - Property 'length' is missing in type '{ one: number; }'. -tests/cases/compiler/arrayAssignmentTest2.ts(55,1): error TS2322: Type 'C1' is not assignable to type 'any[]'. - Property 'length' is missing in type 'C1'. -tests/cases/compiler/arrayAssignmentTest2.ts(56,1): error TS2322: Type 'C2' is not assignable to type 'any[]'. - Property 'length' is missing in type 'C2'. -tests/cases/compiler/arrayAssignmentTest2.ts(57,1): error TS2322: Type 'C3' is not assignable to type 'any[]'. - Property 'length' is missing in type 'C3'. -tests/cases/compiler/arrayAssignmentTest2.ts(58,1): error TS2322: Type 'I1' is not assignable to type 'any[]'. - Property 'length' is missing in type 'I1'. + Property 'CM3M1' is missing in type 'I1' but required in type 'C3'. +tests/cases/compiler/arrayAssignmentTest2.ts(51,1): error TS2740: Type '() => C1' is missing the following properties from type 'any[]': pop, push, concat, join, and 15 more. +tests/cases/compiler/arrayAssignmentTest2.ts(52,1): error TS2740: Type '() => any' is missing the following properties from type 'any[]': pop, push, concat, join, and 15 more. +tests/cases/compiler/arrayAssignmentTest2.ts(53,1): error TS2740: Type '{ one: number; }' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. +tests/cases/compiler/arrayAssignmentTest2.ts(55,1): error TS2740: Type 'C1' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. +tests/cases/compiler/arrayAssignmentTest2.ts(56,1): error TS2740: Type 'C2' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. +tests/cases/compiler/arrayAssignmentTest2.ts(57,1): error TS2740: Type 'C3' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. +tests/cases/compiler/arrayAssignmentTest2.ts(58,1): error TS2740: Type 'I1' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. ==== tests/cases/compiler/arrayAssignmentTest2.ts (10 errors) ==== @@ -73,46 +63,39 @@ tests/cases/compiler/arrayAssignmentTest2.ts(58,1): error TS2322: Type 'I1' is n arr_c3 = arr_c2_2; // should be an error - is ~~~~~~ !!! error TS2322: Type 'C2[]' is not assignable to type 'C3[]'. -!!! error TS2322: Type 'C2' is not assignable to type 'C3'. -!!! error TS2322: Property 'CM3M1' is missing in type 'C2'. +!!! error TS2322: Property 'CM3M1' is missing in type 'C2' but required in type 'C3'. +!!! related TS2728 tests/cases/compiler/arrayAssignmentTest2.ts:14:2: 'CM3M1' is declared here. arr_c3 = arr_c1_2; // should be an error - is ~~~~~~ !!! error TS2322: Type 'C1[]' is not assignable to type 'C3[]'. -!!! error TS2322: Type 'C1' is not assignable to type 'C3'. -!!! error TS2322: Property 'CM3M1' is missing in type 'C1'. +!!! error TS2322: Property 'CM3M1' is missing in type 'C1' but required in type 'C3'. +!!! related TS2728 tests/cases/compiler/arrayAssignmentTest2.ts:14:2: 'CM3M1' is declared here. arr_c3 = arr_i1_2; // should be an error - is ~~~~~~ !!! error TS2322: Type 'I1[]' is not assignable to type 'C3[]'. -!!! error TS2322: Type 'I1' is not assignable to type 'C3'. -!!! error TS2322: Property 'CM3M1' is missing in type 'I1'. +!!! error TS2322: Property 'CM3M1' is missing in type 'I1' but required in type 'C3'. +!!! related TS2728 tests/cases/compiler/arrayAssignmentTest2.ts:14:2: 'CM3M1' is declared here. arr_any = f1; // should be an error - is ~~~~~~~ -!!! error TS2322: Type '() => C1' is not assignable to type 'any[]'. -!!! error TS2322: Property 'pop' is missing in type '() => C1'. +!!! error TS2740: Type '() => C1' is missing the following properties from type 'any[]': pop, push, concat, join, and 15 more. arr_any = function () { return null;} // should be an error - is ~~~~~~~ -!!! error TS2322: Type '() => any' is not assignable to type 'any[]'. -!!! error TS2322: Property 'pop' is missing in type '() => any'. +!!! error TS2740: Type '() => any' is missing the following properties from type 'any[]': pop, push, concat, join, and 15 more. arr_any = o1; // should be an error - is ~~~~~~~ -!!! error TS2322: Type '{ one: number; }' is not assignable to type 'any[]'. -!!! error TS2322: Property 'length' is missing in type '{ one: number; }'. +!!! error TS2740: Type '{ one: number; }' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. arr_any = a1; // should be ok - is arr_any = c1; // should be an error - is ~~~~~~~ -!!! error TS2322: Type 'C1' is not assignable to type 'any[]'. -!!! error TS2322: Property 'length' is missing in type 'C1'. +!!! error TS2740: Type 'C1' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. arr_any = c2; // should be an error - is ~~~~~~~ -!!! error TS2322: Type 'C2' is not assignable to type 'any[]'. -!!! error TS2322: Property 'length' is missing in type 'C2'. +!!! error TS2740: Type 'C2' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. arr_any = c3; // should be an error - is ~~~~~~~ -!!! error TS2322: Type 'C3' is not assignable to type 'any[]'. -!!! error TS2322: Property 'length' is missing in type 'C3'. +!!! error TS2740: Type 'C3' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. arr_any = i1; // should be an error - is ~~~~~~~ -!!! error TS2322: Type 'I1' is not assignable to type 'any[]'. -!!! error TS2322: Property 'length' is missing in type 'I1'. +!!! error TS2740: Type 'I1' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. \ No newline at end of file diff --git a/tests/baselines/reference/arrayAssignmentTest2.js b/tests/baselines/reference/arrayAssignmentTest2.js index 81176c8284f..5b1a655d781 100644 --- a/tests/baselines/reference/arrayAssignmentTest2.js +++ b/tests/baselines/reference/arrayAssignmentTest2.js @@ -66,7 +66,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; } diff --git a/tests/baselines/reference/arrayAssignmentTest3.errors.txt b/tests/baselines/reference/arrayAssignmentTest3.errors.txt index 31347782c5d..04b49ff6daf 100644 --- a/tests/baselines/reference/arrayAssignmentTest3.errors.txt +++ b/tests/baselines/reference/arrayAssignmentTest3.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/arrayAssignmentTest3.ts(12,25): error TS2345: Argument of type 'B' is not assignable to parameter of type 'B[]'. - Property 'length' is missing in type 'B'. + Type 'B' is missing the following properties from type 'B[]': length, pop, push, concat, and 16 more. ==== tests/cases/compiler/arrayAssignmentTest3.ts (1 errors) ==== @@ -17,6 +17,6 @@ tests/cases/compiler/arrayAssignmentTest3.ts(12,25): error TS2345: Argument of t var xx = new a(null, 7, new B()); ~~~~~~~ !!! error TS2345: Argument of type 'B' is not assignable to parameter of type 'B[]'. -!!! error TS2345: Property 'length' is missing in type 'B'. +!!! error TS2345: Type 'B' is missing the following properties from type 'B[]': length, pop, push, concat, and 16 more. \ No newline at end of file diff --git a/tests/baselines/reference/arrayAssignmentTest4.errors.txt b/tests/baselines/reference/arrayAssignmentTest4.errors.txt index 2546c6abf04..3e1c6c3de12 100644 --- a/tests/baselines/reference/arrayAssignmentTest4.errors.txt +++ b/tests/baselines/reference/arrayAssignmentTest4.errors.txt @@ -1,7 +1,5 @@ -tests/cases/compiler/arrayAssignmentTest4.ts(22,1): error TS2322: Type '() => any' is not assignable to type 'any[]'. - Property 'pop' is missing in type '() => any'. -tests/cases/compiler/arrayAssignmentTest4.ts(23,1): error TS2322: Type 'C3' is not assignable to type 'any[]'. - Property 'length' is missing in type 'C3'. +tests/cases/compiler/arrayAssignmentTest4.ts(22,1): error TS2740: Type '() => any' is missing the following properties from type 'any[]': pop, push, concat, join, and 15 more. +tests/cases/compiler/arrayAssignmentTest4.ts(23,1): error TS2740: Type 'C3' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. ==== tests/cases/compiler/arrayAssignmentTest4.ts (2 errors) ==== @@ -28,10 +26,8 @@ tests/cases/compiler/arrayAssignmentTest4.ts(23,1): error TS2322: Type 'C3' is n arr_any = function () { return null;} // should be an error - is ~~~~~~~ -!!! error TS2322: Type '() => any' is not assignable to type 'any[]'. -!!! error TS2322: Property 'pop' is missing in type '() => any'. +!!! error TS2740: Type '() => any' is missing the following properties from type 'any[]': pop, push, concat, join, and 15 more. arr_any = c3; // should be an error - is ~~~~~~~ -!!! error TS2322: Type 'C3' is not assignable to type 'any[]'. -!!! error TS2322: Property 'length' is missing in type 'C3'. +!!! error TS2740: Type 'C3' is missing the following properties from type 'any[]': length, pop, push, concat, and 16 more. \ No newline at end of file diff --git a/tests/baselines/reference/arrayAssignmentTest5.errors.txt b/tests/baselines/reference/arrayAssignmentTest5.errors.txt index 3a45cad9ad7..1a5c1ce4180 100644 --- a/tests/baselines/reference/arrayAssignmentTest5.errors.txt +++ b/tests/baselines/reference/arrayAssignmentTest5.errors.txt @@ -1,6 +1,5 @@ tests/cases/compiler/arrayAssignmentTest5.ts(23,17): error TS2322: Type 'IToken[]' is not assignable to type 'IStateToken[]'. - Type 'IToken' is not assignable to type 'IStateToken'. - Property 'state' is missing in type 'IToken'. + Property 'state' is missing in type 'IToken' but required in type 'IStateToken'. ==== tests/cases/compiler/arrayAssignmentTest5.ts (1 errors) ==== @@ -29,8 +28,8 @@ tests/cases/compiler/arrayAssignmentTest5.ts(23,17): error TS2322: Type 'IToken[ var tokens:IStateToken[]= lineTokens.tokens; ~~~~~~ !!! error TS2322: Type 'IToken[]' is not assignable to type 'IStateToken[]'. -!!! error TS2322: Type 'IToken' is not assignable to type 'IStateToken'. -!!! error TS2322: Property 'state' is missing in type 'IToken'. +!!! error TS2322: Property 'state' is missing in type 'IToken' but required in type 'IStateToken'. +!!! related TS2728 tests/cases/compiler/arrayAssignmentTest5.ts:8:9: 'state' is declared here. if (tokens.length === 0) { return this.onEnter(line, tokens, offset); // <== this should produce an error since onEnter can not be called with (string, IStateToken[], offset) } diff --git a/tests/baselines/reference/arrayBestCommonTypes.js b/tests/baselines/reference/arrayBestCommonTypes.js index c1251a50f38..7b8da4f7970 100644 --- a/tests/baselines/reference/arrayBestCommonTypes.js +++ b/tests/baselines/reference/arrayBestCommonTypes.js @@ -114,7 +114,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; } diff --git a/tests/baselines/reference/arrayFind.types b/tests/baselines/reference/arrayFind.types index 8bc1b36f7f6..c5237183700 100644 --- a/tests/baselines/reference/arrayFind.types +++ b/tests/baselines/reference/arrayFind.types @@ -6,7 +6,7 @@ function isNumber(x: any): x is number { return typeof x === "number"; >typeof x === "number" : boolean ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any >"number" : "number" } diff --git a/tests/baselines/reference/arrayFrom.errors.txt b/tests/baselines/reference/arrayFrom.errors.txt index 4685ec20db8..615bd1bf769 100644 --- a/tests/baselines/reference/arrayFrom.errors.txt +++ b/tests/baselines/reference/arrayFrom.errors.txt @@ -1,6 +1,5 @@ tests/cases/compiler/arrayFrom.ts(20,7): error TS2322: Type 'A[]' is not assignable to type 'B[]'. - Type 'A' is not assignable to type 'B'. - Property 'b' is missing in type 'A'. + Property 'b' is missing in type 'A' but required in type 'B'. tests/cases/compiler/arrayFrom.ts(23,7): error TS2322: Type 'A[]' is not assignable to type 'B[]'. @@ -27,8 +26,8 @@ tests/cases/compiler/arrayFrom.ts(23,7): error TS2322: Type 'A[]' is not assigna const result3: B[] = Array.from(inputA.values()); // expect error ~~~~~~~ !!! error TS2322: Type 'A[]' is not assignable to type 'B[]'. -!!! error TS2322: Type 'A' is not assignable to type 'B'. -!!! error TS2322: Property 'b' is missing in type 'A'. +!!! error TS2322: Property 'b' is missing in type 'A' but required in type 'B'. +!!! related TS2728 tests/cases/compiler/arrayFrom.ts:9:3: 'b' is declared here. const result4: A[] = Array.from(inputB, ({ b }): A => ({ a: b })); const result5: A[] = Array.from(inputALike); const result6: B[] = Array.from(inputALike); // expect error diff --git a/tests/baselines/reference/arrayLiteralTypeInference.errors.txt b/tests/baselines/reference/arrayLiteralTypeInference.errors.txt index a2c4597127f..efffc256a83 100644 --- a/tests/baselines/reference/arrayLiteralTypeInference.errors.txt +++ b/tests/baselines/reference/arrayLiteralTypeInference.errors.txt @@ -1,14 +1,14 @@ -tests/cases/compiler/arrayLiteralTypeInference.ts(14,14): error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type 'Action[]'. - Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type 'Action'. - Type '{ id: number; trueness: boolean; }' is not assignable to type 'Action'. - Object literal may only specify known properties, and 'trueness' does not exist in type 'Action'. -tests/cases/compiler/arrayLiteralTypeInference.ts(31,18): error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type '{ id: number; }[]'. - Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type '{ id: number; }'. - Type '{ id: number; trueness: boolean; }' is not assignable to type '{ id: number; }'. - Object literal may only specify known properties, and 'trueness' does not exist in type '{ id: number; }'. +tests/cases/compiler/arrayLiteralTypeInference.ts(14,14): error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type 'Action'. + Object literal may only specify known properties, and 'trueness' does not exist in type 'Action'. +tests/cases/compiler/arrayLiteralTypeInference.ts(15,14): error TS2322: Type '{ id: number; name: string; }' is not assignable to type 'Action'. + Object literal may only specify known properties, and 'name' does not exist in type 'Action'. +tests/cases/compiler/arrayLiteralTypeInference.ts(31,18): error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type '{ id: number; }'. + Object literal may only specify known properties, and 'trueness' does not exist in type '{ id: number; }'. +tests/cases/compiler/arrayLiteralTypeInference.ts(32,18): error TS2322: Type '{ id: number; name: string; }' is not assignable to type '{ id: number; }'. + Object literal may only specify known properties, and 'name' does not exist in type '{ id: number; }'. -==== tests/cases/compiler/arrayLiteralTypeInference.ts (2 errors) ==== +==== tests/cases/compiler/arrayLiteralTypeInference.ts (4 errors) ==== class Action { id: number; } @@ -24,11 +24,12 @@ tests/cases/compiler/arrayLiteralTypeInference.ts(31,18): error TS2322: Type '({ var x1: Action[] = [ { id: 2, trueness: false }, ~~~~~~~~~~~~~~~ -!!! error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type 'Action[]'. -!!! error TS2322: Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type 'Action'. -!!! error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type 'Action'. -!!! error TS2322: Object literal may only specify known properties, and 'trueness' does not exist in type 'Action'. +!!! error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type 'Action'. +!!! error TS2322: Object literal may only specify known properties, and 'trueness' does not exist in type 'Action'. { id: 3, name: "three" } + ~~~~~~~~~~~~~ +!!! error TS2322: Type '{ id: number; name: string; }' is not assignable to type 'Action'. +!!! error TS2322: Object literal may only specify known properties, and 'name' does not exist in type 'Action'. ] var x2: Action[] = [ @@ -46,11 +47,12 @@ tests/cases/compiler/arrayLiteralTypeInference.ts(31,18): error TS2322: Type '({ [ { id: 2, trueness: false }, ~~~~~~~~~~~~~~~ -!!! error TS2322: Type '({ id: number; trueness: boolean; } | { id: number; name: string; })[]' is not assignable to type '{ id: number; }[]'. -!!! error TS2322: Type '{ id: number; trueness: boolean; } | { id: number; name: string; }' is not assignable to type '{ id: number; }'. -!!! error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type '{ id: number; }'. -!!! error TS2322: Object literal may only specify known properties, and 'trueness' does not exist in type '{ id: number; }'. +!!! error TS2322: Type '{ id: number; trueness: boolean; }' is not assignable to type '{ id: number; }'. +!!! error TS2322: Object literal may only specify known properties, and 'trueness' does not exist in type '{ id: number; }'. { id: 3, name: "three" } + ~~~~~~~~~~~~~ +!!! error TS2322: Type '{ id: number; name: string; }' is not assignable to type '{ id: number; }'. +!!! error TS2322: Object literal may only specify known properties, and 'name' does not exist in type '{ id: number; }'. ] var z2: { id: number }[] = diff --git a/tests/baselines/reference/arrayLiteralTypeInference.js b/tests/baselines/reference/arrayLiteralTypeInference.js index 41cb85f8008..fcd8a62ce0b 100644 --- a/tests/baselines/reference/arrayLiteralTypeInference.js +++ b/tests/baselines/reference/arrayLiteralTypeInference.js @@ -58,7 +58,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; } diff --git a/tests/baselines/reference/arrayLiterals.errors.txt b/tests/baselines/reference/arrayLiterals.errors.txt index f5fe71b79a6..4b9ca295f95 100644 --- a/tests/baselines/reference/arrayLiterals.errors.txt +++ b/tests/baselines/reference/arrayLiterals.errors.txt @@ -1,11 +1,10 @@ -tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts(24,77): error TS2322: Type '({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]' is not assignable to type '{ [n: number]: { a: string; b: number; }; }'. - Index signatures are incompatible. - Type '{ a: string; b: number; c: string; } | { a: string; b: number; c: number; }' is not assignable to type '{ a: string; b: number; }'. - Type '{ a: string; b: number; c: string; }' is not assignable to type '{ a: string; b: number; }'. - Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'. +tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts(24,77): error TS2322: Type '{ a: string; b: number; c: string; }' is not assignable to type '{ a: string; b: number; }'. + Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'. +tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts(24,101): error TS2322: Type '{ a: string; b: number; c: number; }' is not assignable to type '{ a: string; b: number; }'. + Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'. -==== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts (1 errors) ==== +==== tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts (2 errors) ==== // Empty array literal with no contextual type has type Undefined[] var arr1= [[], [1], ['']]; @@ -31,11 +30,13 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts(24,77): error // Contextual type C with numeric index signature makes array literal of EveryType E of type BCT(E,C)[] var context1: { [n: number]: { a: string; b: number; }; } = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }]; ~~~~~ -!!! error TS2322: Type '({ a: string; b: number; c: string; } | { a: string; b: number; c: number; })[]' is not assignable to type '{ [n: number]: { a: string; b: number; }; }'. -!!! error TS2322: Index signatures are incompatible. -!!! error TS2322: Type '{ a: string; b: number; c: string; } | { a: string; b: number; c: number; }' is not assignable to type '{ a: string; b: number; }'. -!!! error TS2322: Type '{ a: string; b: number; c: string; }' is not assignable to type '{ a: string; b: number; }'. -!!! error TS2322: Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'. +!!! error TS2322: Type '{ a: string; b: number; c: string; }' is not assignable to type '{ a: string; b: number; }'. +!!! error TS2322: Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'. +!!! related TS6501 tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts:24:17: The expected type comes from this index signature. + ~~~~ +!!! error TS2322: Type '{ a: string; b: number; c: number; }' is not assignable to type '{ a: string; b: number; }'. +!!! error TS2322: Object literal may only specify known properties, and 'c' does not exist in type '{ a: string; b: number; }'. +!!! related TS6501 tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts:24:17: The expected type comes from this index signature. var context2 = [{ a: '', b: 0, c: '' }, { a: "", b: 3, c: 0 }]; // Contextual type C with numeric index signature of type Base makes array literal of Derived have type Base[] diff --git a/tests/baselines/reference/arrayLiterals.js b/tests/baselines/reference/arrayLiterals.js index bdc11c99e69..c4d257dd546 100644 --- a/tests/baselines/reference/arrayLiterals.js +++ b/tests/baselines/reference/arrayLiterals.js @@ -44,7 +44,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; } diff --git a/tests/baselines/reference/arrayLiterals3.errors.txt b/tests/baselines/reference/arrayLiterals3.errors.txt index d1c99742a27..4d398978c96 100644 --- a/tests/baselines/reference/arrayLiterals3.errors.txt +++ b/tests/baselines/reference/arrayLiterals3.errors.txt @@ -1,15 +1,12 @@ -tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(10,5): error TS2322: Type '[]' is not assignable to type '[any, any, any]'. - Property '0' is missing in type '[]'. +tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(10,5): error TS2739: Type '[]' is missing the following properties from type '[any, any, any]': 0, 1, 2 tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(11,38): error TS2322: Type 'string' is not assignable to type 'boolean'. tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(11,48): error TS2322: Type 'number' is not assignable to type 'string'. tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(11,51): error TS2322: Type 'true' is not assignable to type 'number'. tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(17,5): error TS2322: Type '[number, number, string, boolean]' is not assignable to type '[number, number]'. Types of property 'length' are incompatible. Type '4' is not assignable to type '2'. -tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(32,5): error TS2322: Type '(number[] | string[])[]' is not assignable to type 'tup'. - Property '0' is missing in type '(number[] | string[])[]'. -tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(33,5): error TS2322: Type 'number[]' is not assignable to type '[number, number, number]'. - Property '0' is missing in type 'number[]'. +tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(32,5): error TS2739: Type '(number[] | string[])[]' is missing the following properties from type 'tup': 0, 1 +tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(33,5): error TS2739: Type 'number[]' is missing the following properties from type '[number, number, number]': 0, 1, 2 tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error TS2322: Type '(string | number)[]' is not assignable to type 'myArray'. Types of property 'pop' are incompatible. Type '() => string | number' is not assignable to type '() => Number'. @@ -29,8 +26,7 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error var a0: [any, any, any] = []; // Error ~~ -!!! error TS2322: Type '[]' is not assignable to type '[any, any, any]'. -!!! error TS2322: Property '0' is missing in type '[]'. +!!! error TS2739: Type '[]' is missing the following properties from type '[any, any, any]': 0, 1, 2 var a1: [boolean, string, number] = ["string", 1, true]; // Error ~~~~~~~~ !!! error TS2322: Type 'string' is not assignable to type 'boolean'. @@ -64,12 +60,10 @@ tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts(34,5): error interface myArray2 extends Array { } var c0: tup = [...temp2]; // Error ~~ -!!! error TS2322: Type '(number[] | string[])[]' is not assignable to type 'tup'. -!!! error TS2322: Property '0' is missing in type '(number[] | string[])[]'. +!!! error TS2739: Type '(number[] | string[])[]' is missing the following properties from type 'tup': 0, 1 var c1: [number, number, number] = [...temp1]; // Error cannot assign number[] to [number, number, number] ~~ -!!! error TS2322: Type 'number[]' is not assignable to type '[number, number, number]'. -!!! error TS2322: Property '0' is missing in type 'number[]'. +!!! error TS2739: Type 'number[]' is missing the following properties from type '[number, number, number]': 0, 1, 2 var c2: myArray = [...temp1, ...temp]; // Error cannot assign (number|string)[] to number[] ~~ !!! error TS2322: Type '(string | number)[]' is not assignable to type 'myArray'. diff --git a/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.js b/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.js index 49d1d33c2e8..25a76bec5c7 100644 --- a/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.js +++ b/tests/baselines/reference/arrayLiteralsWithRecursiveGenerics.js @@ -32,7 +32,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; } diff --git a/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.errors.txt b/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.errors.txt index 66a659b3863..319cc4310d8 100644 --- a/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.errors.txt +++ b/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.errors.txt @@ -1,6 +1,5 @@ tests/cases/compiler/arrayOfSubtypeIsAssignableToReadonlyArray.ts(13,1): error TS2322: Type 'A[]' is not assignable to type 'ReadonlyArray'. - Type 'A' is not assignable to type 'B'. - Property 'b' is missing in type 'A'. + Property 'b' is missing in type 'A' but required in type 'B'. tests/cases/compiler/arrayOfSubtypeIsAssignableToReadonlyArray.ts(18,1): error TS2322: Type 'C' is not assignable to type 'ReadonlyArray'. Types of property 'concat' are incompatible. Type '{ (...items: ConcatArray[]): A[]; (...items: (A | ConcatArray)[]): A[]; }' is not assignable to type '{ (...items: ConcatArray[]): B[]; (...items: (B | ConcatArray)[]): B[]; }'. @@ -24,8 +23,8 @@ tests/cases/compiler/arrayOfSubtypeIsAssignableToReadonlyArray.ts(18,1): error T rrb = ara; // error: 'A' is not assignable to 'B' ~~~ !!! error TS2322: Type 'A[]' is not assignable to type 'ReadonlyArray'. -!!! error TS2322: Type 'A' is not assignable to type 'B'. -!!! error TS2322: Property 'b' is missing in type 'A'. +!!! error TS2322: Property 'b' is missing in type 'A' but required in type 'B'. +!!! related TS2728 tests/cases/compiler/arrayOfSubtypeIsAssignableToReadonlyArray.ts:2:21: 'b' is declared here. rra = cra; rra = crb; // OK, C is assignable to ReadonlyArray diff --git a/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.js b/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.js index 47abb0d6255..45b587c0e62 100644 --- a/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.js +++ b/tests/baselines/reference/arrayOfSubtypeIsAssignableToReadonlyArray.js @@ -26,7 +26,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; } diff --git a/tests/baselines/reference/arraySigChecking.errors.txt b/tests/baselines/reference/arraySigChecking.errors.txt index 1968957363c..a1f219919d8 100644 --- a/tests/baselines/reference/arraySigChecking.errors.txt +++ b/tests/baselines/reference/arraySigChecking.errors.txt @@ -1,12 +1,10 @@ tests/cases/compiler/arraySigChecking.ts(11,17): error TS1023: An index signature parameter type must be 'string' or 'number'. -tests/cases/compiler/arraySigChecking.ts(18,5): error TS2322: Type 'void[]' is not assignable to type 'string[]'. - Type 'void' is not assignable to type 'string'. -tests/cases/compiler/arraySigChecking.ts(22,1): error TS2322: Type 'number[][]' is not assignable to type 'number[][][]'. - Type 'number[]' is not assignable to type 'number[][]'. - Type 'number' is not assignable to type 'number[]'. +tests/cases/compiler/arraySigChecking.ts(18,27): error TS2322: Type 'void' is not assignable to type 'string'. +tests/cases/compiler/arraySigChecking.ts(22,13): error TS2322: Type 'number' is not assignable to type 'number[]'. +tests/cases/compiler/arraySigChecking.ts(22,16): error TS2322: Type 'number' is not assignable to type 'number[]'. -==== tests/cases/compiler/arraySigChecking.ts (3 errors) ==== +==== tests/cases/compiler/arraySigChecking.ts (4 errors) ==== declare module M { interface iBar { t: any; } interface iFoo extends iBar { @@ -27,17 +25,16 @@ tests/cases/compiler/arraySigChecking.ts(22,1): error TS2322: Type 'number[][]' } var myVar: myInt; var strArray: string[] = [myVar.voidFn()]; - ~~~~~~~~ -!!! error TS2322: Type 'void[]' is not assignable to type 'string[]'. -!!! error TS2322: Type 'void' is not assignable to type 'string'. + ~~~~~~~~~~~~~~ +!!! error TS2322: Type 'void' is not assignable to type 'string'. var myArray: number[][][]; myArray = [[1, 2]]; - ~~~~~~~ -!!! error TS2322: Type 'number[][]' is not assignable to type 'number[][][]'. -!!! error TS2322: Type 'number[]' is not assignable to type 'number[][]'. -!!! error TS2322: Type 'number' is not assignable to type 'number[]'. + ~ +!!! error TS2322: Type 'number' is not assignable to type 'number[]'. + ~ +!!! error TS2322: Type 'number' is not assignable to type 'number[]'. function isEmpty(l: { length: number }) { return l.length === 0; diff --git a/tests/baselines/reference/arrowFunctionContexts.js b/tests/baselines/reference/arrowFunctionContexts.js index d32683f8ed8..466131ea206 100644 --- a/tests/baselines/reference/arrowFunctionContexts.js +++ b/tests/baselines/reference/arrowFunctionContexts.js @@ -102,7 +102,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; } diff --git a/tests/baselines/reference/assignLambdaToNominalSubtypeOfFunction.errors.txt b/tests/baselines/reference/assignLambdaToNominalSubtypeOfFunction.errors.txt index f462fd347e6..eeab9734ccd 100644 --- a/tests/baselines/reference/assignLambdaToNominalSubtypeOfFunction.errors.txt +++ b/tests/baselines/reference/assignLambdaToNominalSubtypeOfFunction.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/assignLambdaToNominalSubtypeOfFunction.ts(7,4): error TS2345: Argument of type '(a: any, b: any) => boolean' is not assignable to parameter of type 'IResultCallback'. - Property 'x' is missing in type '(a: any, b: any) => boolean'. + Property 'x' is missing in type '(a: any, b: any) => boolean' but required in type 'IResultCallback'. tests/cases/compiler/assignLambdaToNominalSubtypeOfFunction.ts(8,4): error TS2345: Argument of type '(a: any, b: any) => boolean' is not assignable to parameter of type 'IResultCallback'. - Property 'x' is missing in type '(a: any, b: any) => boolean'. + Property 'x' is missing in type '(a: any, b: any) => boolean' but required in type 'IResultCallback'. ==== tests/cases/compiler/assignLambdaToNominalSubtypeOfFunction.ts (2 errors) ==== @@ -14,9 +14,11 @@ tests/cases/compiler/assignLambdaToNominalSubtypeOfFunction.ts(8,4): error TS234 fn((a, b) => true); ~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '(a: any, b: any) => boolean' is not assignable to parameter of type 'IResultCallback'. -!!! error TS2345: Property 'x' is missing in type '(a: any, b: any) => boolean'. +!!! error TS2345: Property 'x' is missing in type '(a: any, b: any) => boolean' but required in type 'IResultCallback'. +!!! related TS2728 tests/cases/compiler/assignLambdaToNominalSubtypeOfFunction.ts:2:5: 'x' is declared here. fn(function (a, b) { return true; }) ~~~~~~~~ !!! error TS2345: Argument of type '(a: any, b: any) => boolean' is not assignable to parameter of type 'IResultCallback'. -!!! error TS2345: Property 'x' is missing in type '(a: any, b: any) => boolean'. +!!! error TS2345: Property 'x' is missing in type '(a: any, b: any) => boolean' but required in type 'IResultCallback'. +!!! related TS2728 tests/cases/compiler/assignLambdaToNominalSubtypeOfFunction.ts:2:5: 'x' is declared here. \ No newline at end of file diff --git a/tests/baselines/reference/assignToEnum.errors.txt b/tests/baselines/reference/assignToEnum.errors.txt index 438a002ef1e..53b4afc1864 100644 --- a/tests/baselines/reference/assignToEnum.errors.txt +++ b/tests/baselines/reference/assignToEnum.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/assignToEnum.ts(2,1): error TS2539: Cannot assign to 'A' because it is not a variable. tests/cases/compiler/assignToEnum.ts(3,1): error TS2539: Cannot assign to 'A' because it is not a variable. -tests/cases/compiler/assignToEnum.ts(4,3): error TS2540: Cannot assign to 'foo' because it is a constant or a read-only property. -tests/cases/compiler/assignToEnum.ts(5,3): error TS2540: Cannot assign to 'foo' because it is a constant or a read-only property. +tests/cases/compiler/assignToEnum.ts(4,3): error TS2540: Cannot assign to 'foo' because it is a read-only property. +tests/cases/compiler/assignToEnum.ts(5,3): error TS2540: Cannot assign to 'foo' because it is a read-only property. ==== tests/cases/compiler/assignToEnum.ts (4 errors) ==== @@ -14,9 +14,9 @@ tests/cases/compiler/assignToEnum.ts(5,3): error TS2540: Cannot assign to 'foo' !!! error TS2539: Cannot assign to 'A' because it is not a variable. A.foo = 1; // invalid LHS ~~~ -!!! error TS2540: Cannot assign to 'foo' because it is a constant or a read-only property. +!!! error TS2540: Cannot assign to 'foo' because it is a read-only property. A.foo = A.bar; // invalid LHS ~~~ -!!! error TS2540: Cannot assign to 'foo' because it is a constant or a read-only property. +!!! error TS2540: Cannot assign to 'foo' because it is a read-only property. \ No newline at end of file diff --git a/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt b/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt index bc92c376c7c..0a7a3a2db5c 100644 --- a/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt +++ b/tests/baselines/reference/assigningFromObjectToAnythingElse.errors.txt @@ -1,11 +1,9 @@ -tests/cases/compiler/assigningFromObjectToAnythingElse.ts(3,1): error TS2322: Type 'Object' is not assignable to type 'RegExp'. - The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? - Property 'exec' is missing in type 'Object'. +tests/cases/compiler/assigningFromObjectToAnythingElse.ts(3,1): error TS2696: The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? + Type 'Object' is missing the following properties from type 'RegExp': exec, test, source, global, and 4 more. tests/cases/compiler/assigningFromObjectToAnythingElse.ts(5,31): error TS2558: Expected 0 type arguments, but got 1. tests/cases/compiler/assigningFromObjectToAnythingElse.ts(6,31): error TS2558: Expected 0 type arguments, but got 1. -tests/cases/compiler/assigningFromObjectToAnythingElse.ts(8,5): error TS2322: Type 'Object' is not assignable to type 'Error'. - The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? - Property 'name' is missing in type 'Object'. +tests/cases/compiler/assigningFromObjectToAnythingElse.ts(8,5): error TS2696: The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? + Type 'Object' is missing the following properties from type 'Error': name, message ==== tests/cases/compiler/assigningFromObjectToAnythingElse.ts (4 errors) ==== @@ -13,9 +11,8 @@ tests/cases/compiler/assigningFromObjectToAnythingElse.ts(8,5): error TS2322: Ty var y: RegExp; y = x; ~ -!!! error TS2322: Type 'Object' is not assignable to type 'RegExp'. -!!! error TS2322: The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? -!!! error TS2322: Property 'exec' is missing in type 'Object'. +!!! error TS2696: The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? +!!! error TS2696: Type 'Object' is missing the following properties from type 'RegExp': exec, test, source, global, and 4 more. var a: String = Object.create(""); ~~~~~~ @@ -26,7 +23,6 @@ tests/cases/compiler/assigningFromObjectToAnythingElse.ts(8,5): error TS2322: Ty var w: Error = new Object(); ~ -!!! error TS2322: Type 'Object' is not assignable to type 'Error'. -!!! error TS2322: The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? -!!! error TS2322: Property 'name' is missing in type 'Object'. +!!! error TS2696: The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead? +!!! error TS2696: Type 'Object' is missing the following properties from type 'Error': name, message \ No newline at end of file diff --git a/tests/baselines/reference/assignmentCompat1.errors.txt b/tests/baselines/reference/assignmentCompat1.errors.txt index e9fc3bd2f7f..d393d553ce4 100644 --- a/tests/baselines/reference/assignmentCompat1.errors.txt +++ b/tests/baselines/reference/assignmentCompat1.errors.txt @@ -1,7 +1,5 @@ -tests/cases/compiler/assignmentCompat1.ts(4,1): error TS2322: Type '{ [index: string]: any; }' is not assignable to type '{ one: number; }'. - Property 'one' is missing in type '{ [index: string]: any; }'. -tests/cases/compiler/assignmentCompat1.ts(6,1): error TS2322: Type '{ [index: number]: any; }' is not assignable to type '{ one: number; }'. - Property 'one' is missing in type '{ [index: number]: any; }'. +tests/cases/compiler/assignmentCompat1.ts(4,1): error TS2741: Property 'one' is missing in type '{ [index: string]: any; }' but required in type '{ one: number; }'. +tests/cases/compiler/assignmentCompat1.ts(6,1): error TS2741: Property 'one' is missing in type '{ [index: number]: any; }' but required in type '{ one: number; }'. tests/cases/compiler/assignmentCompat1.ts(8,1): error TS2322: Type '"foo"' is not assignable to type '{ [index: string]: any; }'. tests/cases/compiler/assignmentCompat1.ts(10,1): error TS2322: Type 'false' is not assignable to type '{ [index: number]: any; }'. @@ -12,13 +10,13 @@ tests/cases/compiler/assignmentCompat1.ts(10,1): error TS2322: Type 'false' is n var z: { [index: number]: any }; x = y; // Error ~ -!!! error TS2322: Type '{ [index: string]: any; }' is not assignable to type '{ one: number; }'. -!!! error TS2322: Property 'one' is missing in type '{ [index: string]: any; }'. +!!! error TS2741: Property 'one' is missing in type '{ [index: string]: any; }' but required in type '{ one: number; }'. +!!! related TS2728 tests/cases/compiler/assignmentCompat1.ts:1:11: 'one' is declared here. y = x; // Ok because index signature type is any x = z; // Error ~ -!!! error TS2322: Type '{ [index: number]: any; }' is not assignable to type '{ one: number; }'. -!!! error TS2322: Property 'one' is missing in type '{ [index: number]: any; }'. +!!! error TS2741: Property 'one' is missing in type '{ [index: number]: any; }' but required in type '{ one: number; }'. +!!! related TS2728 tests/cases/compiler/assignmentCompat1.ts:1:11: 'one' is declared here. z = x; // Ok because index signature type is any y = "foo"; // Error ~ diff --git a/tests/baselines/reference/assignmentCompatBetweenTupleAndArray.errors.txt b/tests/baselines/reference/assignmentCompatBetweenTupleAndArray.errors.txt index b17973302c6..0d6aea98daf 100644 --- a/tests/baselines/reference/assignmentCompatBetweenTupleAndArray.errors.txt +++ b/tests/baselines/reference/assignmentCompatBetweenTupleAndArray.errors.txt @@ -1,8 +1,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatBetweenTupleAndArray.ts(17,1): error TS2322: Type '[number, string]' is not assignable to type 'number[]'. Type 'string | number' is not assignable to type 'number'. Type 'string' is not assignable to type 'number'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatBetweenTupleAndArray.ts(18,1): error TS2322: Type '{}[]' is not assignable to type '[{}]'. - Property '0' is missing in type '{}[]'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatBetweenTupleAndArray.ts(18,1): error TS2741: Property '0' is missing in type '{}[]' but required in type '[{}]'. ==== tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatBetweenTupleAndArray.ts (2 errors) ==== @@ -29,6 +28,5 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme !!! error TS2322: Type 'string' is not assignable to type 'number'. emptyObjTuple = emptyObjArray; ~~~~~~~~~~~~~ -!!! error TS2322: Type '{}[]' is not assignable to type '[{}]'. -!!! error TS2322: Property '0' is missing in type '{}[]'. +!!! error TS2741: Property '0' is missing in type '{}[]' but required in type '[{}]'. \ No newline at end of file diff --git a/tests/baselines/reference/assignmentCompatBug2.errors.txt b/tests/baselines/reference/assignmentCompatBug2.errors.txt index 29ba96e6586..b8bd7d48473 100644 --- a/tests/baselines/reference/assignmentCompatBug2.errors.txt +++ b/tests/baselines/reference/assignmentCompatBug2.errors.txt @@ -4,12 +4,9 @@ tests/cases/compiler/assignmentCompatBug2.ts(3,8): error TS2322: Type '{ a: numb Object literal may only specify known properties, and 'a' does not exist in type '{ b: number; }'. tests/cases/compiler/assignmentCompatBug2.ts(5,13): error TS2322: Type '{ b: number; a: number; }' is not assignable to type '{ b: number; }'. Object literal may only specify known properties, and 'a' does not exist in type '{ b: number; }'. -tests/cases/compiler/assignmentCompatBug2.ts(15,1): error TS2322: Type '{ f: (n: number) => number; g: (s: string) => number; }' is not assignable to type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'. - Property 'm' is missing in type '{ f: (n: number) => number; g: (s: string) => number; }'. -tests/cases/compiler/assignmentCompatBug2.ts(20,1): error TS2322: Type '{ f: (n: number) => number; m: number; }' is not assignable to type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'. - Property 'g' is missing in type '{ f: (n: number) => number; m: number; }'. -tests/cases/compiler/assignmentCompatBug2.ts(33,1): error TS2322: Type '{ f: (n: number) => number; g: (s: string) => number; n: number; k: (a: any) => any; }' is not assignable to type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'. - Property 'm' is missing in type '{ f: (n: number) => number; g: (s: string) => number; n: number; k: (a: any) => any; }'. +tests/cases/compiler/assignmentCompatBug2.ts(15,1): error TS2741: Property 'm' is missing in type '{ f: (n: number) => number; g: (s: string) => number; }' but required in type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'. +tests/cases/compiler/assignmentCompatBug2.ts(20,1): error TS2741: Property 'g' is missing in type '{ f: (n: number) => number; m: number; }' but required in type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'. +tests/cases/compiler/assignmentCompatBug2.ts(33,1): error TS2741: Property 'm' is missing in type '{ f: (n: number) => number; g: (s: string) => number; n: number; k: (a: any) => any; }' but required in type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'. ==== tests/cases/compiler/assignmentCompatBug2.ts (6 errors) ==== @@ -38,16 +35,16 @@ tests/cases/compiler/assignmentCompatBug2.ts(33,1): error TS2322: Type '{ f: (n: b3 = { ~~ -!!! error TS2322: Type '{ f: (n: number) => number; g: (s: string) => number; }' is not assignable to type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'. -!!! error TS2322: Property 'm' is missing in type '{ f: (n: number) => number; g: (s: string) => number; }'. +!!! error TS2741: Property 'm' is missing in type '{ f: (n: number) => number; g: (s: string) => number; }' but required in type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'. +!!! related TS2728 tests/cases/compiler/assignmentCompatBug2.ts:7:55: 'm' is declared here. f: (n) => { return 0; }, g: (s) => { return 0; }, }; // error b3 = { ~~ -!!! error TS2322: Type '{ f: (n: number) => number; m: number; }' is not assignable to type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'. -!!! error TS2322: Property 'g' is missing in type '{ f: (n: number) => number; m: number; }'. +!!! error TS2741: Property 'g' is missing in type '{ f: (n: number) => number; m: number; }' but required in type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'. +!!! related TS2728 tests/cases/compiler/assignmentCompatBug2.ts:7:33: 'g' is declared here. f: (n) => { return 0; }, m: 0, }; // error @@ -62,8 +59,8 @@ tests/cases/compiler/assignmentCompatBug2.ts(33,1): error TS2322: Type '{ f: (n: b3 = { ~~ -!!! error TS2322: Type '{ f: (n: number) => number; g: (s: string) => number; n: number; k: (a: any) => any; }' is not assignable to type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'. -!!! error TS2322: Property 'm' is missing in type '{ f: (n: number) => number; g: (s: string) => number; n: number; k: (a: any) => any; }'. +!!! error TS2741: Property 'm' is missing in type '{ f: (n: number) => number; g: (s: string) => number; n: number; k: (a: any) => any; }' but required in type '{ f(n: number): number; g(s: string): number; m: number; n?: number; k?(a: any): any; }'. +!!! related TS2728 tests/cases/compiler/assignmentCompatBug2.ts:7:55: 'm' is declared here. f: (n) => { return 0; }, g: (s) => { return 0; }, n: 0, diff --git a/tests/baselines/reference/assignmentCompatBug5.errors.txt b/tests/baselines/reference/assignmentCompatBug5.errors.txt index 44e28f15d8c..6a5c5569c8f 100644 --- a/tests/baselines/reference/assignmentCompatBug5.errors.txt +++ b/tests/baselines/reference/assignmentCompatBug5.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/assignmentCompatBug5.ts(2,8): error TS2345: Argument of type '{ b: number; }' is not assignable to parameter of type '{ a: number; }'. Object literal may only specify known properties, and 'b' does not exist in type '{ a: number; }'. -tests/cases/compiler/assignmentCompatBug5.ts(5,6): error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'number[]'. - Type 'string' is not assignable to type 'number'. +tests/cases/compiler/assignmentCompatBug5.ts(5,7): error TS2322: Type 'string' is not assignable to type 'number'. +tests/cases/compiler/assignmentCompatBug5.ts(5,12): error TS2322: Type 'string' is not assignable to type 'number'. tests/cases/compiler/assignmentCompatBug5.ts(8,6): error TS2345: Argument of type '(s: string) => void' is not assignable to parameter of type '(n: number) => number'. Types of parameters 's' and 'n' are incompatible. Type 'number' is not assignable to type 'string'. @@ -9,7 +9,7 @@ tests/cases/compiler/assignmentCompatBug5.ts(9,6): error TS2345: Argument of typ Type 'void' is not assignable to type 'number'. -==== tests/cases/compiler/assignmentCompatBug5.ts (4 errors) ==== +==== tests/cases/compiler/assignmentCompatBug5.ts (5 errors) ==== function foo1(x: { a: number; }) { } foo1({ b: 5 }); ~~~~ @@ -18,9 +18,10 @@ tests/cases/compiler/assignmentCompatBug5.ts(9,6): error TS2345: Argument of typ function foo2(x: number[]) { } foo2(["s", "t"]); - ~~~~~~~~~~ -!!! error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'number[]'. -!!! error TS2345: Type 'string' is not assignable to type 'number'. + ~~~ +!!! error TS2322: Type 'string' is not assignable to type 'number'. + ~~~ +!!! error TS2322: Type 'string' is not assignable to type 'number'. function foo3(x: (n: number) =>number) { }; foo3((s:string) => { }); diff --git a/tests/baselines/reference/assignmentCompatFunctionsWithOptionalArgs.errors.txt b/tests/baselines/reference/assignmentCompatFunctionsWithOptionalArgs.errors.txt index 6686167cf1e..870c5f8839d 100644 --- a/tests/baselines/reference/assignmentCompatFunctionsWithOptionalArgs.errors.txt +++ b/tests/baselines/reference/assignmentCompatFunctionsWithOptionalArgs.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/assignmentCompatFunctionsWithOptionalArgs.ts(1,10): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/compiler/assignmentCompatFunctionsWithOptionalArgs.ts(4,17): error TS2322: Type 'false' is not assignable to type 'string'. tests/cases/compiler/assignmentCompatFunctionsWithOptionalArgs.ts(5,5): error TS2345: Argument of type '{ name: string; }' is not assignable to parameter of type '{ id: number; name?: string; }'. - Property 'id' is missing in type '{ name: string; }'. + Property 'id' is missing in type '{ name: string; }' but required in type '{ id: number; name?: string; }'. ==== tests/cases/compiler/assignmentCompatFunctionsWithOptionalArgs.ts (3 errors) ==== @@ -17,4 +17,5 @@ tests/cases/compiler/assignmentCompatFunctionsWithOptionalArgs.ts(5,5): error TS foo({ name: "hello" }); // Error, id required but missing ~~~~~~~~~~~~~~~~~ !!! error TS2345: Argument of type '{ name: string; }' is not assignable to parameter of type '{ id: number; name?: string; }'. -!!! error TS2345: Property 'id' is missing in type '{ name: string; }'. \ No newline at end of file +!!! error TS2345: Property 'id' is missing in type '{ name: string; }' but required in type '{ id: number; name?: string; }'. +!!! related TS2728 tests/cases/compiler/assignmentCompatFunctionsWithOptionalArgs.ts:1:19: 'id' is declared here. \ No newline at end of file diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures2.errors.txt b/tests/baselines/reference/assignmentCompatWithCallSignatures2.errors.txt index ffc0fdcd772..ba14424f99f 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures2.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures2.errors.txt @@ -1,11 +1,7 @@ -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(31,1): error TS2322: Type '() => number' is not assignable to type 'T'. - Property 'f' is missing in type '() => number'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(32,1): error TS2322: Type '(x: number) => string' is not assignable to type 'T'. - Property 'f' is missing in type '(x: number) => string'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(33,1): error TS2322: Type '() => number' is not assignable to type '{ f(x: number): void; }'. - Property 'f' is missing in type '() => number'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(34,1): error TS2322: Type '(x: number) => string' is not assignable to type '{ f(x: number): void; }'. - Property 'f' is missing in type '(x: number) => string'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(31,1): error TS2741: Property 'f' is missing in type '() => number' but required in type 'T'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(32,1): error TS2741: Property 'f' is missing in type '(x: number) => string' but required in type 'T'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(33,1): error TS2741: Property 'f' is missing in type '() => number' but required in type '{ f(x: number): void; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(34,1): error TS2741: Property 'f' is missing in type '(x: number) => string' but required in type '{ f(x: number): void; }'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(42,1): error TS2322: Type 'S2' is not assignable to type 'T'. Types of property 'f' are incompatible. Type '(x: string) => void' is not assignable to type '(x: number) => void'. @@ -16,10 +12,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme Type '(x: string) => void' is not assignable to type '(x: number) => void'. Types of parameters 'x' and 'x' are incompatible. Type 'number' is not assignable to type 'string'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(44,1): error TS2322: Type '(x: string) => number' is not assignable to type 'T'. - Property 'f' is missing in type '(x: string) => number'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(45,1): error TS2322: Type '(x: string) => string' is not assignable to type 'T'. - Property 'f' is missing in type '(x: string) => string'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(44,1): error TS2741: Property 'f' is missing in type '(x: string) => number' but required in type 'T'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(45,1): error TS2741: Property 'f' is missing in type '(x: string) => string' but required in type 'T'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(46,1): error TS2322: Type 'S2' is not assignable to type '{ f(x: number): void; }'. Types of property 'f' are incompatible. Type '(x: string) => void' is not assignable to type '(x: number) => void'. @@ -30,10 +24,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme Type '(x: string) => void' is not assignable to type '(x: number) => void'. Types of parameters 'x' and 'x' are incompatible. Type 'number' is not assignable to type 'string'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(48,1): error TS2322: Type '(x: string) => number' is not assignable to type '{ f(x: number): void; }'. - Property 'f' is missing in type '(x: string) => number'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(49,1): error TS2322: Type '(x: string) => string' is not assignable to type '{ f(x: number): void; }'. - Property 'f' is missing in type '(x: string) => string'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(48,1): error TS2741: Property 'f' is missing in type '(x: string) => number' but required in type '{ f(x: number): void; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts(49,1): error TS2741: Property 'f' is missing in type '(x: string) => string' but required in type '{ f(x: number): void; }'. ==== tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts (12 errors) ==== @@ -69,20 +61,20 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme // errors t = () => 1; ~ -!!! error TS2322: Type '() => number' is not assignable to type 'T'. -!!! error TS2322: Property 'f' is missing in type '() => number'. +!!! error TS2741: Property 'f' is missing in type '() => number' but required in type 'T'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts:4:5: 'f' is declared here. t = function (x: number) { return ''; } ~ -!!! error TS2322: Type '(x: number) => string' is not assignable to type 'T'. -!!! error TS2322: Property 'f' is missing in type '(x: number) => string'. +!!! error TS2741: Property 'f' is missing in type '(x: number) => string' but required in type 'T'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts:4:5: 'f' is declared here. a = () => 1; ~ -!!! error TS2322: Type '() => number' is not assignable to type '{ f(x: number): void; }'. -!!! error TS2322: Property 'f' is missing in type '() => number'. +!!! error TS2741: Property 'f' is missing in type '() => number' but required in type '{ f(x: number): void; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts:7:10: 'f' is declared here. a = function (x: number) { return ''; } ~ -!!! error TS2322: Type '(x: number) => string' is not assignable to type '{ f(x: number): void; }'. -!!! error TS2322: Property 'f' is missing in type '(x: number) => string'. +!!! error TS2741: Property 'f' is missing in type '(x: number) => string' but required in type '{ f(x: number): void; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts:7:10: 'f' is declared here. interface S2 { f(x: string): void; @@ -106,12 +98,12 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme !!! error TS2322: Type 'number' is not assignable to type 'string'. t = (x: string) => 1; ~ -!!! error TS2322: Type '(x: string) => number' is not assignable to type 'T'. -!!! error TS2322: Property 'f' is missing in type '(x: string) => number'. +!!! error TS2741: Property 'f' is missing in type '(x: string) => number' but required in type 'T'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts:4:5: 'f' is declared here. t = function (x: string) { return ''; } ~ -!!! error TS2322: Type '(x: string) => string' is not assignable to type 'T'. -!!! error TS2322: Property 'f' is missing in type '(x: string) => string'. +!!! error TS2741: Property 'f' is missing in type '(x: string) => string' but required in type 'T'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts:4:5: 'f' is declared here. a = s2; ~ !!! error TS2322: Type 'S2' is not assignable to type '{ f(x: number): void; }'. @@ -128,10 +120,10 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme !!! error TS2322: Type 'number' is not assignable to type 'string'. a = (x: string) => 1; ~ -!!! error TS2322: Type '(x: string) => number' is not assignable to type '{ f(x: number): void; }'. -!!! error TS2322: Property 'f' is missing in type '(x: string) => number'. +!!! error TS2741: Property 'f' is missing in type '(x: string) => number' but required in type '{ f(x: number): void; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts:7:10: 'f' is declared here. a = function (x: string) { return ''; } ~ -!!! error TS2322: Type '(x: string) => string' is not assignable to type '{ f(x: number): void; }'. -!!! error TS2322: Property 'f' is missing in type '(x: string) => string'. +!!! error TS2741: Property 'f' is missing in type '(x: string) => string' but required in type '{ f(x: number): void; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures2.ts:7:10: 'f' is declared here. \ No newline at end of file diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures3.errors.txt b/tests/baselines/reference/assignmentCompatWithCallSignatures3.errors.txt index 441810033d2..aeab1787439 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures3.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures3.errors.txt @@ -35,14 +35,12 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures3.ts(77,1): error TS2322: Type '(x: { foo: string; }, y: { foo: string; bar: string; }) => Base' is not assignable to type '(x: T, y: T) => T'. Types of parameters 'y' and 'y' are incompatible. Type 'T' is not assignable to type '{ foo: string; bar: string; }'. - Type 'Base' is not assignable to type '{ foo: string; bar: string; }'. - Property 'bar' is missing in type 'Base'. + Property 'bar' is missing in type 'Base' but required in type '{ foo: string; bar: string; }'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures3.ts(80,1): error TS2322: Type '(x: Base[], y: Derived2[]) => Derived[]' is not assignable to type '(x: Base[], y: T) => Derived[]'. Types of parameters 'y' and 'y' are incompatible. Type 'T' is not assignable to type 'Derived2[]'. Type 'Base[]' is not assignable to type 'Derived2[]'. - Type 'Base' is not assignable to type 'Derived2'. - Property 'baz' is missing in type 'Base'. + Type 'Base' is missing the following properties from type 'Derived2': baz, bar tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures3.ts(83,1): error TS2322: Type '(x: Base[], y: Derived[]) => Derived[]' is not assignable to type '(x: Base[], y: T) => T'. Type 'Derived[]' is not assignable to type 'T'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures3.ts(85,1): error TS2322: Type '(x: { a: T; b: T; }) => T' is not assignable to type '(x: { a: string; b: number; }) => Object'. @@ -183,8 +181,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme !!! error TS2322: Type '(x: { foo: string; }, y: { foo: string; bar: string; }) => Base' is not assignable to type '(x: T, y: T) => T'. !!! error TS2322: Types of parameters 'y' and 'y' are incompatible. !!! error TS2322: Type 'T' is not assignable to type '{ foo: string; bar: string; }'. -!!! error TS2322: Type 'Base' is not assignable to type '{ foo: string; bar: string; }'. -!!! error TS2322: Property 'bar' is missing in type 'Base'. +!!! error TS2322: Property 'bar' is missing in type 'Base' but required in type '{ foo: string; bar: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithCallSignatures3.ts:18:49: 'bar' is declared here. var b12: >(x: Array, y: T) => Array; a12 = b12; // ok b12 = a12; // ok @@ -193,8 +191,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme !!! error TS2322: Types of parameters 'y' and 'y' are incompatible. !!! error TS2322: Type 'T' is not assignable to type 'Derived2[]'. !!! error TS2322: Type 'Base[]' is not assignable to type 'Derived2[]'. -!!! error TS2322: Type 'Base' is not assignable to type 'Derived2'. -!!! error TS2322: Property 'baz' is missing in type 'Base'. +!!! error TS2322: Type 'Base' is missing the following properties from type 'Derived2': baz, bar var b13: >(x: Array, y: T) => T; a13 = b13; // ok b13 = a13; // ok diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures3.js b/tests/baselines/reference/assignmentCompatWithCallSignatures3.js index 2490b1ef9c8..a051b4e5194 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures3.js +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures3.js @@ -107,7 +107,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; } diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures4.js b/tests/baselines/reference/assignmentCompatWithCallSignatures4.js index d1e898d3c6d..fc83877023b 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures4.js +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures4.js @@ -106,7 +106,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; } diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures5.js b/tests/baselines/reference/assignmentCompatWithCallSignatures5.js index 6eaacacf897..fb6d0be1be1 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures5.js +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures5.js @@ -73,7 +73,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; } diff --git a/tests/baselines/reference/assignmentCompatWithCallSignatures6.js b/tests/baselines/reference/assignmentCompatWithCallSignatures6.js index 775d7886310..9e752a43a17 100644 --- a/tests/baselines/reference/assignmentCompatWithCallSignatures6.js +++ b/tests/baselines/reference/assignmentCompatWithCallSignatures6.js @@ -50,7 +50,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; } diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures2.errors.txt b/tests/baselines/reference/assignmentCompatWithConstructSignatures2.errors.txt index 0155b8611c4..b42670aa902 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures2.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures2.errors.txt @@ -1,11 +1,7 @@ -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(23,1): error TS2322: Type '() => number' is not assignable to type 'T'. - Property 'f' is missing in type '() => number'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(24,1): error TS2322: Type '(x: number) => string' is not assignable to type 'T'. - Property 'f' is missing in type '(x: number) => string'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(25,1): error TS2322: Type '() => number' is not assignable to type '{ f: new (x: number) => void; }'. - Property 'f' is missing in type '() => number'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(26,1): error TS2322: Type '(x: number) => string' is not assignable to type '{ f: new (x: number) => void; }'. - Property 'f' is missing in type '(x: number) => string'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(23,1): error TS2741: Property 'f' is missing in type '() => number' but required in type 'T'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(24,1): error TS2741: Property 'f' is missing in type '(x: number) => string' but required in type 'T'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(25,1): error TS2741: Property 'f' is missing in type '() => number' but required in type '{ f: new (x: number) => void; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(26,1): error TS2741: Property 'f' is missing in type '(x: number) => string' but required in type '{ f: new (x: number) => void; }'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(34,1): error TS2322: Type 'S2' is not assignable to type 'T'. Types of property 'f' are incompatible. Type '(x: string) => void' is not assignable to type 'new (x: number) => void'. @@ -14,10 +10,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme Types of property 'f' are incompatible. Type '(x: string) => void' is not assignable to type 'new (x: number) => void'. Type '(x: string) => void' provides no match for the signature 'new (x: number): void'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(36,1): error TS2322: Type '(x: string) => number' is not assignable to type 'T'. - Property 'f' is missing in type '(x: string) => number'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(37,1): error TS2322: Type '(x: string) => string' is not assignable to type 'T'. - Property 'f' is missing in type '(x: string) => string'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(36,1): error TS2741: Property 'f' is missing in type '(x: string) => number' but required in type 'T'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(37,1): error TS2741: Property 'f' is missing in type '(x: string) => string' but required in type 'T'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(38,1): error TS2322: Type 'S2' is not assignable to type '{ f: new (x: number) => void; }'. Types of property 'f' are incompatible. Type '(x: string) => void' is not assignable to type 'new (x: number) => void'. @@ -26,10 +20,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme Types of property 'f' are incompatible. Type '(x: string) => void' is not assignable to type 'new (x: number) => void'. Type '(x: string) => void' provides no match for the signature 'new (x: number): void'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(40,1): error TS2322: Type '(x: string) => number' is not assignable to type '{ f: new (x: number) => void; }'. - Property 'f' is missing in type '(x: string) => number'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(41,1): error TS2322: Type '(x: string) => string' is not assignable to type '{ f: new (x: number) => void; }'. - Property 'f' is missing in type '(x: string) => string'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(40,1): error TS2741: Property 'f' is missing in type '(x: string) => number' but required in type '{ f: new (x: number) => void; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts(41,1): error TS2741: Property 'f' is missing in type '(x: string) => string' but required in type '{ f: new (x: number) => void; }'. ==== tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts (12 errors) ==== @@ -57,20 +49,20 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme // errors t = () => 1; ~ -!!! error TS2322: Type '() => number' is not assignable to type 'T'. -!!! error TS2322: Property 'f' is missing in type '() => number'. +!!! error TS2741: Property 'f' is missing in type '() => number' but required in type 'T'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts:4:5: 'f' is declared here. t = function (x: number) { return ''; } ~ -!!! error TS2322: Type '(x: number) => string' is not assignable to type 'T'. -!!! error TS2322: Property 'f' is missing in type '(x: number) => string'. +!!! error TS2741: Property 'f' is missing in type '(x: number) => string' but required in type 'T'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts:4:5: 'f' is declared here. a = () => 1; ~ -!!! error TS2322: Type '() => number' is not assignable to type '{ f: new (x: number) => void; }'. -!!! error TS2322: Property 'f' is missing in type '() => number'. +!!! error TS2741: Property 'f' is missing in type '() => number' but required in type '{ f: new (x: number) => void; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts:7:10: 'f' is declared here. a = function (x: number) { return ''; } ~ -!!! error TS2322: Type '(x: number) => string' is not assignable to type '{ f: new (x: number) => void; }'. -!!! error TS2322: Property 'f' is missing in type '(x: number) => string'. +!!! error TS2741: Property 'f' is missing in type '(x: number) => string' but required in type '{ f: new (x: number) => void; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts:7:10: 'f' is declared here. interface S2 { f(x: string): void; @@ -92,12 +84,12 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme !!! error TS2322: Type '(x: string) => void' provides no match for the signature 'new (x: number): void'. t = (x: string) => 1; ~ -!!! error TS2322: Type '(x: string) => number' is not assignable to type 'T'. -!!! error TS2322: Property 'f' is missing in type '(x: string) => number'. +!!! error TS2741: Property 'f' is missing in type '(x: string) => number' but required in type 'T'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts:4:5: 'f' is declared here. t = function (x: string) { return ''; } ~ -!!! error TS2322: Type '(x: string) => string' is not assignable to type 'T'. -!!! error TS2322: Property 'f' is missing in type '(x: string) => string'. +!!! error TS2741: Property 'f' is missing in type '(x: string) => string' but required in type 'T'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts:4:5: 'f' is declared here. a = s2; ~ !!! error TS2322: Type 'S2' is not assignable to type '{ f: new (x: number) => void; }'. @@ -112,10 +104,10 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme !!! error TS2322: Type '(x: string) => void' provides no match for the signature 'new (x: number): void'. a = (x: string) => 1; ~ -!!! error TS2322: Type '(x: string) => number' is not assignable to type '{ f: new (x: number) => void; }'. -!!! error TS2322: Property 'f' is missing in type '(x: string) => number'. +!!! error TS2741: Property 'f' is missing in type '(x: string) => number' but required in type '{ f: new (x: number) => void; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts:7:10: 'f' is declared here. a = function (x: string) { return ''; } ~ -!!! error TS2322: Type '(x: string) => string' is not assignable to type '{ f: new (x: number) => void; }'. -!!! error TS2322: Property 'f' is missing in type '(x: string) => string'. +!!! error TS2741: Property 'f' is missing in type '(x: string) => string' but required in type '{ f: new (x: number) => void; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures2.ts:7:10: 'f' is declared here. \ No newline at end of file diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures3.errors.txt b/tests/baselines/reference/assignmentCompatWithConstructSignatures3.errors.txt index 3bce93635d0..1db469b6a4f 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures3.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures3.errors.txt @@ -35,14 +35,12 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures3.ts(77,1): error TS2322: Type 'new (x: { foo: string; }, y: { foo: string; bar: string; }) => Base' is not assignable to type 'new (x: T, y: T) => T'. Types of parameters 'y' and 'y' are incompatible. Type 'T' is not assignable to type '{ foo: string; bar: string; }'. - Type 'Base' is not assignable to type '{ foo: string; bar: string; }'. - Property 'bar' is missing in type 'Base'. + Property 'bar' is missing in type 'Base' but required in type '{ foo: string; bar: string; }'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures3.ts(80,1): error TS2322: Type 'new (x: Base[], y: Derived2[]) => Derived[]' is not assignable to type 'new (x: Base[], y: T) => Derived[]'. Types of parameters 'y' and 'y' are incompatible. Type 'T' is not assignable to type 'Derived2[]'. Type 'Base[]' is not assignable to type 'Derived2[]'. - Type 'Base' is not assignable to type 'Derived2'. - Property 'baz' is missing in type 'Base'. + Type 'Base' is missing the following properties from type 'Derived2': baz, bar tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures3.ts(83,1): error TS2322: Type 'new (x: Base[], y: Derived[]) => Derived[]' is not assignable to type 'new (x: Base[], y: T) => T'. Type 'Derived[]' is not assignable to type 'T'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures3.ts(85,1): error TS2322: Type 'new (x: { a: T; b: T; }) => T' is not assignable to type 'new (x: { a: string; b: number; }) => Object'. @@ -183,8 +181,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme !!! error TS2322: Type 'new (x: { foo: string; }, y: { foo: string; bar: string; }) => Base' is not assignable to type 'new (x: T, y: T) => T'. !!! error TS2322: Types of parameters 'y' and 'y' are incompatible. !!! error TS2322: Type 'T' is not assignable to type '{ foo: string; bar: string; }'. -!!! error TS2322: Type 'Base' is not assignable to type '{ foo: string; bar: string; }'. -!!! error TS2322: Property 'bar' is missing in type 'Base'. +!!! error TS2322: Property 'bar' is missing in type 'Base' but required in type '{ foo: string; bar: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithConstructSignatures3.ts:18:53: 'bar' is declared here. var b12: new >(x: Array, y: T) => Array; a12 = b12; // ok b12 = a12; // ok @@ -193,8 +191,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme !!! error TS2322: Types of parameters 'y' and 'y' are incompatible. !!! error TS2322: Type 'T' is not assignable to type 'Derived2[]'. !!! error TS2322: Type 'Base[]' is not assignable to type 'Derived2[]'. -!!! error TS2322: Type 'Base' is not assignable to type 'Derived2'. -!!! error TS2322: Property 'baz' is missing in type 'Base'. +!!! error TS2322: Type 'Base' is missing the following properties from type 'Derived2': baz, bar var b13: new >(x: Array, y: T) => T; a13 = b13; // ok b13 = a13; // ok diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures3.js b/tests/baselines/reference/assignmentCompatWithConstructSignatures3.js index 15ebdef5dad..932f9bb5d66 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures3.js +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures3.js @@ -107,7 +107,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; } diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures4.js b/tests/baselines/reference/assignmentCompatWithConstructSignatures4.js index aa0ce793dce..4dad18cea8f 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures4.js +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures4.js @@ -106,7 +106,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; } diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures5.js b/tests/baselines/reference/assignmentCompatWithConstructSignatures5.js index fbe0f53fa56..5f16895caf2 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures5.js +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures5.js @@ -73,7 +73,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; } diff --git a/tests/baselines/reference/assignmentCompatWithConstructSignatures6.js b/tests/baselines/reference/assignmentCompatWithConstructSignatures6.js index b476dd66420..dfce487fff1 100644 --- a/tests/baselines/reference/assignmentCompatWithConstructSignatures6.js +++ b/tests/baselines/reference/assignmentCompatWithConstructSignatures6.js @@ -50,7 +50,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; } diff --git a/tests/baselines/reference/assignmentCompatWithNumericIndexer.errors.txt b/tests/baselines/reference/assignmentCompatWithNumericIndexer.errors.txt index c5987a93ddf..9f60ca55002 100644 --- a/tests/baselines/reference/assignmentCompatWithNumericIndexer.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithNumericIndexer.errors.txt @@ -1,11 +1,9 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer.ts(14,1): error TS2322: Type 'A' is not assignable to type '{ [x: number]: Derived; }'. Index signatures are incompatible. - Type 'Base' is not assignable to type 'Derived'. - Property 'bar' is missing in type 'Base'. + Property 'bar' is missing in type 'Base' but required in type 'Derived'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer.ts(18,1): error TS2322: Type 'A' is not assignable to type '{ [x: number]: Derived2; }'. Index signatures are incompatible. - Type 'Base' is not assignable to type 'Derived2'. - Property 'baz' is missing in type 'Base'. + Type 'Base' is missing the following properties from type 'Derived2': baz, bar tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer.ts(32,9): error TS2322: Type '{ [x: number]: Derived; }' is not assignable to type 'A'. Index signatures are incompatible. Type 'Derived' is not assignable to type 'T'. @@ -40,8 +38,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme ~ !!! error TS2322: Type 'A' is not assignable to type '{ [x: number]: Derived; }'. !!! error TS2322: Index signatures are incompatible. -!!! error TS2322: Type 'Base' is not assignable to type 'Derived'. -!!! error TS2322: Property 'bar' is missing in type 'Base'. +!!! error TS2322: Property 'bar' is missing in type 'Base' but required in type 'Derived'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer.ts:4:34: 'bar' is declared here. var b2: { [x: number]: Derived2; } a = b2; @@ -49,8 +47,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme ~~ !!! error TS2322: Type 'A' is not assignable to type '{ [x: number]: Derived2; }'. !!! error TS2322: Index signatures are incompatible. -!!! error TS2322: Type 'Base' is not assignable to type 'Derived2'. -!!! error TS2322: Property 'baz' is missing in type 'Base'. +!!! error TS2322: Type 'Base' is missing the following properties from type 'Derived2': baz, bar module Generics { class A { diff --git a/tests/baselines/reference/assignmentCompatWithNumericIndexer.js b/tests/baselines/reference/assignmentCompatWithNumericIndexer.js index cbe47f21a95..6cdab6f3bed 100644 --- a/tests/baselines/reference/assignmentCompatWithNumericIndexer.js +++ b/tests/baselines/reference/assignmentCompatWithNumericIndexer.js @@ -51,7 +51,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; } diff --git a/tests/baselines/reference/assignmentCompatWithNumericIndexer2.errors.txt b/tests/baselines/reference/assignmentCompatWithNumericIndexer2.errors.txt index f91d0dd0c15..e063a16fd3f 100644 --- a/tests/baselines/reference/assignmentCompatWithNumericIndexer2.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithNumericIndexer2.errors.txt @@ -1,11 +1,9 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer2.ts(14,1): error TS2322: Type 'A' is not assignable to type '{ [x: number]: Derived; }'. Index signatures are incompatible. - Type 'Base' is not assignable to type 'Derived'. - Property 'bar' is missing in type 'Base'. + Property 'bar' is missing in type 'Base' but required in type 'Derived'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer2.ts(18,1): error TS2322: Type 'A' is not assignable to type '{ [x: number]: Derived2; }'. Index signatures are incompatible. - Type 'Base' is not assignable to type 'Derived2'. - Property 'baz' is missing in type 'Base'. + Type 'Base' is missing the following properties from type 'Derived2': baz, bar tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer2.ts(32,9): error TS2322: Type '{ [x: number]: Derived; }' is not assignable to type 'A'. Index signatures are incompatible. Type 'Derived' is not assignable to type 'T'. @@ -40,8 +38,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme ~ !!! error TS2322: Type 'A' is not assignable to type '{ [x: number]: Derived; }'. !!! error TS2322: Index signatures are incompatible. -!!! error TS2322: Type 'Base' is not assignable to type 'Derived'. -!!! error TS2322: Property 'bar' is missing in type 'Base'. +!!! error TS2322: Property 'bar' is missing in type 'Base' but required in type 'Derived'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer2.ts:4:34: 'bar' is declared here. var b2: { [x: number]: Derived2; } a = b2; @@ -49,8 +47,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme ~~ !!! error TS2322: Type 'A' is not assignable to type '{ [x: number]: Derived2; }'. !!! error TS2322: Index signatures are incompatible. -!!! error TS2322: Type 'Base' is not assignable to type 'Derived2'. -!!! error TS2322: Property 'baz' is missing in type 'Base'. +!!! error TS2322: Type 'Base' is missing the following properties from type 'Derived2': baz, bar module Generics { interface A { diff --git a/tests/baselines/reference/assignmentCompatWithNumericIndexer3.errors.txt b/tests/baselines/reference/assignmentCompatWithNumericIndexer3.errors.txt index 61f9e082a48..845edafd82c 100644 --- a/tests/baselines/reference/assignmentCompatWithNumericIndexer3.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithNumericIndexer3.errors.txt @@ -1,11 +1,9 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer3.ts(14,1): error TS2322: Type '{ [x: number]: Base; }' is not assignable to type 'A'. Index signatures are incompatible. - Type 'Base' is not assignable to type 'Derived'. - Property 'bar' is missing in type 'Base'. + Property 'bar' is missing in type 'Base' but required in type 'Derived'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer3.ts(23,1): error TS2322: Type 'A' is not assignable to type '{ [x: number]: Derived2; }'. Index signatures are incompatible. - Type 'Derived' is not assignable to type 'Derived2'. - Property 'baz' is missing in type 'Derived'. + Property 'baz' is missing in type 'Derived' but required in type 'Derived2'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer3.ts(33,9): error TS2322: Type '{ [x: number]: Derived; }' is not assignable to type 'A'. Index signatures are incompatible. Type 'Derived' is not assignable to type 'T'. @@ -29,8 +27,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme ~ !!! error TS2322: Type '{ [x: number]: Base; }' is not assignable to type 'A'. !!! error TS2322: Index signatures are incompatible. -!!! error TS2322: Type 'Base' is not assignable to type 'Derived'. -!!! error TS2322: Property 'bar' is missing in type 'Base'. +!!! error TS2322: Property 'bar' is missing in type 'Base' but required in type 'Derived'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer3.ts:4:34: 'bar' is declared here. b = a; // ok class B2 extends A { @@ -43,8 +41,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme ~~ !!! error TS2322: Type 'A' is not assignable to type '{ [x: number]: Derived2; }'. !!! error TS2322: Index signatures are incompatible. -!!! error TS2322: Type 'Derived' is not assignable to type 'Derived2'. -!!! error TS2322: Property 'baz' is missing in type 'Derived'. +!!! error TS2322: Property 'baz' is missing in type 'Derived' but required in type 'Derived2'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithNumericIndexer3.ts:5:38: 'baz' is declared here. module Generics { class A { diff --git a/tests/baselines/reference/assignmentCompatWithNumericIndexer3.js b/tests/baselines/reference/assignmentCompatWithNumericIndexer3.js index cc8dc2fb1b8..54eb5e3ac9b 100644 --- a/tests/baselines/reference/assignmentCompatWithNumericIndexer3.js +++ b/tests/baselines/reference/assignmentCompatWithNumericIndexer3.js @@ -48,7 +48,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; } diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembers4.errors.txt b/tests/baselines/reference/assignmentCompatWithObjectMembers4.errors.txt index 0fdae0b7cfa..5f53c581c79 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembers4.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithObjectMembers4.errors.txt @@ -1,11 +1,9 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers4.ts(24,5): error TS2322: Type 'T' is not assignable to type 'S'. Types of property 'foo' are incompatible. - Type 'Derived2' is not assignable to type 'Derived'. - Property 'bar' is missing in type 'Derived2'. + Property 'bar' is missing in type 'Derived2' but required in type 'Derived'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers4.ts(25,5): error TS2322: Type 'S' is not assignable to type 'T'. Types of property 'foo' are incompatible. - Type 'Derived' is not assignable to type 'Derived2'. - Property 'baz' is missing in type 'Derived'. + Property 'baz' is missing in type 'Derived' but required in type 'Derived2'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers4.ts(29,5): error TS2322: Type 'T2' is not assignable to type 'S2'. Types of property 'foo' are incompatible. Type 'Derived2' is not assignable to type 'Derived'. @@ -41,8 +39,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme Type 'Derived2' is not assignable to type 'Derived'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers4.ts(70,5): error TS2322: Type 'S' is not assignable to type 'T'. Types of property 'foo' are incompatible. - Type 'Base' is not assignable to type 'Derived2'. - Property 'baz' is missing in type 'Base'. + Property 'baz' is missing in type 'Base' but required in type 'Derived2'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers4.ts(75,5): error TS2322: Type 'S2' is not assignable to type 'T2'. Types of property 'foo' are incompatible. Type 'Base' is not assignable to type 'Derived2'. @@ -82,14 +79,14 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme ~ !!! error TS2322: Type 'T' is not assignable to type 'S'. !!! error TS2322: Types of property 'foo' are incompatible. -!!! error TS2322: Type 'Derived2' is not assignable to type 'Derived'. -!!! error TS2322: Property 'bar' is missing in type 'Derived2'. +!!! error TS2322: Property 'bar' is missing in type 'Derived2' but required in type 'Derived'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers4.ts:5:34: 'bar' is declared here. t = s; // error ~ !!! error TS2322: Type 'S' is not assignable to type 'T'. !!! error TS2322: Types of property 'foo' are incompatible. -!!! error TS2322: Type 'Derived' is not assignable to type 'Derived2'. -!!! error TS2322: Property 'baz' is missing in type 'Derived'. +!!! error TS2322: Property 'baz' is missing in type 'Derived' but required in type 'Derived2'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers4.ts:6:35: 'baz' is declared here. s = s2; // ok s = a2; // ok @@ -182,8 +179,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme ~ !!! error TS2322: Type 'S' is not assignable to type 'T'. !!! error TS2322: Types of property 'foo' are incompatible. -!!! error TS2322: Type 'Base' is not assignable to type 'Derived2'. -!!! error TS2322: Property 'baz' is missing in type 'Base'. +!!! error TS2322: Property 'baz' is missing in type 'Base' but required in type 'Derived2'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers4.ts:51:35: 'baz' is declared here. s = s2; // ok s = a2; // ok diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembers4.js b/tests/baselines/reference/assignmentCompatWithObjectMembers4.js index 46dfee1ed80..dd8d9d1bf46 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembers4.js +++ b/tests/baselines/reference/assignmentCompatWithObjectMembers4.js @@ -99,7 +99,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; } diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembers5.errors.txt b/tests/baselines/reference/assignmentCompatWithObjectMembers5.errors.txt index f9f7e48c685..ce025fde179 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembers5.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithObjectMembers5.errors.txt @@ -1,7 +1,5 @@ -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers5.ts(13,1): error TS2322: Type 'I' is not assignable to type 'C'. - Property 'foo' is missing in type 'I'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers5.ts(14,1): error TS2322: Type 'C' is not assignable to type 'I'. - Property 'fooo' is missing in type 'C'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers5.ts(13,1): error TS2741: Property 'foo' is missing in type 'I' but required in type 'C'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers5.ts(14,1): error TS2741: Property 'fooo' is missing in type 'C' but required in type 'I'. ==== tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers5.ts (2 errors) ==== @@ -19,9 +17,9 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme c = i; // error ~ -!!! error TS2322: Type 'I' is not assignable to type 'C'. -!!! error TS2322: Property 'foo' is missing in type 'I'. +!!! error TS2741: Property 'foo' is missing in type 'I' but required in type 'C'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers5.ts:2:5: 'foo' is declared here. i = c; // error ~ -!!! error TS2322: Type 'C' is not assignable to type 'I'. -!!! error TS2322: Property 'fooo' is missing in type 'C'. \ No newline at end of file +!!! error TS2741: Property 'fooo' is missing in type 'C' but required in type 'I'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembers5.ts:8:5: 'fooo' is declared here. \ No newline at end of file diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality.js b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality.js index c53936f696e..fa8ca3f7ad8 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality.js +++ b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality.js @@ -96,7 +96,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; } diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.errors.txt b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.errors.txt index 0d7fe1071e9..4121337fdad 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.errors.txt @@ -7,24 +7,15 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(39,5): error TS2559: Type 'D' has no properties in common with type '{ opt?: Base; }'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(40,5): error TS2559: Type 'E' has no properties in common with type '{ opt?: Base; }'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(41,5): error TS2559: Type 'F' has no properties in common with type '{ opt?: Base; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(74,5): error TS2322: Type 'D' is not assignable to type 'C'. - Property 'opt' is missing in type 'D'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(75,5): error TS2322: Type 'E' is not assignable to type 'C'. - Property 'opt' is missing in type 'E'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(76,5): error TS2322: Type 'F' is not assignable to type 'C'. - Property 'opt' is missing in type 'F'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(79,5): error TS2322: Type 'D' is not assignable to type '{ opt: Base; }'. - Property 'opt' is missing in type 'D'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(80,5): error TS2322: Type 'E' is not assignable to type '{ opt: Base; }'. - Property 'opt' is missing in type 'E'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(81,5): error TS2322: Type 'F' is not assignable to type '{ opt: Base; }'. - Property 'opt' is missing in type 'F'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(84,5): error TS2322: Type 'D' is not assignable to type '{ opt: Base; }'. - Property 'opt' is missing in type 'D'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(85,5): error TS2322: Type 'E' is not assignable to type '{ opt: Base; }'. - Property 'opt' is missing in type 'E'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(86,5): error TS2322: Type 'F' is not assignable to type '{ opt: Base; }'. - Property 'opt' is missing in type 'F'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(74,5): error TS2741: Property 'opt' is missing in type 'D' but required in type 'C'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(75,5): error TS2741: Property 'opt' is missing in type 'E' but required in type 'C'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(76,5): error TS2741: Property 'opt' is missing in type 'F' but required in type 'C'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(79,5): error TS2741: Property 'opt' is missing in type 'D' but required in type '{ opt: Base; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(80,5): error TS2741: Property 'opt' is missing in type 'E' but required in type '{ opt: Base; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(81,5): error TS2741: Property 'opt' is missing in type 'F' but required in type '{ opt: Base; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(84,5): error TS2741: Property 'opt' is missing in type 'D' but required in type '{ opt: Base; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(85,5): error TS2741: Property 'opt' is missing in type 'E' but required in type '{ opt: Base; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts(86,5): error TS2741: Property 'opt' is missing in type 'F' but required in type '{ opt: Base; }'. ==== tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts (18 errors) ==== @@ -121,44 +112,44 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme c = d; // error ~ -!!! error TS2322: Type 'D' is not assignable to type 'C'. -!!! error TS2322: Property 'opt' is missing in type 'D'. +!!! error TS2741: Property 'opt' is missing in type 'D' but required in type 'C'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts:53:9: 'opt' is declared here. c = e; // error ~ -!!! error TS2322: Type 'E' is not assignable to type 'C'. -!!! error TS2322: Property 'opt' is missing in type 'E'. +!!! error TS2741: Property 'opt' is missing in type 'E' but required in type 'C'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts:53:9: 'opt' is declared here. c = f; // error ~ -!!! error TS2322: Type 'F' is not assignable to type 'C'. -!!! error TS2322: Property 'opt' is missing in type 'F'. +!!! error TS2741: Property 'opt' is missing in type 'F' but required in type 'C'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts:53:9: 'opt' is declared here. c = a; // ok a = d; // error ~ -!!! error TS2322: Type 'D' is not assignable to type '{ opt: Base; }'. -!!! error TS2322: Property 'opt' is missing in type 'D'. +!!! error TS2741: Property 'opt' is missing in type 'D' but required in type '{ opt: Base; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts:57:14: 'opt' is declared here. a = e; // error ~ -!!! error TS2322: Type 'E' is not assignable to type '{ opt: Base; }'. -!!! error TS2322: Property 'opt' is missing in type 'E'. +!!! error TS2741: Property 'opt' is missing in type 'E' but required in type '{ opt: Base; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts:57:14: 'opt' is declared here. a = f; // error ~ -!!! error TS2322: Type 'F' is not assignable to type '{ opt: Base; }'. -!!! error TS2322: Property 'opt' is missing in type 'F'. +!!! error TS2741: Property 'opt' is missing in type 'F' but required in type '{ opt: Base; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts:57:14: 'opt' is declared here. a = c; // ok b = d; // error ~ -!!! error TS2322: Type 'D' is not assignable to type '{ opt: Base; }'. -!!! error TS2322: Property 'opt' is missing in type 'D'. +!!! error TS2741: Property 'opt' is missing in type 'D' but required in type '{ opt: Base; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts:58:15: 'opt' is declared here. b = e; // error ~ -!!! error TS2322: Type 'E' is not assignable to type '{ opt: Base; }'. -!!! error TS2322: Property 'opt' is missing in type 'E'. +!!! error TS2741: Property 'opt' is missing in type 'E' but required in type '{ opt: Base; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts:58:15: 'opt' is declared here. b = f; // error ~ -!!! error TS2322: Type 'F' is not assignable to type '{ opt: Base; }'. -!!! error TS2322: Property 'opt' is missing in type 'F'. +!!! error TS2741: Property 'opt' is missing in type 'F' but required in type '{ opt: Base; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersOptionality2.ts:58:15: 'opt' is declared here. b = a; // ok b = c; // ok } diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.js b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.js index 60793f2843f..918c2739ace 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.js +++ b/tests/baselines/reference/assignmentCompatWithObjectMembersOptionality2.js @@ -99,7 +99,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; } diff --git a/tests/baselines/reference/assignmentCompatWithObjectMembersStringNumericNames.errors.txt b/tests/baselines/reference/assignmentCompatWithObjectMembersStringNumericNames.errors.txt index d86c73f5cf8..b9cfa3c6b2b 100644 --- a/tests/baselines/reference/assignmentCompatWithObjectMembersStringNumericNames.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithObjectMembersStringNumericNames.errors.txt @@ -1,61 +1,32 @@ -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(21,5): error TS2322: Type 'T' is not assignable to type 'S'. - Property ''1'' is missing in type 'T'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(22,5): error TS2322: Type 'S' is not assignable to type 'T'. - Property ''1.'' is missing in type 'S'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(24,5): error TS2322: Type '{ '1.0': string; }' is not assignable to type 'S'. - Property ''1'' is missing in type '{ '1.0': string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(26,5): error TS2322: Type 'T2' is not assignable to type 'S2'. - Property ''1'' is missing in type 'T2'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(27,5): error TS2322: Type 'S2' is not assignable to type 'T2'. - Property ''1.0'' is missing in type 'S2'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(28,5): error TS2322: Type 'T' is not assignable to type 'S2'. - Property ''1'' is missing in type 'T'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(29,5): error TS2322: Type '{ '1.0': string; baz?: string; }' is not assignable to type 'S2'. - Property ''1'' is missing in type '{ '1.0': string; baz?: string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(30,5): error TS2322: Type '{ '1.0': string; }' is not assignable to type 'S2'. - Property ''1'' is missing in type '{ '1.0': string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(32,5): error TS2322: Type '{ '1.0': string; baz?: string; }' is not assignable to type '{ '1.': string; bar?: string; }'. - Property ''1.'' is missing in type '{ '1.0': string; baz?: string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(33,5): error TS2322: Type '{ '1.': string; bar?: string; }' is not assignable to type '{ '1.0': string; baz?: string; }'. - Property ''1.0'' is missing in type '{ '1.': string; bar?: string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(34,5): error TS2322: Type 'S' is not assignable to type '{ '1.': string; bar?: string; }'. - Property ''1.'' is missing in type 'S'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(35,5): error TS2322: Type 'S2' is not assignable to type '{ '1.': string; bar?: string; }'. - Property ''1.'' is missing in type 'S2'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(36,5): error TS2322: Type '{ '1.0': string; }' is not assignable to type '{ '1.': string; bar?: string; }'. - Property ''1.'' is missing in type '{ '1.0': string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(38,5): error TS2322: Type '{ '1': string; }' is not assignable to type '{ '1.0': string; }'. - Property ''1.0'' is missing in type '{ '1': string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(39,5): error TS2322: Type '{ '1.0': string; }' is not assignable to type '{ '1': string; }'. - Property ''1'' is missing in type '{ '1.0': string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(42,5): error TS2322: Type 'T' is not assignable to type '{ '1.0': string; }'. - Property ''1.0'' is missing in type 'T'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(65,5): error TS2322: Type '{ '1.0': string; }' is not assignable to type 'S'. - Property ''1'' is missing in type '{ '1.0': string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(71,5): error TS2322: Type '{ '1.0': string; }' is not assignable to type 'S2'. - Property ''1'' is missing in type '{ '1.0': string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(73,5): error TS2322: Type '{ 1.0: string; baz?: string; }' is not assignable to type '{ '1.': string; bar?: string; }'. - Property ''1.'' is missing in type '{ 1.0: string; baz?: string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(74,5): error TS2322: Type '{ '1.': string; bar?: string; }' is not assignable to type '{ 1.0: string; baz?: string; }'. - Property '1.0' is missing in type '{ '1.': string; bar?: string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(75,5): error TS2322: Type 'S' is not assignable to type '{ '1.': string; bar?: string; }'. - Property ''1.'' is missing in type 'S'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(76,5): error TS2322: Type 'S2' is not assignable to type '{ '1.': string; bar?: string; }'. - Property ''1.'' is missing in type 'S2'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(77,5): error TS2322: Type '{ '1.0': string; }' is not assignable to type '{ '1.': string; bar?: string; }'. - Property ''1.'' is missing in type '{ '1.0': string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(78,5): error TS2322: Type '{ 1.: string; }' is not assignable to type '{ '1.': string; bar?: string; }'. - Property ''1.'' is missing in type '{ 1.: string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(80,5): error TS2322: Type '{ 1.: string; }' is not assignable to type '{ '1.0': string; }'. - Property ''1.0'' is missing in type '{ 1.: string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(81,5): error TS2322: Type '{ '1.0': string; }' is not assignable to type '{ 1.: string; }'. - Property '1.' is missing in type '{ '1.0': string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(82,5): error TS2322: Type '{ 1.0: string; baz?: string; }' is not assignable to type '{ '1.0': string; }'. - Property ''1.0'' is missing in type '{ 1.0: string; baz?: string; }'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(83,5): error TS2322: Type 'T2' is not assignable to type '{ '1.0': string; }'. - Property ''1.0'' is missing in type 'T2'. -tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(84,5): error TS2322: Type 'T' is not assignable to type '{ '1.0': string; }'. - Property ''1.0'' is missing in type 'T'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(21,5): error TS2741: Property ''1'' is missing in type 'T' but required in type 'S'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(22,5): error TS2741: Property ''1.'' is missing in type 'S' but required in type 'T'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(24,5): error TS2741: Property ''1'' is missing in type '{ '1.0': string; }' but required in type 'S'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(26,5): error TS2741: Property ''1'' is missing in type 'T2' but required in type 'S2'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(27,5): error TS2741: Property ''1.0'' is missing in type 'S2' but required in type 'T2'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(28,5): error TS2741: Property ''1'' is missing in type 'T' but required in type 'S2'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(29,5): error TS2741: Property ''1'' is missing in type '{ '1.0': string; baz?: string; }' but required in type 'S2'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(30,5): error TS2741: Property ''1'' is missing in type '{ '1.0': string; }' but required in type 'S2'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(32,5): error TS2741: Property ''1.'' is missing in type '{ '1.0': string; baz?: string; }' but required in type '{ '1.': string; bar?: string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(33,5): error TS2741: Property ''1.0'' is missing in type '{ '1.': string; bar?: string; }' but required in type '{ '1.0': string; baz?: string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(34,5): error TS2741: Property ''1.'' is missing in type 'S' but required in type '{ '1.': string; bar?: string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(35,5): error TS2741: Property ''1.'' is missing in type 'S2' but required in type '{ '1.': string; bar?: string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(36,5): error TS2741: Property ''1.'' is missing in type '{ '1.0': string; }' but required in type '{ '1.': string; bar?: string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(38,5): error TS2741: Property ''1.0'' is missing in type '{ '1': string; }' but required in type '{ '1.0': string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(39,5): error TS2741: Property ''1'' is missing in type '{ '1.0': string; }' but required in type '{ '1': string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(42,5): error TS2741: Property ''1.0'' is missing in type 'T' but required in type '{ '1.0': string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(65,5): error TS2741: Property ''1'' is missing in type '{ '1.0': string; }' but required in type 'S'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(71,5): error TS2741: Property ''1'' is missing in type '{ '1.0': string; }' but required in type 'S2'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(73,5): error TS2741: Property ''1.'' is missing in type '{ 1.0: string; baz?: string; }' but required in type '{ '1.': string; bar?: string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(74,5): error TS2741: Property '1.0' is missing in type '{ '1.': string; bar?: string; }' but required in type '{ 1.0: string; baz?: string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(75,5): error TS2741: Property ''1.'' is missing in type 'S' but required in type '{ '1.': string; bar?: string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(76,5): error TS2741: Property ''1.'' is missing in type 'S2' but required in type '{ '1.': string; bar?: string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(77,5): error TS2741: Property ''1.'' is missing in type '{ '1.0': string; }' but required in type '{ '1.': string; bar?: string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(78,5): error TS2741: Property ''1.'' is missing in type '{ 1.: string; }' but required in type '{ '1.': string; bar?: string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(80,5): error TS2741: Property ''1.0'' is missing in type '{ 1.: string; }' but required in type '{ '1.0': string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(81,5): error TS2741: Property '1.' is missing in type '{ '1.0': string; }' but required in type '{ 1.: string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(82,5): error TS2741: Property ''1.0'' is missing in type '{ 1.0: string; baz?: string; }' but required in type '{ '1.0': string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(83,5): error TS2741: Property ''1.0'' is missing in type 'T2' but required in type '{ '1.0': string; }'. +tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts(84,5): error TS2741: Property ''1.0'' is missing in type 'T' but required in type '{ '1.0': string; }'. ==== tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts (29 errors) ==== @@ -81,74 +52,74 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme s = t; ~ -!!! error TS2322: Type 'T' is not assignable to type 'S'. -!!! error TS2322: Property ''1'' is missing in type 'T'. +!!! error TS2741: Property ''1'' is missing in type 'T' but required in type 'S'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:5:15: ''1'' is declared here. t = s; ~ -!!! error TS2322: Type 'S' is not assignable to type 'T'. -!!! error TS2322: Property ''1.'' is missing in type 'S'. +!!! error TS2741: Property ''1.'' is missing in type 'S' but required in type 'T'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:6:15: ''1.'' is declared here. s = s2; // ok s = a2; ~ -!!! error TS2322: Type '{ '1.0': string; }' is not assignable to type 'S'. -!!! error TS2322: Property ''1'' is missing in type '{ '1.0': string; }'. +!!! error TS2741: Property ''1'' is missing in type '{ '1.0': string; }' but required in type 'S'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:5:15: ''1'' is declared here. s2 = t2; ~~ -!!! error TS2322: Type 'T2' is not assignable to type 'S2'. -!!! error TS2322: Property ''1'' is missing in type 'T2'. +!!! error TS2741: Property ''1'' is missing in type 'T2' but required in type 'S2'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:10:20: ''1'' is declared here. t2 = s2; ~~ -!!! error TS2322: Type 'S2' is not assignable to type 'T2'. -!!! error TS2322: Property ''1.0'' is missing in type 'S2'. +!!! error TS2741: Property ''1.0'' is missing in type 'S2' but required in type 'T2'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:11:20: ''1.0'' is declared here. s2 = t; ~~ -!!! error TS2322: Type 'T' is not assignable to type 'S2'. -!!! error TS2322: Property ''1'' is missing in type 'T'. +!!! error TS2741: Property ''1'' is missing in type 'T' but required in type 'S2'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:10:20: ''1'' is declared here. s2 = b; ~~ -!!! error TS2322: Type '{ '1.0': string; baz?: string; }' is not assignable to type 'S2'. -!!! error TS2322: Property ''1'' is missing in type '{ '1.0': string; baz?: string; }'. +!!! error TS2741: Property ''1'' is missing in type '{ '1.0': string; baz?: string; }' but required in type 'S2'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:10:20: ''1'' is declared here. s2 = a2; ~~ -!!! error TS2322: Type '{ '1.0': string; }' is not assignable to type 'S2'. -!!! error TS2322: Property ''1'' is missing in type '{ '1.0': string; }'. +!!! error TS2741: Property ''1'' is missing in type '{ '1.0': string; }' but required in type 'S2'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:10:20: ''1'' is declared here. a = b; ~ -!!! error TS2322: Type '{ '1.0': string; baz?: string; }' is not assignable to type '{ '1.': string; bar?: string; }'. -!!! error TS2322: Property ''1.'' is missing in type '{ '1.0': string; baz?: string; }'. +!!! error TS2741: Property ''1.'' is missing in type '{ '1.0': string; baz?: string; }' but required in type '{ '1.': string; bar?: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:15:14: ''1.'' is declared here. b = a; ~ -!!! error TS2322: Type '{ '1.': string; bar?: string; }' is not assignable to type '{ '1.0': string; baz?: string; }'. -!!! error TS2322: Property ''1.0'' is missing in type '{ '1.': string; bar?: string; }'. +!!! error TS2741: Property ''1.0'' is missing in type '{ '1.': string; bar?: string; }' but required in type '{ '1.0': string; baz?: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:16:14: ''1.0'' is declared here. a = s; ~ -!!! error TS2322: Type 'S' is not assignable to type '{ '1.': string; bar?: string; }'. -!!! error TS2322: Property ''1.'' is missing in type 'S'. +!!! error TS2741: Property ''1.'' is missing in type 'S' but required in type '{ '1.': string; bar?: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:15:14: ''1.'' is declared here. a = s2; ~ -!!! error TS2322: Type 'S2' is not assignable to type '{ '1.': string; bar?: string; }'. -!!! error TS2322: Property ''1.'' is missing in type 'S2'. +!!! error TS2741: Property ''1.'' is missing in type 'S2' but required in type '{ '1.': string; bar?: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:15:14: ''1.'' is declared here. a = a2; ~ -!!! error TS2322: Type '{ '1.0': string; }' is not assignable to type '{ '1.': string; bar?: string; }'. -!!! error TS2322: Property ''1.'' is missing in type '{ '1.0': string; }'. +!!! error TS2741: Property ''1.'' is missing in type '{ '1.0': string; }' but required in type '{ '1.': string; bar?: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:15:14: ''1.'' is declared here. a2 = b2; ~~ -!!! error TS2322: Type '{ '1': string; }' is not assignable to type '{ '1.0': string; }'. -!!! error TS2322: Property ''1.0'' is missing in type '{ '1': string; }'. +!!! error TS2741: Property ''1.0'' is missing in type '{ '1': string; }' but required in type '{ '1.0': string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:18:16: ''1.0'' is declared here. b2 = a2; ~~ -!!! error TS2322: Type '{ '1.0': string; }' is not assignable to type '{ '1': string; }'. -!!! error TS2322: Property ''1'' is missing in type '{ '1.0': string; }'. +!!! error TS2741: Property ''1'' is missing in type '{ '1.0': string; }' but required in type '{ '1': string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:19:16: ''1'' is declared here. a2 = b; // ok a2 = t2; // ok a2 = t; ~~ -!!! error TS2322: Type 'T' is not assignable to type '{ '1.0': string; }'. -!!! error TS2322: Property ''1.0'' is missing in type 'T'. +!!! error TS2741: Property ''1.0'' is missing in type 'T' but required in type '{ '1.0': string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:18:16: ''1.0'' is declared here. } module NumbersAndStrings { @@ -173,8 +144,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme s = s2; // ok s = a2; // error ~ -!!! error TS2322: Type '{ '1.0': string; }' is not assignable to type 'S'. -!!! error TS2322: Property ''1'' is missing in type '{ '1.0': string; }'. +!!! error TS2741: Property ''1'' is missing in type '{ '1.0': string; }' but required in type 'S'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:46:15: ''1'' is declared here. s2 = t2; // ok t2 = s2; // ok @@ -182,52 +153,52 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme s2 = b; // ok s2 = a2; // error ~~ -!!! error TS2322: Type '{ '1.0': string; }' is not assignable to type 'S2'. -!!! error TS2322: Property ''1'' is missing in type '{ '1.0': string; }'. +!!! error TS2741: Property ''1'' is missing in type '{ '1.0': string; }' but required in type 'S2'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:51:20: ''1'' is declared here. a = b; // error ~ -!!! error TS2322: Type '{ 1.0: string; baz?: string; }' is not assignable to type '{ '1.': string; bar?: string; }'. -!!! error TS2322: Property ''1.'' is missing in type '{ 1.0: string; baz?: string; }'. +!!! error TS2741: Property ''1.'' is missing in type '{ 1.0: string; baz?: string; }' but required in type '{ '1.': string; bar?: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:56:14: ''1.'' is declared here. b = a; // error ~ -!!! error TS2322: Type '{ '1.': string; bar?: string; }' is not assignable to type '{ 1.0: string; baz?: string; }'. -!!! error TS2322: Property '1.0' is missing in type '{ '1.': string; bar?: string; }'. +!!! error TS2741: Property '1.0' is missing in type '{ '1.': string; bar?: string; }' but required in type '{ 1.0: string; baz?: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:57:14: '1.0' is declared here. a = s; // error ~ -!!! error TS2322: Type 'S' is not assignable to type '{ '1.': string; bar?: string; }'. -!!! error TS2322: Property ''1.'' is missing in type 'S'. +!!! error TS2741: Property ''1.'' is missing in type 'S' but required in type '{ '1.': string; bar?: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:56:14: ''1.'' is declared here. a = s2; // error ~ -!!! error TS2322: Type 'S2' is not assignable to type '{ '1.': string; bar?: string; }'. -!!! error TS2322: Property ''1.'' is missing in type 'S2'. +!!! error TS2741: Property ''1.'' is missing in type 'S2' but required in type '{ '1.': string; bar?: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:56:14: ''1.'' is declared here. a = a2; // error ~ -!!! error TS2322: Type '{ '1.0': string; }' is not assignable to type '{ '1.': string; bar?: string; }'. -!!! error TS2322: Property ''1.'' is missing in type '{ '1.0': string; }'. +!!! error TS2741: Property ''1.'' is missing in type '{ '1.0': string; }' but required in type '{ '1.': string; bar?: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:56:14: ''1.'' is declared here. a = b2; // error ~ -!!! error TS2322: Type '{ 1.: string; }' is not assignable to type '{ '1.': string; bar?: string; }'. -!!! error TS2322: Property ''1.'' is missing in type '{ 1.: string; }'. +!!! error TS2741: Property ''1.'' is missing in type '{ 1.: string; }' but required in type '{ '1.': string; bar?: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:56:14: ''1.'' is declared here. a2 = b2; // error ~~ -!!! error TS2322: Type '{ 1.: string; }' is not assignable to type '{ '1.0': string; }'. -!!! error TS2322: Property ''1.0'' is missing in type '{ 1.: string; }'. +!!! error TS2741: Property ''1.0'' is missing in type '{ 1.: string; }' but required in type '{ '1.0': string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:59:16: ''1.0'' is declared here. b2 = a2; // error ~~ -!!! error TS2322: Type '{ '1.0': string; }' is not assignable to type '{ 1.: string; }'. -!!! error TS2322: Property '1.' is missing in type '{ '1.0': string; }'. +!!! error TS2741: Property '1.' is missing in type '{ '1.0': string; }' but required in type '{ 1.: string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:60:16: '1.' is declared here. a2 = b; // error ~~ -!!! error TS2322: Type '{ 1.0: string; baz?: string; }' is not assignable to type '{ '1.0': string; }'. -!!! error TS2322: Property ''1.0'' is missing in type '{ 1.0: string; baz?: string; }'. +!!! error TS2741: Property ''1.0'' is missing in type '{ 1.0: string; baz?: string; }' but required in type '{ '1.0': string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:59:16: ''1.0'' is declared here. a2 = t2; // error ~~ -!!! error TS2322: Type 'T2' is not assignable to type '{ '1.0': string; }'. -!!! error TS2322: Property ''1.0'' is missing in type 'T2'. +!!! error TS2741: Property ''1.0'' is missing in type 'T2' but required in type '{ '1.0': string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:59:16: ''1.0'' is declared here. a2 = t; // error ~~ -!!! error TS2322: Type 'T' is not assignable to type '{ '1.0': string; }'. -!!! error TS2322: Property ''1.0'' is missing in type 'T'. +!!! error TS2741: Property ''1.0'' is missing in type 'T' but required in type '{ '1.0': string; }'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithObjectMembersStringNumericNames.ts:59:16: ''1.0'' is declared here. } \ No newline at end of file diff --git a/tests/baselines/reference/assignmentCompatWithStringIndexer.errors.txt b/tests/baselines/reference/assignmentCompatWithStringIndexer.errors.txt index 51762bb9418..523c6b97337 100644 --- a/tests/baselines/reference/assignmentCompatWithStringIndexer.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithStringIndexer.errors.txt @@ -1,11 +1,9 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer.ts(15,1): error TS2322: Type 'A' is not assignable to type '{ [x: string]: Derived; }'. Index signatures are incompatible. - Type 'Base' is not assignable to type 'Derived'. - Property 'bar' is missing in type 'Base'. + Property 'bar' is missing in type 'Base' but required in type 'Derived'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer.ts(19,1): error TS2322: Type 'A' is not assignable to type '{ [x: string]: Derived2; }'. Index signatures are incompatible. - Type 'Base' is not assignable to type 'Derived2'. - Property 'baz' is missing in type 'Base'. + Type 'Base' is missing the following properties from type 'Derived2': baz, bar tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer.ts(33,5): error TS2322: Type 'A' is not assignable to type '{ [x: string]: Derived; }'. Index signatures are incompatible. Type 'Base' is not assignable to type 'Derived'. @@ -47,8 +45,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme ~ !!! error TS2322: Type 'A' is not assignable to type '{ [x: string]: Derived; }'. !!! error TS2322: Index signatures are incompatible. -!!! error TS2322: Type 'Base' is not assignable to type 'Derived'. -!!! error TS2322: Property 'bar' is missing in type 'Base'. +!!! error TS2322: Property 'bar' is missing in type 'Base' but required in type 'Derived'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer.ts:4:34: 'bar' is declared here. var b2: { [x: string]: Derived2; } a = b2; // ok @@ -56,8 +54,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme ~~ !!! error TS2322: Type 'A' is not assignable to type '{ [x: string]: Derived2; }'. !!! error TS2322: Index signatures are incompatible. -!!! error TS2322: Type 'Base' is not assignable to type 'Derived2'. -!!! error TS2322: Property 'baz' is missing in type 'Base'. +!!! error TS2322: Type 'Base' is missing the following properties from type 'Derived2': baz, bar module Generics { class A { diff --git a/tests/baselines/reference/assignmentCompatWithStringIndexer.js b/tests/baselines/reference/assignmentCompatWithStringIndexer.js index 62b22fc0091..9a67a00bac0 100644 --- a/tests/baselines/reference/assignmentCompatWithStringIndexer.js +++ b/tests/baselines/reference/assignmentCompatWithStringIndexer.js @@ -61,7 +61,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; } diff --git a/tests/baselines/reference/assignmentCompatWithStringIndexer2.errors.txt b/tests/baselines/reference/assignmentCompatWithStringIndexer2.errors.txt index 0b0d70d01bb..180012decc2 100644 --- a/tests/baselines/reference/assignmentCompatWithStringIndexer2.errors.txt +++ b/tests/baselines/reference/assignmentCompatWithStringIndexer2.errors.txt @@ -1,11 +1,9 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer2.ts(15,1): error TS2322: Type 'A' is not assignable to type '{ [x: string]: Derived; }'. Index signatures are incompatible. - Type 'Base' is not assignable to type 'Derived'. - Property 'bar' is missing in type 'Base'. + Property 'bar' is missing in type 'Base' but required in type 'Derived'. tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer2.ts(19,1): error TS2322: Type 'A' is not assignable to type '{ [x: string]: Derived2; }'. Index signatures are incompatible. - Type 'Base' is not assignable to type 'Derived2'. - Property 'baz' is missing in type 'Base'. + Type 'Base' is missing the following properties from type 'Derived2': baz, bar tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer2.ts(33,5): error TS2322: Type 'A' is not assignable to type '{ [x: string]: Derived; }'. Index signatures are incompatible. Type 'Base' is not assignable to type 'Derived'. @@ -47,8 +45,8 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme ~ !!! error TS2322: Type 'A' is not assignable to type '{ [x: string]: Derived; }'. !!! error TS2322: Index signatures are incompatible. -!!! error TS2322: Type 'Base' is not assignable to type 'Derived'. -!!! error TS2322: Property 'bar' is missing in type 'Base'. +!!! error TS2322: Property 'bar' is missing in type 'Base' but required in type 'Derived'. +!!! related TS2728 tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithStringIndexer2.ts:4:34: 'bar' is declared here. var b2: { [x: string]: Derived2; } a = b2; // ok @@ -56,8 +54,7 @@ tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignme ~~ !!! error TS2322: Type 'A' is not assignable to type '{ [x: string]: Derived2; }'. !!! error TS2322: Index signatures are incompatible. -!!! error TS2322: Type 'Base' is not assignable to type 'Derived2'. -!!! error TS2322: Property 'baz' is missing in type 'Base'. +!!! error TS2322: Type 'Base' is missing the following properties from type 'Derived2': baz, bar module Generics { interface A { diff --git a/tests/baselines/reference/assignmentCompatability_checking-apply-member-off-of-function-interface.errors.txt b/tests/baselines/reference/assignmentCompatability_checking-apply-member-off-of-function-interface.errors.txt index e9adcba03b7..cc61e0ebfe4 100644 --- a/tests/baselines/reference/assignmentCompatability_checking-apply-member-off-of-function-interface.errors.txt +++ b/tests/baselines/reference/assignmentCompatability_checking-apply-member-off-of-function-interface.errors.txt @@ -1,14 +1,12 @@ tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts(10,1): error TS2322: Type '""' is not assignable to type 'Applicable'. -tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts(11,1): error TS2322: Type 'string[]' is not assignable to type 'Applicable'. - Property 'apply' is missing in type 'string[]'. +tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts(11,1): error TS2741: Property 'apply' is missing in type 'string[]' but required in type 'Applicable'. tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts(12,1): error TS2322: Type '4' is not assignable to type 'Applicable'. -tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts(13,1): error TS2322: Type '{}' is not assignable to type 'Applicable'. - Property 'apply' is missing in type '{}'. +tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts(13,1): error TS2741: Property 'apply' is missing in type '{}' but required in type 'Applicable'. tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts(22,4): error TS2345: Argument of type '""' is not assignable to parameter of type 'Applicable'. tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts(23,4): error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'Applicable'. tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts(24,4): error TS2345: Argument of type '4' is not assignable to parameter of type 'Applicable'. tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts(25,4): error TS2345: Argument of type '{}' is not assignable to parameter of type 'Applicable'. - Property 'apply' is missing in type '{}'. + Property 'apply' is missing in type '{}' but required in type 'Applicable'. ==== tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts (8 errors) ==== @@ -26,15 +24,15 @@ tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-functi !!! error TS2322: Type '""' is not assignable to type 'Applicable'. x = ['']; ~ -!!! error TS2322: Type 'string[]' is not assignable to type 'Applicable'. -!!! error TS2322: Property 'apply' is missing in type 'string[]'. +!!! error TS2741: Property 'apply' is missing in type 'string[]' but required in type 'Applicable'. +!!! related TS2728 tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts:4:5: 'apply' is declared here. x = 4; ~ !!! error TS2322: Type '4' is not assignable to type 'Applicable'. x = {}; ~ -!!! error TS2322: Type '{}' is not assignable to type 'Applicable'. -!!! error TS2322: Property 'apply' is missing in type '{}'. +!!! error TS2741: Property 'apply' is missing in type '{}' but required in type 'Applicable'. +!!! related TS2728 tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts:4:5: 'apply' is declared here. // Should work function f() { }; @@ -55,7 +53,8 @@ tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-functi fn({}); ~~ !!! error TS2345: Argument of type '{}' is not assignable to parameter of type 'Applicable'. -!!! error TS2345: Property 'apply' is missing in type '{}'. +!!! error TS2345: Property 'apply' is missing in type '{}' but required in type 'Applicable'. +!!! related TS2728 tests/cases/compiler/assignmentCompatability_checking-apply-member-off-of-function-interface.ts:4:5: 'apply' is declared here. // Should work diff --git a/tests/baselines/reference/assignmentCompatability_checking-call-member-off-of-function-interface.errors.txt b/tests/baselines/reference/assignmentCompatability_checking-call-member-off-of-function-interface.errors.txt index 17556302178..d1894692635 100644 --- a/tests/baselines/reference/assignmentCompatability_checking-call-member-off-of-function-interface.errors.txt +++ b/tests/baselines/reference/assignmentCompatability_checking-call-member-off-of-function-interface.errors.txt @@ -1,14 +1,12 @@ tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts(10,1): error TS2322: Type '""' is not assignable to type 'Callable'. -tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts(11,1): error TS2322: Type 'string[]' is not assignable to type 'Callable'. - Property 'call' is missing in type 'string[]'. +tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts(11,1): error TS2741: Property 'call' is missing in type 'string[]' but required in type 'Callable'. tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts(12,1): error TS2322: Type '4' is not assignable to type 'Callable'. -tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts(13,1): error TS2322: Type '{}' is not assignable to type 'Callable'. - Property 'call' is missing in type '{}'. +tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts(13,1): error TS2741: Property 'call' is missing in type '{}' but required in type 'Callable'. tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts(22,4): error TS2345: Argument of type '""' is not assignable to parameter of type 'Callable'. tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts(23,4): error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'Callable'. tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts(24,4): error TS2345: Argument of type '4' is not assignable to parameter of type 'Callable'. tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts(25,4): error TS2345: Argument of type '{}' is not assignable to parameter of type 'Callable'. - Property 'call' is missing in type '{}'. + Property 'call' is missing in type '{}' but required in type 'Callable'. ==== tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts (8 errors) ==== @@ -26,15 +24,15 @@ tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-functio !!! error TS2322: Type '""' is not assignable to type 'Callable'. x = ['']; ~ -!!! error TS2322: Type 'string[]' is not assignable to type 'Callable'. -!!! error TS2322: Property 'call' is missing in type 'string[]'. +!!! error TS2741: Property 'call' is missing in type 'string[]' but required in type 'Callable'. +!!! related TS2728 tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts:4:5: 'call' is declared here. x = 4; ~ !!! error TS2322: Type '4' is not assignable to type 'Callable'. x = {}; ~ -!!! error TS2322: Type '{}' is not assignable to type 'Callable'. -!!! error TS2322: Property 'call' is missing in type '{}'. +!!! error TS2741: Property 'call' is missing in type '{}' but required in type 'Callable'. +!!! related TS2728 tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts:4:5: 'call' is declared here. // Should work function f() { }; @@ -55,7 +53,8 @@ tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-functio fn({}); ~~ !!! error TS2345: Argument of type '{}' is not assignable to parameter of type 'Callable'. -!!! error TS2345: Property 'call' is missing in type '{}'. +!!! error TS2345: Property 'call' is missing in type '{}' but required in type 'Callable'. +!!! related TS2728 tests/cases/compiler/assignmentCompatability_checking-call-member-off-of-function-interface.ts:4:5: 'call' is declared here. // Should work diff --git a/tests/baselines/reference/assignmentLHSIsValue.js b/tests/baselines/reference/assignmentLHSIsValue.js index 1eacd789df1..dd7f28cb003 100644 --- a/tests/baselines/reference/assignmentLHSIsValue.js +++ b/tests/baselines/reference/assignmentLHSIsValue.js @@ -77,7 +77,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; } diff --git a/tests/baselines/reference/assignmentToObjectAndFunction.errors.txt b/tests/baselines/reference/assignmentToObjectAndFunction.errors.txt index 8ba04d8ab2c..897c96a1c8f 100644 --- a/tests/baselines/reference/assignmentToObjectAndFunction.errors.txt +++ b/tests/baselines/reference/assignmentToObjectAndFunction.errors.txt @@ -1,6 +1,5 @@ tests/cases/compiler/assignmentToObjectAndFunction.ts(1,24): error TS2322: Type 'number' is not assignable to type '() => string'. -tests/cases/compiler/assignmentToObjectAndFunction.ts(8,5): error TS2322: Type '{}' is not assignable to type 'Function'. - Property 'apply' is missing in type '{}'. +tests/cases/compiler/assignmentToObjectAndFunction.ts(8,5): error TS2740: Type '{}' is missing the following properties from type 'Function': apply, call, bind, prototype, and 3 more. tests/cases/compiler/assignmentToObjectAndFunction.ts(29,5): error TS2322: Type 'typeof bad' is not assignable to type 'Function'. Types of property 'apply' are incompatible. Type 'number' is not assignable to type '(this: Function, thisArg: any, argArray?: any) => any'. @@ -10,7 +9,6 @@ tests/cases/compiler/assignmentToObjectAndFunction.ts(29,5): error TS2322: Type var errObj: Object = { toString: 0 }; // Error, incompatible toString ~~~~~~~~ !!! error TS2322: Type 'number' is not assignable to type '() => string'. -!!! related TS6500 /.ts/lib.es5.d.ts:125:5: The expected type comes from property 'toString' which is declared here on type 'Object' var goodObj: Object = { toString(x?) { return ""; @@ -19,8 +17,7 @@ tests/cases/compiler/assignmentToObjectAndFunction.ts(29,5): error TS2322: Type var errFun: Function = {}; // Error for no call signature ~~~~~~ -!!! error TS2322: Type '{}' is not assignable to type 'Function'. -!!! error TS2322: Property 'apply' is missing in type '{}'. +!!! error TS2740: Type '{}' is missing the following properties from type 'Function': apply, call, bind, prototype, and 3 more. function foo() { } module foo { diff --git a/tests/baselines/reference/assignments.errors.txt b/tests/baselines/reference/assignments.errors.txt index cb8b7a17bdf..19cdbd813a6 100644 --- a/tests/baselines/reference/assignments.errors.txt +++ b/tests/baselines/reference/assignments.errors.txt @@ -1,7 +1,7 @@ tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(11,1): error TS2708: Cannot use namespace 'M' as a value. tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(14,1): error TS2539: Cannot assign to 'C' because it is not a variable. tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(17,1): error TS2539: Cannot assign to 'E' because it is not a variable. -tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(18,3): error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. +tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(18,3): error TS2540: Cannot assign to 'A' because it is a read-only property. tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(21,1): error TS2539: Cannot assign to 'fn' because it is not a variable. tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(31,1): error TS2693: 'I' only refers to a type, but is being used as a value here. @@ -32,7 +32,7 @@ tests/cases/conformance/expressions/valuesAndReferences/assignments.ts(31,1): er !!! error TS2539: Cannot assign to 'E' because it is not a variable. E.A = null; // OK per spec, Error per implementation (509581) ~ -!!! error TS2540: Cannot assign to 'A' because it is a constant or a read-only property. +!!! error TS2540: Cannot assign to 'A' because it is a read-only property. function fn() { } fn = null; // Should be error diff --git a/tests/baselines/reference/asyncImportedPromise_es5.js b/tests/baselines/reference/asyncImportedPromise_es5.js index 5aabc56c56a..f17459321c8 100644 --- a/tests/baselines/reference/asyncImportedPromise_es5.js +++ b/tests/baselines/reference/asyncImportedPromise_es5.js @@ -17,7 +17,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; } diff --git a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.js b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.js index 4b33d8492e9..2a910226703 100644 --- a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.js +++ b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.js @@ -2,14 +2,19 @@ class A { x() { } + y() { + } } class B extends A { // async method with only call/get on 'super' does not require a binding async simple() { const _super = null; + const _superIndex = null; // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); @@ -24,6 +29,7 @@ class B extends A { // async method with assignment/destructuring on 'super' requires a binding async advanced() { const _super = null; + const _superIndex = null; const f = () => {}; // call with property access @@ -50,7 +56,8 @@ class B extends A { // destructuring assign with element access ({ f: super["x"] } = { f }); } -} +} + //// [asyncMethodWithSuperConflict_es6.js] var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { @@ -64,48 +71,61 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge class A { x() { } + y() { + } } class B extends A { // async method with only call/get on 'super' does not require a binding simple() { - const _super_1 = name => super[name]; + const _superIndex_1 = name => super[name]; + const _super_1 = Object.create(null, { + x: { get: () => super.x }, + y: { get: () => super.y } + }); return __awaiter(this, void 0, void 0, function* () { const _super = null; + const _superIndex = null; // call with property access - _super_1("x").call(this); + _super_1.x.call(this); + // call additional property. + _super_1.y.call(this); // call with element access - _super_1("x").call(this); + _superIndex_1("x").call(this); // property access (read) - const a = _super_1("x"); + const a = _super_1.x; // element access (read) - const b = _super_1("x"); + const b = _superIndex_1("x"); }); } // async method with assignment/destructuring on 'super' requires a binding advanced() { - const _super_1 = (function (geti, seti) { + const _superIndex_1 = (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_1 = Object.create(null, { + x: { get: () => super.x, set: v => super.x = v } + }); return __awaiter(this, void 0, void 0, function* () { const _super = null; + const _superIndex = null; const f = () => { }; // call with property access - _super_1("x").value.call(this); + _super_1.x.call(this); // call with element access - _super_1("x").value.call(this); + _superIndex_1("x").value.call(this); // property access (read) - const a = _super_1("x").value; + const a = _super_1.x; // element access (read) - const b = _super_1("x").value; + const b = _superIndex_1("x").value; // property access (assign) - _super_1("x").value = f; + _super_1.x = f; // element access (assign) - _super_1("x").value = f; + _superIndex_1("x").value = f; // destructuring assign with property access - ({ f: _super_1("x").value } = { f }); + ({ f: _super_1.x } = { f }); // destructuring assign with element access - ({ f: _super_1("x").value } = { f }); + ({ f: _superIndex_1("x").value } = { f }); }); } } diff --git a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.symbols b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.symbols index ddc8fdf013c..161b6eca39b 100644 --- a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.symbols +++ b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.symbols @@ -5,18 +5,24 @@ class A { x() { >x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) } + y() { +>y : Symbol(A.y, Decl(asyncMethodWithSuperConflict_es6.ts, 2, 5)) + } } class B extends A { ->B : Symbol(B, Decl(asyncMethodWithSuperConflict_es6.ts, 3, 1)) +>B : Symbol(B, Decl(asyncMethodWithSuperConflict_es6.ts, 5, 1)) >A : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) // async method with only call/get on 'super' does not require a binding async simple() { ->simple : Symbol(B.simple, Decl(asyncMethodWithSuperConflict_es6.ts, 5, 19)) +>simple : Symbol(B.simple, Decl(asyncMethodWithSuperConflict_es6.ts, 7, 19)) const _super = null; ->_super : Symbol(_super, Decl(asyncMethodWithSuperConflict_es6.ts, 8, 13)) +>_super : Symbol(_super, Decl(asyncMethodWithSuperConflict_es6.ts, 10, 13)) + + const _superIndex = null; +>_superIndex : Symbol(_superIndex, Decl(asyncMethodWithSuperConflict_es6.ts, 11, 13)) // call with property access super.x(); @@ -24,6 +30,12 @@ class B extends A { >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) + // call additional property. + super.y(); +>super.y : Symbol(A.y, Decl(asyncMethodWithSuperConflict_es6.ts, 2, 5)) +>super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) +>y : Symbol(A.y, Decl(asyncMethodWithSuperConflict_es6.ts, 2, 5)) + // call with element access super["x"](); >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) @@ -31,27 +43,30 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuperConflict_es6.ts, 16, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuperConflict_es6.ts, 21, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuperConflict_es6.ts, 19, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuperConflict_es6.ts, 24, 13)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) } // async method with assignment/destructuring on 'super' requires a binding async advanced() { ->advanced : Symbol(B.advanced, Decl(asyncMethodWithSuperConflict_es6.ts, 20, 5)) +>advanced : Symbol(B.advanced, Decl(asyncMethodWithSuperConflict_es6.ts, 25, 5)) const _super = null; ->_super : Symbol(_super, Decl(asyncMethodWithSuperConflict_es6.ts, 24, 13)) +>_super : Symbol(_super, Decl(asyncMethodWithSuperConflict_es6.ts, 29, 13)) + + const _superIndex = null; +>_superIndex : Symbol(_superIndex, Decl(asyncMethodWithSuperConflict_es6.ts, 30, 13)) const f = () => {}; ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 25, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 31, 13)) // call with property access super.x(); @@ -66,14 +81,14 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuperConflict_es6.ts, 34, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuperConflict_es6.ts, 40, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuperConflict_es6.ts, 37, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuperConflict_es6.ts, 43, 13)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) @@ -82,27 +97,28 @@ class B extends A { >super.x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 25, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 31, 13)) // element access (assign) super["x"] = f; >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 25, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 31, 13)) // destructuring assign with property access ({ f: super.x } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 46, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 52, 10)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 46, 27)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 52, 27)) // destructuring assign with element access ({ f: super["x"] } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 49, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 55, 10)) >super : Symbol(A, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuperConflict_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 49, 30)) +>f : Symbol(f, Decl(asyncMethodWithSuperConflict_es6.ts, 55, 30)) } } + diff --git a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.types b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.types index ac82440a3d8..9efebc2f192 100644 --- a/tests/baselines/reference/asyncMethodWithSuperConflict_es6.types +++ b/tests/baselines/reference/asyncMethodWithSuperConflict_es6.types @@ -5,6 +5,9 @@ class A { x() { >x : () => void } + y() { +>y : () => void + } } class B extends A { @@ -17,6 +20,10 @@ class B extends A { const _super = null; >_super : any +>null : null + + const _superIndex = null; +>_superIndex : any >null : null // call with property access @@ -26,6 +33,13 @@ class B extends A { >super : A >x : () => void + // call additional property. + super.y(); +>super.y() : void +>super.y : () => void +>super : A +>y : () => void + // call with element access super["x"](); >super["x"]() : void @@ -54,6 +68,10 @@ class B extends A { const _super = null; >_super : any +>null : null + + const _superIndex = null; +>_superIndex : any >null : null const f = () => {}; @@ -129,3 +147,4 @@ class B extends A { >f : () => void } } + diff --git a/tests/baselines/reference/asyncMethodWithSuper_es2017.js b/tests/baselines/reference/asyncMethodWithSuper_es2017.js index b6925793163..4c5a7aa9866 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es2017.js +++ b/tests/baselines/reference/asyncMethodWithSuper_es2017.js @@ -2,6 +2,8 @@ class A { x() { } + y() { + } } class B extends A { @@ -9,6 +11,8 @@ class B extends A { async simple() { // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); @@ -48,18 +52,23 @@ class B extends A { // destructuring assign with element access ({ f: super["x"] } = { f }); } -} +} + //// [asyncMethodWithSuper_es2017.js] class A { x() { } + y() { + } } class B extends A { // async method with only call/get on 'super' does not require a binding async simple() { // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); // property access (read) diff --git a/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols b/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols index 39ed91d7acb..bee97d8a006 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols +++ b/tests/baselines/reference/asyncMethodWithSuper_es2017.symbols @@ -5,15 +5,18 @@ class A { x() { >x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) } + y() { +>y : Symbol(A.y, Decl(asyncMethodWithSuper_es2017.ts, 2, 5)) + } } class B extends A { ->B : Symbol(B, Decl(asyncMethodWithSuper_es2017.ts, 3, 1)) +>B : Symbol(B, Decl(asyncMethodWithSuper_es2017.ts, 5, 1)) >A : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) // async method with only call/get on 'super' does not require a binding async simple() { ->simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es2017.ts, 5, 19)) +>simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es2017.ts, 7, 19)) // call with property access super.x(); @@ -21,6 +24,12 @@ class B extends A { >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) + // call additional property. + super.y(); +>super.y : Symbol(A.y, Decl(asyncMethodWithSuper_es2017.ts, 2, 5)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) +>y : Symbol(A.y, Decl(asyncMethodWithSuper_es2017.ts, 2, 5)) + // call with element access super["x"](); >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) @@ -28,24 +37,24 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuper_es2017.ts, 15, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuper_es2017.ts, 19, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuper_es2017.ts, 18, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuper_es2017.ts, 22, 13)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) } // async method with assignment/destructuring on 'super' requires a binding async advanced() { ->advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es2017.ts, 19, 5)) +>advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es2017.ts, 23, 5)) const f = () => {}; ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 27, 13)) // call with property access super.x(); @@ -60,14 +69,14 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuper_es2017.ts, 32, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuper_es2017.ts, 36, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuper_es2017.ts, 35, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuper_es2017.ts, 39, 13)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) @@ -76,27 +85,28 @@ class B extends A { >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 27, 13)) // element access (assign) super["x"] = f; >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 27, 13)) // destructuring assign with property access ({ f: super.x } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 44, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 48, 10)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 44, 27)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 48, 27)) // destructuring assign with element access ({ f: super["x"] } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 47, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 51, 10)) >super : Symbol(A, Decl(asyncMethodWithSuper_es2017.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es2017.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 47, 30)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es2017.ts, 51, 30)) } } + diff --git a/tests/baselines/reference/asyncMethodWithSuper_es2017.types b/tests/baselines/reference/asyncMethodWithSuper_es2017.types index b2678e8b837..b76b13798b8 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es2017.types +++ b/tests/baselines/reference/asyncMethodWithSuper_es2017.types @@ -5,6 +5,9 @@ class A { x() { >x : () => void } + y() { +>y : () => void + } } class B extends A { @@ -22,6 +25,13 @@ class B extends A { >super : A >x : () => void + // call additional property. + super.y(); +>super.y() : void +>super.y : () => void +>super : A +>y : () => void + // call with element access super["x"](); >super["x"]() : void @@ -121,3 +131,4 @@ class B extends A { >f : () => void } } + diff --git a/tests/baselines/reference/asyncMethodWithSuper_es5.js b/tests/baselines/reference/asyncMethodWithSuper_es5.js index a2931b9f8e1..441ad8875c4 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es5.js +++ b/tests/baselines/reference/asyncMethodWithSuper_es5.js @@ -2,6 +2,8 @@ class A { x() { } + y() { + } } class B extends A { @@ -9,6 +11,8 @@ class B extends A { async simple() { // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); @@ -48,7 +52,8 @@ class B extends A { // destructuring assign with element access ({ f: super["x"] } = { f }); } -} +} + //// [asyncMethodWithSuper_es5.js] var A = /** @class */ (function () { @@ -56,6 +61,8 @@ var A = /** @class */ (function () { } A.prototype.x = function () { }; + A.prototype.y = function () { + }; return A; }()); var B = /** @class */ (function (_super) { @@ -70,6 +77,8 @@ var B = /** @class */ (function (_super) { return __generator(this, function (_a) { // call with property access _super.prototype.x.call(this); + // call additional property. + _super.prototype.y.call(this); // call with element access _super.prototype["x"].call(this); a = _super.prototype.x; diff --git a/tests/baselines/reference/asyncMethodWithSuper_es5.symbols b/tests/baselines/reference/asyncMethodWithSuper_es5.symbols index e05f00a8e97..c013058c85a 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es5.symbols +++ b/tests/baselines/reference/asyncMethodWithSuper_es5.symbols @@ -5,15 +5,18 @@ class A { x() { >x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) } + y() { +>y : Symbol(A.y, Decl(asyncMethodWithSuper_es5.ts, 2, 5)) + } } class B extends A { ->B : Symbol(B, Decl(asyncMethodWithSuper_es5.ts, 3, 1)) +>B : Symbol(B, Decl(asyncMethodWithSuper_es5.ts, 5, 1)) >A : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) // async method with only call/get on 'super' does not require a binding async simple() { ->simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es5.ts, 5, 19)) +>simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es5.ts, 7, 19)) // call with property access super.x(); @@ -21,6 +24,12 @@ class B extends A { >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) + // call additional property. + super.y(); +>super.y : Symbol(A.y, Decl(asyncMethodWithSuper_es5.ts, 2, 5)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) +>y : Symbol(A.y, Decl(asyncMethodWithSuper_es5.ts, 2, 5)) + // call with element access super["x"](); >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) @@ -28,24 +37,24 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuper_es5.ts, 15, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuper_es5.ts, 19, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuper_es5.ts, 18, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuper_es5.ts, 22, 13)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) } // async method with assignment/destructuring on 'super' requires a binding async advanced() { ->advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es5.ts, 19, 5)) +>advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es5.ts, 23, 5)) const f = () => {}; ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 27, 13)) // call with property access super.x(); @@ -60,14 +69,14 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuper_es5.ts, 32, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuper_es5.ts, 36, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuper_es5.ts, 35, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuper_es5.ts, 39, 13)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) @@ -76,27 +85,28 @@ class B extends A { >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 27, 13)) // element access (assign) super["x"] = f; >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 27, 13)) // destructuring assign with property access ({ f: super.x } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 44, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 48, 10)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 44, 27)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 48, 27)) // destructuring assign with element access ({ f: super["x"] } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 47, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 51, 10)) >super : Symbol(A, Decl(asyncMethodWithSuper_es5.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es5.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 47, 30)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es5.ts, 51, 30)) } } + diff --git a/tests/baselines/reference/asyncMethodWithSuper_es5.types b/tests/baselines/reference/asyncMethodWithSuper_es5.types index 4622d83a679..58f545dc93b 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es5.types +++ b/tests/baselines/reference/asyncMethodWithSuper_es5.types @@ -5,6 +5,9 @@ class A { x() { >x : () => void } + y() { +>y : () => void + } } class B extends A { @@ -22,6 +25,13 @@ class B extends A { >super : A >x : () => void + // call additional property. + super.y(); +>super.y() : void +>super.y : () => void +>super : A +>y : () => void + // call with element access super["x"](); >super["x"]() : void @@ -121,3 +131,4 @@ class B extends A { >f : () => void } } + diff --git a/tests/baselines/reference/asyncMethodWithSuper_es6.js b/tests/baselines/reference/asyncMethodWithSuper_es6.js index eacb0a882b2..5ff89d26e94 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es6.js +++ b/tests/baselines/reference/asyncMethodWithSuper_es6.js @@ -2,6 +2,8 @@ class A { x() { } + y() { + } } class B extends A { @@ -9,6 +11,8 @@ class B extends A { async simple() { // call with property access super.x(); + // call additional property. + super.y(); // call with element access super["x"](); @@ -48,52 +52,64 @@ class B extends A { // destructuring assign with element access ({ f: super["x"] } = { f }); } -} +} + //// [asyncMethodWithSuper_es6.js] class A { x() { } + y() { + } } class B extends A { // async method with only call/get on 'super' does not require a binding simple() { - const _super = name => super[name]; + const _superIndex = name => super[name]; + const _super = Object.create(null, { + x: { get: () => super.x }, + y: { get: () => super.y } + }); return __awaiter(this, void 0, void 0, function* () { // call with property access - _super("x").call(this); + _super.x.call(this); + // call additional property. + _super.y.call(this); // call with element access - _super("x").call(this); + _superIndex("x").call(this); // property access (read) - const a = _super("x"); + const a = _super.x; // element access (read) - const b = _super("x"); + const b = _superIndex("x"); }); } // async method with assignment/destructuring on 'super' requires a binding advanced() { - 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); + const _super = Object.create(null, { + x: { get: () => super.x, set: v => super.x = v } + }); return __awaiter(this, void 0, void 0, function* () { const f = () => { }; // call with property access - _super("x").value.call(this); + _super.x.call(this); // call with element access - _super("x").value.call(this); + _superIndex("x").value.call(this); // property access (read) - const a = _super("x").value; + const a = _super.x; // element access (read) - const b = _super("x").value; + const b = _superIndex("x").value; // property access (assign) - _super("x").value = f; + _super.x = f; // element access (assign) - _super("x").value = f; + _superIndex("x").value = f; // destructuring assign with property access - ({ f: _super("x").value } = { f }); + ({ f: _super.x } = { f }); // destructuring assign with element access - ({ f: _super("x").value } = { f }); + ({ f: _superIndex("x").value } = { f }); }); } } diff --git a/tests/baselines/reference/asyncMethodWithSuper_es6.symbols b/tests/baselines/reference/asyncMethodWithSuper_es6.symbols index 268ad90f203..d33bcf3449a 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es6.symbols +++ b/tests/baselines/reference/asyncMethodWithSuper_es6.symbols @@ -5,15 +5,18 @@ class A { x() { >x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) } + y() { +>y : Symbol(A.y, Decl(asyncMethodWithSuper_es6.ts, 2, 5)) + } } class B extends A { ->B : Symbol(B, Decl(asyncMethodWithSuper_es6.ts, 3, 1)) +>B : Symbol(B, Decl(asyncMethodWithSuper_es6.ts, 5, 1)) >A : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) // async method with only call/get on 'super' does not require a binding async simple() { ->simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es6.ts, 5, 19)) +>simple : Symbol(B.simple, Decl(asyncMethodWithSuper_es6.ts, 7, 19)) // call with property access super.x(); @@ -21,6 +24,12 @@ class B extends A { >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) + // call additional property. + super.y(); +>super.y : Symbol(A.y, Decl(asyncMethodWithSuper_es6.ts, 2, 5)) +>super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) +>y : Symbol(A.y, Decl(asyncMethodWithSuper_es6.ts, 2, 5)) + // call with element access super["x"](); >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) @@ -28,24 +37,24 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuper_es6.ts, 15, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuper_es6.ts, 19, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuper_es6.ts, 18, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuper_es6.ts, 22, 13)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) } // async method with assignment/destructuring on 'super' requires a binding async advanced() { ->advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es6.ts, 19, 5)) +>advanced : Symbol(B.advanced, Decl(asyncMethodWithSuper_es6.ts, 23, 5)) const f = () => {}; ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 27, 13)) // call with property access super.x(); @@ -60,14 +69,14 @@ class B extends A { // property access (read) const a = super.x; ->a : Symbol(a, Decl(asyncMethodWithSuper_es6.ts, 32, 13)) +>a : Symbol(a, Decl(asyncMethodWithSuper_es6.ts, 36, 13)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) // element access (read) const b = super["x"]; ->b : Symbol(b, Decl(asyncMethodWithSuper_es6.ts, 35, 13)) +>b : Symbol(b, Decl(asyncMethodWithSuper_es6.ts, 39, 13)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) @@ -76,27 +85,28 @@ class B extends A { >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 27, 13)) // element access (assign) super["x"] = f; >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 23, 13)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 27, 13)) // destructuring assign with property access ({ f: super.x } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 44, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 48, 10)) >super.x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >x : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 44, 27)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 48, 27)) // destructuring assign with element access ({ f: super["x"] } = { f }); ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 47, 10)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 51, 10)) >super : Symbol(A, Decl(asyncMethodWithSuper_es6.ts, 0, 0)) >"x" : Symbol(A.x, Decl(asyncMethodWithSuper_es6.ts, 0, 9)) ->f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 47, 30)) +>f : Symbol(f, Decl(asyncMethodWithSuper_es6.ts, 51, 30)) } } + diff --git a/tests/baselines/reference/asyncMethodWithSuper_es6.types b/tests/baselines/reference/asyncMethodWithSuper_es6.types index 030c9fe4e6a..1333beb8f04 100644 --- a/tests/baselines/reference/asyncMethodWithSuper_es6.types +++ b/tests/baselines/reference/asyncMethodWithSuper_es6.types @@ -5,6 +5,9 @@ class A { x() { >x : () => void } + y() { +>y : () => void + } } class B extends A { @@ -22,6 +25,13 @@ class B extends A { >super : A >x : () => void + // call additional property. + super.y(); +>super.y() : void +>super.y : () => void +>super : A +>y : () => void + // call with element access super["x"](); >super["x"]() : void @@ -121,3 +131,4 @@ class B extends A { >f : () => void } } + diff --git a/tests/baselines/reference/augmentExportEquals3.symbols b/tests/baselines/reference/augmentExportEquals3.symbols index e4e7a8e1a5f..2644d6d5b21 100644 --- a/tests/baselines/reference/augmentExportEquals3.symbols +++ b/tests/baselines/reference/augmentExportEquals3.symbols @@ -1,9 +1,9 @@ === tests/cases/compiler/file1.ts === function foo() {} ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 17), Decl(file2.ts, 1, 8)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 17), Decl(file2.ts, 1, 8)) namespace foo { ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 17), Decl(file2.ts, 1, 8)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 17), Decl(file2.ts, 1, 8)) export var v = 1; >v : Symbol(v, Decl(file1.ts, 2, 14)) diff --git a/tests/baselines/reference/augmentExportEquals3_1.symbols b/tests/baselines/reference/augmentExportEquals3_1.symbols index 2431b293dea..181ceb343b8 100644 --- a/tests/baselines/reference/augmentExportEquals3_1.symbols +++ b/tests/baselines/reference/augmentExportEquals3_1.symbols @@ -3,10 +3,10 @@ declare module "file1" { >"file1" : Symbol("file1", Decl(file1.d.ts, 0, 0)) function foo(): void; ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 25), Decl(file2.ts, 2, 8)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 25), Decl(file2.ts, 2, 8)) namespace foo { ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 25), Decl(file2.ts, 2, 8)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 25), Decl(file2.ts, 2, 8)) export var v: number; >v : Symbol(v, Decl(file1.d.ts, 3, 18)) diff --git a/tests/baselines/reference/augmentExportEquals4.symbols b/tests/baselines/reference/augmentExportEquals4.symbols index f1f63762545..75da60335c3 100644 --- a/tests/baselines/reference/augmentExportEquals4.symbols +++ b/tests/baselines/reference/augmentExportEquals4.symbols @@ -1,9 +1,9 @@ === tests/cases/compiler/file1.ts === class foo {} ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 8)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 8)) namespace foo { ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 8)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 8)) export var v = 1; >v : Symbol(v, Decl(file1.ts, 2, 14)) diff --git a/tests/baselines/reference/augmentExportEquals4_1.symbols b/tests/baselines/reference/augmentExportEquals4_1.symbols index d2a3c001825..97d115e453e 100644 --- a/tests/baselines/reference/augmentExportEquals4_1.symbols +++ b/tests/baselines/reference/augmentExportEquals4_1.symbols @@ -3,10 +3,10 @@ declare module "file1" { >"file1" : Symbol("file1", Decl(file1.d.ts, 0, 0)) class foo {} ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 2, 8)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 2, 8)) namespace foo { ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 2, 8)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 2, 8)) export var v: number; >v : Symbol(v, Decl(file1.d.ts, 3, 18)) diff --git a/tests/baselines/reference/augmentExportEquals5.symbols b/tests/baselines/reference/augmentExportEquals5.symbols index 244073b6515..ef62f66817e 100644 --- a/tests/baselines/reference/augmentExportEquals5.symbols +++ b/tests/baselines/reference/augmentExportEquals5.symbols @@ -16,12 +16,12 @@ declare module "express" { >"express" : Symbol("express", Decl(express.d.ts, 4, 1)) function e(): e.Express; ->e : Symbol(e, Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28), Decl(augmentation.ts, 1, 29)) +>e : Symbol("tests/cases/compiler/express.d.ts", Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28), Decl(augmentation.ts, 1, 29)) >e : Symbol(e, Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28)) >Express : Symbol(Express, Decl(express.d.ts, 52, 9)) namespace e { ->e : Symbol(e, Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28), Decl(augmentation.ts, 1, 29)) +>e : Symbol("tests/cases/compiler/express.d.ts", Decl(express.d.ts, 6, 26), Decl(express.d.ts, 7, 28), Decl(augmentation.ts, 1, 29)) interface IRoute { >IRoute : Symbol(IRoute, Decl(express.d.ts, 8, 17)) diff --git a/tests/baselines/reference/augmentExportEquals6.symbols b/tests/baselines/reference/augmentExportEquals6.symbols index 2125b650464..72ef677c592 100644 --- a/tests/baselines/reference/augmentExportEquals6.symbols +++ b/tests/baselines/reference/augmentExportEquals6.symbols @@ -1,9 +1,9 @@ === tests/cases/compiler/file1.ts === class foo {} ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 10)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 10)) namespace foo { ->foo : Symbol(foo, Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 10)) +>foo : Symbol("tests/cases/compiler/file1.ts", Decl(file1.ts, 0, 0), Decl(file1.ts, 0, 12), Decl(file2.ts, 1, 10)) export class A {} >A : Symbol(A, Decl(file1.ts, 1, 15), Decl(file2.ts, 4, 26)) diff --git a/tests/baselines/reference/augmentExportEquals6_1.symbols b/tests/baselines/reference/augmentExportEquals6_1.symbols index b75f8131c01..e37b094549a 100644 --- a/tests/baselines/reference/augmentExportEquals6_1.symbols +++ b/tests/baselines/reference/augmentExportEquals6_1.symbols @@ -3,10 +3,10 @@ declare module "file1" { >"file1" : Symbol("file1", Decl(file1.d.ts, 0, 0)) class foo {} ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 1, 28)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 1, 28)) namespace foo { ->foo : Symbol(foo, Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 1, 28)) +>foo : Symbol("tests/cases/compiler/file1.d.ts", Decl(file1.d.ts, 0, 24), Decl(file1.d.ts, 1, 16), Decl(file2.ts, 1, 28)) class A {} >A : Symbol(A, Decl(file1.d.ts, 2, 19), Decl(file2.ts, 4, 24)) diff --git a/tests/baselines/reference/autolift4.js b/tests/baselines/reference/autolift4.js index 19d6cd43932..53ce6dc9dc3 100644 --- a/tests/baselines/reference/autolift4.js +++ b/tests/baselines/reference/autolift4.js @@ -30,7 +30,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; } diff --git a/tests/baselines/reference/bangInModuleName.symbols b/tests/baselines/reference/bangInModuleName.symbols index ca3d4a161f5..fa1b84ba296 100644 --- a/tests/baselines/reference/bangInModuleName.symbols +++ b/tests/baselines/reference/bangInModuleName.symbols @@ -10,7 +10,7 @@ declare module "http" { } declare module 'intern/dojo/node!http' { ->'intern/dojo/node!http' : Symbol('intern/dojo/node!http', Decl(a.d.ts, 1, 1)) +>'intern/dojo/node!http' : Symbol("intern/dojo/node!http", Decl(a.d.ts, 1, 1)) import http = require('http'); >http : Symbol(http, Decl(a.d.ts, 3, 40)) diff --git a/tests/baselines/reference/baseCheck.js b/tests/baselines/reference/baseCheck.js index e48c235a087..114bbf655e4 100644 --- a/tests/baselines/reference/baseCheck.js +++ b/tests/baselines/reference/baseCheck.js @@ -36,7 +36,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; } diff --git a/tests/baselines/reference/baseClassImprovedMismatchErrors.js b/tests/baselines/reference/baseClassImprovedMismatchErrors.js index def62c018bd..2b864807570 100644 --- a/tests/baselines/reference/baseClassImprovedMismatchErrors.js +++ b/tests/baselines/reference/baseClassImprovedMismatchErrors.js @@ -25,7 +25,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; } diff --git a/tests/baselines/reference/baseConstraintOfDecorator.errors.txt b/tests/baselines/reference/baseConstraintOfDecorator.errors.txt index efc0c59f9ee..3af8756fac2 100644 --- a/tests/baselines/reference/baseConstraintOfDecorator.errors.txt +++ b/tests/baselines/reference/baseConstraintOfDecorator.errors.txt @@ -1,13 +1,36 @@ tests/cases/compiler/baseConstraintOfDecorator.ts(2,5): error TS2322: Type 'typeof decoratorFunc' is not assignable to type 'TFunction'. tests/cases/compiler/baseConstraintOfDecorator.ts(2,40): error TS2507: Type 'TFunction' is not a constructor function type. +tests/cases/compiler/baseConstraintOfDecorator.ts(12,5): error TS2322: Type 'typeof decoratorFunc' is not assignable to type 'TFunction'. +tests/cases/compiler/baseConstraintOfDecorator.ts(12,40): error TS2507: Type 'TFunction' is not a constructor function type. -==== tests/cases/compiler/baseConstraintOfDecorator.ts (2 errors) ==== +==== tests/cases/compiler/baseConstraintOfDecorator.ts (4 errors) ==== export function classExtender(superClass: TFunction, _instanceModifier: (instance: any, args: any[]) => void): TFunction { return class decoratorFunc extends superClass { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~ !!! error TS2507: Type 'TFunction' is not a constructor function type. +!!! related TS2735 tests/cases/compiler/baseConstraintOfDecorator.ts:1:31: Did you mean for 'TFunction' to be constrained to type 'new (...args: any[]) => unknown'? + constructor(...args: any[]) { + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + super(...args); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + _instanceModifier(this, args); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + } + ~~~~~~~~~ + }; + ~~~~~~ +!!! error TS2322: Type 'typeof decoratorFunc' is not assignable to type 'TFunction'. + } + + class MyClass { private x; } + export function classExtender2 MyClass>(superClass: TFunction, _instanceModifier: (instance: any, args: any[]) => void): TFunction { + return class decoratorFunc extends superClass { + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + ~~~~~~~~~~ +!!! error TS2507: Type 'TFunction' is not a constructor function type. +!!! related TS2735 tests/cases/compiler/baseConstraintOfDecorator.ts:11:32: Did you mean for 'TFunction' to be constrained to type 'new (...args: any[]) => MyClass'? constructor(...args: any[]) { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ super(...args); diff --git a/tests/baselines/reference/baseConstraintOfDecorator.js b/tests/baselines/reference/baseConstraintOfDecorator.js index 198dcb3d7b9..0c1f77e31e6 100644 --- a/tests/baselines/reference/baseConstraintOfDecorator.js +++ b/tests/baselines/reference/baseConstraintOfDecorator.js @@ -7,6 +7,16 @@ export function classExtender(superClass: TFunction, _instanceModifie } }; } + +class MyClass { private x; } +export function classExtender2 MyClass>(superClass: TFunction, _instanceModifier: (instance: any, args: any[]) => void): TFunction { + return class decoratorFunc extends superClass { + constructor(...args: any[]) { + super(...args); + _instanceModifier(this, args); + } + }; +} //// [baseConstraintOfDecorator.js] @@ -17,7 +27,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; } @@ -41,3 +51,24 @@ function classExtender(superClass, _instanceModifier) { }(superClass)); } exports.classExtender = classExtender; +var MyClass = /** @class */ (function () { + function MyClass() { + } + return MyClass; +}()); +function classExtender2(superClass, _instanceModifier) { + return /** @class */ (function (_super) { + __extends(decoratorFunc, _super); + function decoratorFunc() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var _this = _super.apply(this, args) || this; + _instanceModifier(_this, args); + return _this; + } + return decoratorFunc; + }(superClass)); +} +exports.classExtender2 = classExtender2; diff --git a/tests/baselines/reference/baseConstraintOfDecorator.symbols b/tests/baselines/reference/baseConstraintOfDecorator.symbols index 71d7773a7cf..9048d7ed568 100644 --- a/tests/baselines/reference/baseConstraintOfDecorator.symbols +++ b/tests/baselines/reference/baseConstraintOfDecorator.symbols @@ -27,3 +27,37 @@ export function classExtender(superClass: TFunction, _instanceModifie }; } +class MyClass { private x; } +>MyClass : Symbol(MyClass, Decl(baseConstraintOfDecorator.ts, 7, 1)) +>x : Symbol(MyClass.x, Decl(baseConstraintOfDecorator.ts, 9, 15)) + +export function classExtender2 MyClass>(superClass: TFunction, _instanceModifier: (instance: any, args: any[]) => void): TFunction { +>classExtender2 : Symbol(classExtender2, Decl(baseConstraintOfDecorator.ts, 9, 28)) +>TFunction : Symbol(TFunction, Decl(baseConstraintOfDecorator.ts, 10, 31)) +>args : Symbol(args, Decl(baseConstraintOfDecorator.ts, 10, 54)) +>MyClass : Symbol(MyClass, Decl(baseConstraintOfDecorator.ts, 7, 1)) +>superClass : Symbol(superClass, Decl(baseConstraintOfDecorator.ts, 10, 85)) +>TFunction : Symbol(TFunction, Decl(baseConstraintOfDecorator.ts, 10, 31)) +>_instanceModifier : Symbol(_instanceModifier, Decl(baseConstraintOfDecorator.ts, 10, 107)) +>instance : Symbol(instance, Decl(baseConstraintOfDecorator.ts, 10, 128)) +>args : Symbol(args, Decl(baseConstraintOfDecorator.ts, 10, 142)) +>TFunction : Symbol(TFunction, Decl(baseConstraintOfDecorator.ts, 10, 31)) + + return class decoratorFunc extends superClass { +>decoratorFunc : Symbol(decoratorFunc, Decl(baseConstraintOfDecorator.ts, 11, 10)) +>superClass : Symbol(superClass, Decl(baseConstraintOfDecorator.ts, 10, 85)) + + constructor(...args: any[]) { +>args : Symbol(args, Decl(baseConstraintOfDecorator.ts, 12, 20)) + + super(...args); +>args : Symbol(args, Decl(baseConstraintOfDecorator.ts, 12, 20)) + + _instanceModifier(this, args); +>_instanceModifier : Symbol(_instanceModifier, Decl(baseConstraintOfDecorator.ts, 10, 107)) +>this : Symbol(decoratorFunc, Decl(baseConstraintOfDecorator.ts, 11, 10)) +>args : Symbol(args, Decl(baseConstraintOfDecorator.ts, 12, 20)) + } + }; +} + diff --git a/tests/baselines/reference/baseConstraintOfDecorator.types b/tests/baselines/reference/baseConstraintOfDecorator.types index edf9641a4ba..a5a277c5d2a 100644 --- a/tests/baselines/reference/baseConstraintOfDecorator.types +++ b/tests/baselines/reference/baseConstraintOfDecorator.types @@ -29,3 +29,38 @@ export function classExtender(superClass: TFunction, _instanceModifie }; } +class MyClass { private x; } +>MyClass : MyClass +>x : any + +export function classExtender2 MyClass>(superClass: TFunction, _instanceModifier: (instance: any, args: any[]) => void): TFunction { +>classExtender2 : MyClass>(superClass: TFunction, _instanceModifier: (instance: any, args: any[]) => void) => TFunction +>args : string[] +>superClass : TFunction +>_instanceModifier : (instance: any, args: any[]) => void +>instance : any +>args : any[] + + return class decoratorFunc extends superClass { +>class decoratorFunc extends superClass { constructor(...args: any[]) { super(...args); _instanceModifier(this, args); } } : typeof decoratorFunc +>decoratorFunc : typeof decoratorFunc +>superClass : TFunction + + constructor(...args: any[]) { +>args : any[] + + super(...args); +>super(...args) : void +>super : any +>...args : any +>args : any[] + + _instanceModifier(this, args); +>_instanceModifier(this, args) : void +>_instanceModifier : (instance: any, args: any[]) => void +>this : this +>args : any[] + } + }; +} + diff --git a/tests/baselines/reference/baseExpressionTypeParameters.js b/tests/baselines/reference/baseExpressionTypeParameters.js index fd907be7e52..aa16fcebf55 100644 --- a/tests/baselines/reference/baseExpressionTypeParameters.js +++ b/tests/baselines/reference/baseExpressionTypeParameters.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; } diff --git a/tests/baselines/reference/baseIndexSignatureResolution.js b/tests/baselines/reference/baseIndexSignatureResolution.js index d5732b7f3d5..09aabe21ac4 100644 --- a/tests/baselines/reference/baseIndexSignatureResolution.js +++ b/tests/baselines/reference/baseIndexSignatureResolution.js @@ -31,7 +31,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; } diff --git a/tests/baselines/reference/baseTypeOrderChecking.js b/tests/baselines/reference/baseTypeOrderChecking.js index 9e6800d376a..31fa3391af5 100644 --- a/tests/baselines/reference/baseTypeOrderChecking.js +++ b/tests/baselines/reference/baseTypeOrderChecking.js @@ -43,7 +43,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; } diff --git a/tests/baselines/reference/baseTypeWrappingInstantiationChain.js b/tests/baselines/reference/baseTypeWrappingInstantiationChain.js index 3f8e475504d..de50a58205d 100644 --- a/tests/baselines/reference/baseTypeWrappingInstantiationChain.js +++ b/tests/baselines/reference/baseTypeWrappingInstantiationChain.js @@ -34,7 +34,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; } diff --git a/tests/baselines/reference/bases.errors.txt b/tests/baselines/reference/bases.errors.txt index 3069f977fe1..fb63428b876 100644 --- a/tests/baselines/reference/bases.errors.txt +++ b/tests/baselines/reference/bases.errors.txt @@ -2,7 +2,7 @@ tests/cases/compiler/bases.ts(7,14): error TS2339: Property 'y' does not exist o tests/cases/compiler/bases.ts(7,15): error TS1005: ';' expected. tests/cases/compiler/bases.ts(7,17): error TS2693: 'any' only refers to a type, but is being used as a value here. tests/cases/compiler/bases.ts(11,7): error TS2420: Class 'C' incorrectly implements interface 'I'. - Property 'x' is missing in type 'C'. + Property 'x' is missing in type 'C' but required in type 'I'. tests/cases/compiler/bases.ts(12,5): error TS2377: Constructors for derived classes must contain a 'super' call. tests/cases/compiler/bases.ts(13,9): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. tests/cases/compiler/bases.ts(13,14): error TS2339: Property 'x' does not exist on type 'C'. @@ -32,7 +32,8 @@ tests/cases/compiler/bases.ts(18,9): error TS2339: Property 'y' does not exist o class C extends B implements I { ~ !!! error TS2420: Class 'C' incorrectly implements interface 'I'. -!!! error TS2420: Property 'x' is missing in type 'C'. +!!! error TS2420: Property 'x' is missing in type 'C' but required in type 'I'. +!!! related TS2728 tests/cases/compiler/bases.ts:2:5: 'x' is declared here. constructor() { ~~~~~~~~~~~~~~~ this.x: any; diff --git a/tests/baselines/reference/bases.js b/tests/baselines/reference/bases.js index 9ff19e7ae61..25cf4073d5c 100644 --- a/tests/baselines/reference/bases.js +++ b/tests/baselines/reference/bases.js @@ -27,7 +27,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; } diff --git a/tests/baselines/reference/bestCommonTypeOfConditionalExpressions.js b/tests/baselines/reference/bestCommonTypeOfConditionalExpressions.js index 1eaa060ce1f..b755bf200a5 100644 --- a/tests/baselines/reference/bestCommonTypeOfConditionalExpressions.js +++ b/tests/baselines/reference/bestCommonTypeOfConditionalExpressions.js @@ -35,7 +35,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; } diff --git a/tests/baselines/reference/bestCommonTypeOfConditionalExpressions2.js b/tests/baselines/reference/bestCommonTypeOfConditionalExpressions2.js index 77543b29fe8..b7afc3eee41 100644 --- a/tests/baselines/reference/bestCommonTypeOfConditionalExpressions2.js +++ b/tests/baselines/reference/bestCommonTypeOfConditionalExpressions2.js @@ -33,7 +33,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; } diff --git a/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt b/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt index 2c57099c3e8..e3c5dcc7986 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt +++ b/tests/baselines/reference/bestCommonTypeOfTuple.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(22,13): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(23,13): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(24,13): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(25,13): error TS2733: Index '3' is out-of-bounds in tuple of length 3. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(22,13): error TS2339: Property '2' does not exist on type '[(x: number) => string, (x: number) => number]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(23,13): error TS2339: Property '2' does not exist on type '[E1, E2]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(24,13): error TS2339: Property '2' does not exist on type '[number, any]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts(25,13): error TS2339: Property '3' does not exist on type '[E1, E2, number]'. ==== tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple.ts (4 errors) ==== @@ -28,13 +28,13 @@ tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfT t4 = [E1.one, E2.two, 20]; var e1 = t1[2]; // {} ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[(x: number) => string, (x: number) => number]'. var e2 = t2[2]; // {} ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[E1, E2]'. var e3 = t3[2]; // any ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[number, any]'. var e4 = t4[3]; // number ~ -!!! error TS2733: Index '3' is out-of-bounds in tuple of length 3. \ No newline at end of file +!!! error TS2339: Property '3' does not exist on type '[E1, E2, number]'. \ No newline at end of file diff --git a/tests/baselines/reference/bestCommonTypeOfTuple.types b/tests/baselines/reference/bestCommonTypeOfTuple.types index 612403084a5..4cc64a25505 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple.types +++ b/tests/baselines/reference/bestCommonTypeOfTuple.types @@ -76,26 +76,26 @@ t4 = [E1.one, E2.two, 20]; >20 : 20 var e1 = t1[2]; // {} ->e1 : ((x: number) => string) | ((x: number) => number) ->t1[2] : ((x: number) => string) | ((x: number) => number) +>e1 : undefined +>t1[2] : undefined >t1 : [(x: number) => string, (x: number) => number] >2 : 2 var e2 = t2[2]; // {} ->e2 : E1 | E2 ->t2[2] : E1 | E2 +>e2 : undefined +>t2[2] : undefined >t2 : [E1, E2] >2 : 2 var e3 = t3[2]; // any ->e3 : any ->t3[2] : any +>e3 : undefined +>t3[2] : undefined >t3 : [number, any] >2 : 2 var e4 = t4[3]; // number ->e4 : number ->t4[3] : number +>e4 : undefined +>t4[3] : undefined >t4 : [E1, E2, number] >3 : 3 diff --git a/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt b/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt index 80f40c74a07..d2fd301e131 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt +++ b/tests/baselines/reference/bestCommonTypeOfTuple2.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(17,14): error TS2733: Index '4' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(18,14): error TS2733: Index '4' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(19,14): error TS2733: Index '4' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(20,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. -tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(21,14): error TS2733: Index '2' is out-of-bounds in tuple of length 2. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(17,14): error TS2339: Property '4' does not exist on type '[C, base]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(18,14): error TS2339: Property '4' does not exist on type '[C, D]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(19,14): error TS2339: Property '4' does not exist on type '[C1, D1]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(20,14): error TS2339: Property '2' does not exist on type '[base1, C1]'. +tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts(21,14): error TS2339: Property '2' does not exist on type '[C1, F]'. ==== tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfTuple2.ts (5 errors) ==== @@ -24,17 +24,17 @@ tests/cases/conformance/types/typeRelationships/bestCommonType/bestCommonTypeOfT var e11 = t1[4]; // base ~ -!!! error TS2733: Index '4' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '4' does not exist on type '[C, base]'. var e21 = t2[4]; // {} ~ -!!! error TS2733: Index '4' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '4' does not exist on type '[C, D]'. var e31 = t3[4]; // C1 ~ -!!! error TS2733: Index '4' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '4' does not exist on type '[C1, D1]'. var e41 = t4[2]; // base1 ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[base1, C1]'. var e51 = t5[2]; // {} ~ -!!! error TS2733: Index '2' is out-of-bounds in tuple of length 2. +!!! error TS2339: Property '2' does not exist on type '[C1, F]'. \ No newline at end of file diff --git a/tests/baselines/reference/bestCommonTypeOfTuple2.js b/tests/baselines/reference/bestCommonTypeOfTuple2.js index 0dbea701fa3..a3672a76423 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple2.js +++ b/tests/baselines/reference/bestCommonTypeOfTuple2.js @@ -29,7 +29,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; } diff --git a/tests/baselines/reference/bestCommonTypeOfTuple2.types b/tests/baselines/reference/bestCommonTypeOfTuple2.types index 33691bc65a9..6b3e6a3789c 100644 --- a/tests/baselines/reference/bestCommonTypeOfTuple2.types +++ b/tests/baselines/reference/bestCommonTypeOfTuple2.types @@ -49,32 +49,32 @@ var t5: [C1, F] >t5 : [C1, F] var e11 = t1[4]; // base ->e11 : base | C ->t1[4] : base | C +>e11 : undefined +>t1[4] : undefined >t1 : [C, base] >4 : 4 var e21 = t2[4]; // {} ->e21 : C | D ->t2[4] : C | D +>e21 : undefined +>t2[4] : undefined >t2 : [C, D] >4 : 4 var e31 = t3[4]; // C1 ->e31 : C1 | D1 ->t3[4] : C1 | D1 +>e31 : undefined +>t3[4] : undefined >t3 : [C1, D1] >4 : 4 var e41 = t4[2]; // base1 ->e41 : base1 | C1 ->t4[2] : base1 | C1 +>e41 : undefined +>t4[2] : undefined >t4 : [base1, C1] >2 : 2 var e51 = t5[2]; // {} ->e51 : F | C1 ->t5[2] : F | C1 +>e51 : undefined +>t5[2] : undefined >t5 : [C1, F] >2 : 2 diff --git a/tests/baselines/reference/betterErrorForAccidentalCall.errors.txt b/tests/baselines/reference/betterErrorForAccidentalCall.errors.txt new file mode 100644 index 00000000000..f5358b45a4f --- /dev/null +++ b/tests/baselines/reference/betterErrorForAccidentalCall.errors.txt @@ -0,0 +1,39 @@ +tests/cases/compiler/betterErrorForAccidentalCall.ts(3,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/betterErrorForAccidentalCall.ts(5,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/betterErrorForAccidentalCall.ts(7,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/betterErrorForAccidentalCall.ts(10,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +tests/cases/compiler/betterErrorForAccidentalCall.ts(13,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. + + +==== tests/cases/compiler/betterErrorForAccidentalCall.ts (5 errors) ==== + declare function foo(): string; + + foo()(1 as number).toString(); + ~~~~~~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. + + foo() (1 as number).toString(); + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. + + foo() + ~~~~~ + (1 as number).toString(); + ~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +!!! related TS2734 tests/cases/compiler/betterErrorForAccidentalCall.ts:7:1: It is highly likely that you are missing a semicolon. + + foo() + ~~~~~ + (1 + 2).toString(); + ~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +!!! related TS2734 tests/cases/compiler/betterErrorForAccidentalCall.ts:10:1: It is highly likely that you are missing a semicolon. + + foo() + ~~~~~ + (1).toString(); + ~~~~~~~~~~~~~~~ +!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. +!!! related TS2734 tests/cases/compiler/betterErrorForAccidentalCall.ts:13:1: It is highly likely that you are missing a semicolon. + \ No newline at end of file diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js b/tests/baselines/reference/betterErrorForAccidentalCall.js similarity index 53% rename from tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js rename to tests/baselines/reference/betterErrorForAccidentalCall.js index 877ed539e71..deb2b22d2f6 100644 --- a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.js +++ b/tests/baselines/reference/betterErrorForAccidentalCall.js @@ -1,4 +1,4 @@ -//// [betterErrorForAccidentallyCallingTypeAssertionExpressions.ts] +//// [betterErrorForAccidentalCall.ts] declare function foo(): string; foo()(1 as number).toString(); @@ -8,16 +8,16 @@ foo() (1 as number).toString(); foo() (1 as number).toString(); -foo() - (1 as number).toString(); +foo() + (1 + 2).toString(); -foo() +foo() (1).toString(); -//// [betterErrorForAccidentallyCallingTypeAssertionExpressions.js] -foo()(1).toString(); +//// [betterErrorForAccidentalCall.js] foo()(1).toString(); foo()(1).toString(); foo()(1).toString(); +foo()(1 + 2).toString(); foo()(1).toString(); diff --git a/tests/baselines/reference/betterErrorForAccidentalCall.symbols b/tests/baselines/reference/betterErrorForAccidentalCall.symbols new file mode 100644 index 00000000000..9471b0bb060 --- /dev/null +++ b/tests/baselines/reference/betterErrorForAccidentalCall.symbols @@ -0,0 +1,25 @@ +=== tests/cases/compiler/betterErrorForAccidentalCall.ts === +declare function foo(): string; +>foo : Symbol(foo, Decl(betterErrorForAccidentalCall.ts, 0, 0)) + +foo()(1 as number).toString(); +>foo : Symbol(foo, Decl(betterErrorForAccidentalCall.ts, 0, 0)) + +foo() (1 as number).toString(); +>foo : Symbol(foo, Decl(betterErrorForAccidentalCall.ts, 0, 0)) + +foo() +>foo : Symbol(foo, Decl(betterErrorForAccidentalCall.ts, 0, 0)) + +(1 as number).toString(); + +foo() +>foo : Symbol(foo, Decl(betterErrorForAccidentalCall.ts, 0, 0)) + + (1 + 2).toString(); + +foo() +>foo : Symbol(foo, Decl(betterErrorForAccidentalCall.ts, 0, 0)) + + (1).toString(); + diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types b/tests/baselines/reference/betterErrorForAccidentalCall.types similarity index 65% rename from tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types rename to tests/baselines/reference/betterErrorForAccidentalCall.types index 54564d7462c..1a3dfbd47f3 100644 --- a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.types +++ b/tests/baselines/reference/betterErrorForAccidentalCall.types @@ -1,4 +1,4 @@ -=== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts === +=== tests/cases/compiler/betterErrorForAccidentalCall.ts === declare function foo(): string; >foo : () => string @@ -34,22 +34,23 @@ foo() >1 : 1 >toString : any -foo() ->foo() (1 as number).toString() : any ->foo() (1 as number).toString : any ->foo() (1 as number) : any +foo() +>foo() (1 + 2).toString() : any +>foo() (1 + 2).toString : any +>foo() (1 + 2) : any >foo() : string >foo : () => string - (1 as number).toString(); ->1 as number : number + (1 + 2).toString(); +>1 + 2 : number >1 : 1 +>2 : 2 >toString : any -foo() ->foo() (1).toString() : any ->foo() (1).toString : any ->foo() (1) : any +foo() +>foo() (1).toString() : any +>foo() (1).toString : any +>foo() (1) : any >foo() : string >foo : () => string diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt deleted file mode 100644 index 023e40a70da..00000000000 --- a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.errors.txt +++ /dev/null @@ -1,39 +0,0 @@ -tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(3,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. -tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(5,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. -tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(7,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. -tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(10,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. -tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts(13,1): error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. - - -==== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts (5 errors) ==== - declare function foo(): string; - - foo()(1 as number).toString(); - ~~~~~~~~~~~~~~~~~~ -!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. - - foo() (1 as number).toString(); - ~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. - - foo() - ~~~~~ - (1 as number).toString(); - ~~~~~~~~~~~~~ -!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. -!!! related TS2734 tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts:7:1: It is highly likely that you are missing a semicolon. - - foo() - ~~~~~~~~ - (1 as number).toString(); - ~~~~~~~~~~~~~~~~~ -!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. -!!! related TS2734 tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts:10:1: It is highly likely that you are missing a semicolon. - - foo() - ~~~~~~~~ - (1).toString(); - ~~~~~~~~~~~~~~~ -!!! error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'String' has no compatible call signatures. -!!! related TS2734 tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts:13:1: It is highly likely that you are missing a semicolon. - \ No newline at end of file diff --git a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols b/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols deleted file mode 100644 index 9dc2e676937..00000000000 --- a/tests/baselines/reference/betterErrorForAccidentallyCallingTypeAssertionExpressions.symbols +++ /dev/null @@ -1,25 +0,0 @@ -=== tests/cases/compiler/betterErrorForAccidentallyCallingTypeAssertionExpressions.ts === -declare function foo(): string; ->foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) - -foo()(1 as number).toString(); ->foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) - -foo() (1 as number).toString(); ->foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) - -foo() ->foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) - -(1 as number).toString(); - -foo() ->foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) - - (1 as number).toString(); - -foo() ->foo : Symbol(foo, Decl(betterErrorForAccidentallyCallingTypeAssertionExpressions.ts, 0, 0)) - - (1).toString(); - diff --git a/tests/baselines/reference/bigIntWithTargetES3.errors.txt b/tests/baselines/reference/bigIntWithTargetES3.errors.txt new file mode 100644 index 00000000000..6fa938535f1 --- /dev/null +++ b/tests/baselines/reference/bigIntWithTargetES3.errors.txt @@ -0,0 +1,21 @@ +tests/cases/compiler/bigIntWithTargetES3.ts(5,22): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigIntWithTargetES3.ts(5,29): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigIntWithTargetES3.ts(5,39): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigIntWithTargetES3.ts(5,48): error TS2737: BigInt literals are not available when targeting lower than ESNext. + + +==== tests/cases/compiler/bigIntWithTargetES3.ts (4 errors) ==== + const normalNumber = 123; // should not error + let bigintType: bigint; // should not error + let bigintLiteralType: 123n; // should not error when used as type + let bigintNegativeLiteralType: -123n; // should not error when used as type + const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error + ~~~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + ~~~~~~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + ~~~~~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + ~~~~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + \ No newline at end of file diff --git a/tests/baselines/reference/bigIntWithTargetES3.js b/tests/baselines/reference/bigIntWithTargetES3.js new file mode 100644 index 00000000000..ad6f25a7671 --- /dev/null +++ b/tests/baselines/reference/bigIntWithTargetES3.js @@ -0,0 +1,14 @@ +//// [bigIntWithTargetES3.ts] +const normalNumber = 123; // should not error +let bigintType: bigint; // should not error +let bigintLiteralType: 123n; // should not error when used as type +let bigintNegativeLiteralType: -123n; // should not error when used as type +const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error + + +//// [bigIntWithTargetES3.js] +var normalNumber = 123; // should not error +var bigintType; // should not error +var bigintLiteralType; // should not error when used as type +var bigintNegativeLiteralType; // should not error when used as type +var bigintNumber = 123n * 15n + 292n * 0x7fn; // each literal should error diff --git a/tests/baselines/reference/bigIntWithTargetES3.symbols b/tests/baselines/reference/bigIntWithTargetES3.symbols new file mode 100644 index 00000000000..b4415dca87f --- /dev/null +++ b/tests/baselines/reference/bigIntWithTargetES3.symbols @@ -0,0 +1,16 @@ +=== tests/cases/compiler/bigIntWithTargetES3.ts === +const normalNumber = 123; // should not error +>normalNumber : Symbol(normalNumber, Decl(bigIntWithTargetES3.ts, 0, 5)) + +let bigintType: bigint; // should not error +>bigintType : Symbol(bigintType, Decl(bigIntWithTargetES3.ts, 1, 3)) + +let bigintLiteralType: 123n; // should not error when used as type +>bigintLiteralType : Symbol(bigintLiteralType, Decl(bigIntWithTargetES3.ts, 2, 3)) + +let bigintNegativeLiteralType: -123n; // should not error when used as type +>bigintNegativeLiteralType : Symbol(bigintNegativeLiteralType, Decl(bigIntWithTargetES3.ts, 3, 3)) + +const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error +>bigintNumber : Symbol(bigintNumber, Decl(bigIntWithTargetES3.ts, 4, 5)) + diff --git a/tests/baselines/reference/bigIntWithTargetES3.types b/tests/baselines/reference/bigIntWithTargetES3.types new file mode 100644 index 00000000000..ff9b8d80c3d --- /dev/null +++ b/tests/baselines/reference/bigIntWithTargetES3.types @@ -0,0 +1,26 @@ +=== tests/cases/compiler/bigIntWithTargetES3.ts === +const normalNumber = 123; // should not error +>normalNumber : 123 +>123 : 123 + +let bigintType: bigint; // should not error +>bigintType : bigint + +let bigintLiteralType: 123n; // should not error when used as type +>bigintLiteralType : 123n + +let bigintNegativeLiteralType: -123n; // should not error when used as type +>bigintNegativeLiteralType : -123n +>-123n : -123n +>123n : 123n + +const bigintNumber = 123n * 0b1111n + 0o444n * 0x7fn; // each literal should error +>bigintNumber : bigint +>123n * 0b1111n + 0o444n * 0x7fn : bigint +>123n * 0b1111n : bigint +>123n : 123n +>0b1111n : 15n +>0o444n * 0x7fn : bigint +>0o444n : 292n +>0x7fn : 127n + diff --git a/tests/baselines/reference/bigintIndex.errors.txt b/tests/baselines/reference/bigintIndex.errors.txt new file mode 100644 index 00000000000..50e360a1905 --- /dev/null +++ b/tests/baselines/reference/bigintIndex.errors.txt @@ -0,0 +1,59 @@ +tests/cases/compiler/a.ts(2,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/compiler/a.ts(8,11): error TS2538: Type '1n' cannot be used as an index type. +tests/cases/compiler/a.ts(14,1): error TS2322: Type '123n' is not assignable to type 'string | number | symbol'. +tests/cases/compiler/a.ts(19,12): error TS2538: Type 'bigint' cannot be used as an index type. +tests/cases/compiler/b.ts(2,12): error TS1136: Property assignment expected. +tests/cases/compiler/b.ts(2,14): error TS1005: ';' expected. +tests/cases/compiler/b.ts(2,19): error TS1128: Declaration or statement expected. +tests/cases/compiler/b.ts(3,12): error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'. +tests/cases/compiler/b.ts(4,12): error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'. + + +==== tests/cases/compiler/a.ts (4 errors) ==== + interface BigIntIndex { + [index: bigint]: E; // should error + ~~~~~ +!!! error TS1023: An index signature parameter type must be 'string' or 'number'. + } + + const arr: number[] = [1, 2, 3]; + let num: number = arr[1]; + num = arr["1"]; + num = arr[1n]; // should error + ~~ +!!! error TS2538: Type '1n' cannot be used as an index type. + + let key: keyof any; // should be type "string | number | symbol" + key = 123; + key = "abc"; + key = Symbol(); + key = 123n; // should error + ~~~ +!!! error TS2322: Type '123n' is not assignable to type 'string | number | symbol'. + + // Show correct usage of bigint index: explicitly convert to string + const bigNum: bigint = 0n; + const typedArray = new Uint8Array(3); + typedArray[bigNum] = 0xAA; // should error + ~~~~~~ +!!! error TS2538: Type 'bigint' cannot be used as an index type. + typedArray[String(bigNum)] = 0xAA; + typedArray["1"] = 0xBB; + typedArray[2] = 0xCC; + + // {1n: 123} is a syntax error; must go in separate file so BigIntIndex error is shown +==== tests/cases/compiler/b.ts (5 errors) ==== + // BigInt cannot be used as an object literal property + const a = {1n: 123}; + ~~ +!!! error TS1136: Property assignment expected. + ~ +!!! error TS1005: ';' expected. + ~ +!!! error TS1128: Declaration or statement expected. + const b = {[1n]: 456}; + ~~~~ +!!! error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'. + const c = {[bigNum]: 789}; + ~~~~~~~~ +!!! error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'. \ No newline at end of file diff --git a/tests/baselines/reference/bigintIndex.js b/tests/baselines/reference/bigintIndex.js new file mode 100644 index 00000000000..abf2159996e --- /dev/null +++ b/tests/baselines/reference/bigintIndex.js @@ -0,0 +1,59 @@ +//// [tests/cases/compiler/bigintIndex.ts] //// + +//// [a.ts] +interface BigIntIndex { + [index: bigint]: E; // should error +} + +const arr: number[] = [1, 2, 3]; +let num: number = arr[1]; +num = arr["1"]; +num = arr[1n]; // should error + +let key: keyof any; // should be type "string | number | symbol" +key = 123; +key = "abc"; +key = Symbol(); +key = 123n; // should error + +// Show correct usage of bigint index: explicitly convert to string +const bigNum: bigint = 0n; +const typedArray = new Uint8Array(3); +typedArray[bigNum] = 0xAA; // should error +typedArray[String(bigNum)] = 0xAA; +typedArray["1"] = 0xBB; +typedArray[2] = 0xCC; + +// {1n: 123} is a syntax error; must go in separate file so BigIntIndex error is shown +//// [b.ts] +// BigInt cannot be used as an object literal property +const a = {1n: 123}; +const b = {[1n]: 456}; +const c = {[bigNum]: 789}; + +//// [a.js] +const arr = [1, 2, 3]; +let num = arr[1]; +num = arr["1"]; +num = arr[1n]; // should error +let key; // should be type "string | number | symbol" +key = 123; +key = "abc"; +key = Symbol(); +key = 123n; // should error +// Show correct usage of bigint index: explicitly convert to string +const bigNum = 0n; +const typedArray = new Uint8Array(3); +typedArray[bigNum] = 0xAA; // should error +typedArray[String(bigNum)] = 0xAA; +typedArray["1"] = 0xBB; +typedArray[2] = 0xCC; +// {1n: 123} is a syntax error; must go in separate file so BigIntIndex error is shown +//// [b.js] +// BigInt cannot be used as an object literal property +const a = {}; +1n; +123; +; +const b = { [1n]: 456 }; +const c = { [bigNum]: 789 }; diff --git a/tests/baselines/reference/bigintIndex.symbols b/tests/baselines/reference/bigintIndex.symbols new file mode 100644 index 00000000000..c115a0f9daf --- /dev/null +++ b/tests/baselines/reference/bigintIndex.symbols @@ -0,0 +1,79 @@ +=== tests/cases/compiler/a.ts === +interface BigIntIndex { +>BigIntIndex : Symbol(BigIntIndex, Decl(a.ts, 0, 0)) +>E : Symbol(E, Decl(a.ts, 0, 22)) + + [index: bigint]: E; // should error +>index : Symbol(index, Decl(a.ts, 1, 5)) +>E : Symbol(E, Decl(a.ts, 0, 22)) +} + +const arr: number[] = [1, 2, 3]; +>arr : Symbol(arr, Decl(a.ts, 4, 5)) + +let num: number = arr[1]; +>num : Symbol(num, Decl(a.ts, 5, 3)) +>arr : Symbol(arr, Decl(a.ts, 4, 5)) + +num = arr["1"]; +>num : Symbol(num, Decl(a.ts, 5, 3)) +>arr : Symbol(arr, Decl(a.ts, 4, 5)) + +num = arr[1n]; // should error +>num : Symbol(num, Decl(a.ts, 5, 3)) +>arr : Symbol(arr, Decl(a.ts, 4, 5)) + +let key: keyof any; // should be type "string | number | symbol" +>key : Symbol(key, Decl(a.ts, 9, 3)) + +key = 123; +>key : Symbol(key, Decl(a.ts, 9, 3)) + +key = "abc"; +>key : Symbol(key, Decl(a.ts, 9, 3)) + +key = Symbol(); +>key : Symbol(key, Decl(a.ts, 9, 3)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) + +key = 123n; // should error +>key : Symbol(key, Decl(a.ts, 9, 3)) + +// Show correct usage of bigint index: explicitly convert to string +const bigNum: bigint = 0n; +>bigNum : Symbol(bigNum, Decl(a.ts, 16, 5)) + +const typedArray = new Uint8Array(3); +>typedArray : Symbol(typedArray, Decl(a.ts, 17, 5)) +>Uint8Array : Symbol(Uint8Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --)) + +typedArray[bigNum] = 0xAA; // should error +>typedArray : Symbol(typedArray, Decl(a.ts, 17, 5)) +>bigNum : Symbol(bigNum, Decl(a.ts, 16, 5)) + +typedArray[String(bigNum)] = 0xAA; +>typedArray : Symbol(typedArray, Decl(a.ts, 17, 5)) +>String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --) ... and 2 more) +>bigNum : Symbol(bigNum, Decl(a.ts, 16, 5)) + +typedArray["1"] = 0xBB; +>typedArray : Symbol(typedArray, Decl(a.ts, 17, 5)) + +typedArray[2] = 0xCC; +>typedArray : Symbol(typedArray, Decl(a.ts, 17, 5)) + +// {1n: 123} is a syntax error; must go in separate file so BigIntIndex error is shown +=== tests/cases/compiler/b.ts === +// BigInt cannot be used as an object literal property +const a = {1n: 123}; +>a : Symbol(a, Decl(b.ts, 1, 5)) + +const b = {[1n]: 456}; +>b : Symbol(b, Decl(b.ts, 2, 5)) +>[1n] : Symbol([1n], Decl(b.ts, 2, 11)) + +const c = {[bigNum]: 789}; +>c : Symbol(c, Decl(b.ts, 3, 5)) +>[bigNum] : Symbol([bigNum], Decl(b.ts, 3, 11)) +>bigNum : Symbol(bigNum, Decl(a.ts, 16, 5)) + diff --git a/tests/baselines/reference/bigintIndex.types b/tests/baselines/reference/bigintIndex.types new file mode 100644 index 00000000000..a70c1f9aec5 --- /dev/null +++ b/tests/baselines/reference/bigintIndex.types @@ -0,0 +1,121 @@ +=== tests/cases/compiler/a.ts === +interface BigIntIndex { + [index: bigint]: E; // should error +>index : bigint +} + +const arr: number[] = [1, 2, 3]; +>arr : number[] +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 + +let num: number = arr[1]; +>num : number +>arr[1] : number +>arr : number[] +>1 : 1 + +num = arr["1"]; +>num = arr["1"] : any +>num : number +>arr["1"] : any +>arr : number[] +>"1" : "1" + +num = arr[1n]; // should error +>num = arr[1n] : any +>num : number +>arr[1n] : any +>arr : number[] +>1n : 1n + +let key: keyof any; // should be type "string | number | symbol" +>key : string | number | symbol + +key = 123; +>key = 123 : 123 +>key : string | number | symbol +>123 : 123 + +key = "abc"; +>key = "abc" : "abc" +>key : string | number | symbol +>"abc" : "abc" + +key = Symbol(); +>key = Symbol() : symbol +>key : string | number | symbol +>Symbol() : symbol +>Symbol : SymbolConstructor + +key = 123n; // should error +>key = 123n : 123n +>key : string | number | symbol +>123n : 123n + +// Show correct usage of bigint index: explicitly convert to string +const bigNum: bigint = 0n; +>bigNum : bigint +>0n : 0n + +const typedArray = new Uint8Array(3); +>typedArray : Uint8Array +>new Uint8Array(3) : Uint8Array +>Uint8Array : Uint8ArrayConstructor +>3 : 3 + +typedArray[bigNum] = 0xAA; // should error +>typedArray[bigNum] = 0xAA : 170 +>typedArray[bigNum] : any +>typedArray : Uint8Array +>bigNum : bigint +>0xAA : 170 + +typedArray[String(bigNum)] = 0xAA; +>typedArray[String(bigNum)] = 0xAA : 170 +>typedArray[String(bigNum)] : any +>typedArray : Uint8Array +>String(bigNum) : string +>String : StringConstructor +>bigNum : bigint +>0xAA : 170 + +typedArray["1"] = 0xBB; +>typedArray["1"] = 0xBB : 187 +>typedArray["1"] : any +>typedArray : Uint8Array +>"1" : "1" +>0xBB : 187 + +typedArray[2] = 0xCC; +>typedArray[2] = 0xCC : 204 +>typedArray[2] : number +>typedArray : Uint8Array +>2 : 2 +>0xCC : 204 + +// {1n: 123} is a syntax error; must go in separate file so BigIntIndex error is shown +=== tests/cases/compiler/b.ts === +// BigInt cannot be used as an object literal property +const a = {1n: 123}; +>a : {} +>{ : {} +>1n : 1n +>123 : 123 + +const b = {[1n]: 456}; +>b : {} +>{[1n]: 456} : {} +>[1n] : number +>1n : 1n +>456 : 456 + +const c = {[bigNum]: 789}; +>c : {} +>{[bigNum]: 789} : {} +>[bigNum] : number +>bigNum : bigint +>789 : 789 + diff --git a/tests/baselines/reference/bigintWithLib.errors.txt b/tests/baselines/reference/bigintWithLib.errors.txt new file mode 100644 index 00000000000..993f43d5a05 --- /dev/null +++ b/tests/baselines/reference/bigintWithLib.errors.txt @@ -0,0 +1,81 @@ +tests/cases/compiler/bigintWithLib.ts(4,1): error TS2350: Only a void function can be called with the 'new' keyword. +tests/cases/compiler/bigintWithLib.ts(16,33): error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'ArrayBuffer | SharedArrayBuffer'. + Type 'number[]' is missing the following properties from type 'SharedArrayBuffer': byteLength, [Symbol.species], [Symbol.toStringTag] +tests/cases/compiler/bigintWithLib.ts(21,13): error TS2540: Cannot assign to 'length' because it is a read-only property. +tests/cases/compiler/bigintWithLib.ts(28,35): error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'ArrayBuffer | SharedArrayBuffer'. + Type 'number[]' is not assignable to type 'SharedArrayBuffer'. +tests/cases/compiler/bigintWithLib.ts(33,13): error TS2540: Cannot assign to 'length' because it is a read-only property. +tests/cases/compiler/bigintWithLib.ts(40,25): error TS2345: Argument of type '-1' is not assignable to parameter of type 'bigint'. +tests/cases/compiler/bigintWithLib.ts(43,26): error TS2345: Argument of type '123' is not assignable to parameter of type 'bigint'. + + +==== tests/cases/compiler/bigintWithLib.ts (7 errors) ==== + // Test BigInt functions + let bigintVal: bigint = BigInt(123); + bigintVal = BigInt("456"); + new BigInt(123); // should error + ~~~~~~~~~~~~~~~ +!!! error TS2350: Only a void function can be called with the 'new' keyword. + bigintVal = BigInt.asIntN(8, 0xFFFFn); + bigintVal = BigInt.asUintN(8, 0xFFFFn); + bigintVal = bigintVal.valueOf(); + let stringVal: string = bigintVal.toString(); + stringVal = bigintVal.toString(2); + stringVal = bigintVal.toLocaleString(); + + // Test BigInt64Array + let bigIntArray: BigInt64Array = new BigInt64Array(); + bigIntArray = new BigInt64Array(10); + bigIntArray = new BigInt64Array([1n, 2n, 3n]); + bigIntArray = new BigInt64Array([1, 2, 3]); // should error + ~~~~~~~~~ +!!! error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'ArrayBuffer | SharedArrayBuffer'. +!!! error TS2345: Type 'number[]' is missing the following properties from type 'SharedArrayBuffer': byteLength, [Symbol.species], [Symbol.toStringTag] + bigIntArray = new BigInt64Array(new ArrayBuffer(80)); + bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); + bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); + let len: number = bigIntArray.length; + bigIntArray.length = 10; // should error + ~~~~~~ +!!! error TS2540: Cannot assign to 'length' because it is a read-only property. + let arrayBufferLike: ArrayBufferView = bigIntArray; + + // Test BigUint64Array + let bigUintArray: BigUint64Array = new BigUint64Array(); + bigUintArray = new BigUint64Array(10); + bigUintArray = new BigUint64Array([1n, 2n, 3n]); + bigUintArray = new BigUint64Array([1, 2, 3]); // should error + ~~~~~~~~~ +!!! error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'ArrayBuffer | SharedArrayBuffer'. +!!! error TS2345: Type 'number[]' is not assignable to type 'SharedArrayBuffer'. + bigUintArray = new BigUint64Array(new ArrayBuffer(80)); + bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); + bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); + len = bigIntArray.length; + bigIntArray.length = 10; // should error + ~~~~~~ +!!! error TS2540: Cannot assign to 'length' because it is a read-only property. + arrayBufferLike = bigIntArray; + + // Test added DataView methods + const dataView = new DataView(new ArrayBuffer(80)); + dataView.setBigInt64(1, -1n); + dataView.setBigInt64(1, -1n, true); + dataView.setBigInt64(1, -1); // should error + ~~ +!!! error TS2345: Argument of type '-1' is not assignable to parameter of type 'bigint'. + dataView.setBigUint64(2, 123n); + dataView.setBigUint64(2, 123n, true); + dataView.setBigUint64(2, 123); // should error + ~~~ +!!! error TS2345: Argument of type '123' is not assignable to parameter of type 'bigint'. + bigintVal = dataView.getBigInt64(1); + bigintVal = dataView.getBigInt64(1, true); + bigintVal = dataView.getBigUint64(2); + bigintVal = dataView.getBigUint64(2, true); + + // Test emitted declarations files + const w = 12n; // should emit as const w = 12n + const x = -12n; // should emit as const x = -12n + const y: 12n = 12n; // should emit type 12n + let z = 12n; // should emit type bigint in declaration file \ No newline at end of file diff --git a/tests/baselines/reference/bigintWithLib.js b/tests/baselines/reference/bigintWithLib.js new file mode 100644 index 00000000000..754b2144f0c --- /dev/null +++ b/tests/baselines/reference/bigintWithLib.js @@ -0,0 +1,119 @@ +//// [bigintWithLib.ts] +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +bigintVal = BigInt("456"); +new BigInt(123); // should error +bigintVal = BigInt.asIntN(8, 0xFFFFn); +bigintVal = BigInt.asUintN(8, 0xFFFFn); +bigintVal = bigintVal.valueOf(); +let stringVal: string = bigintVal.toString(); +stringVal = bigintVal.toString(2); +stringVal = bigintVal.toLocaleString(); + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +bigIntArray = new BigInt64Array(10); +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +bigIntArray = new BigInt64Array([1, 2, 3]); // should error +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +let len: number = bigIntArray.length; +bigIntArray.length = 10; // should error +let arrayBufferLike: ArrayBufferView = bigIntArray; + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +bigUintArray = new BigUint64Array(10); +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +bigUintArray = new BigUint64Array([1, 2, 3]); // should error +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +len = bigIntArray.length; +bigIntArray.length = 10; // should error +arrayBufferLike = bigIntArray; + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +dataView.setBigInt64(1, -1n); +dataView.setBigInt64(1, -1n, true); +dataView.setBigInt64(1, -1); // should error +dataView.setBigUint64(2, 123n); +dataView.setBigUint64(2, 123n, true); +dataView.setBigUint64(2, 123); // should error +bigintVal = dataView.getBigInt64(1); +bigintVal = dataView.getBigInt64(1, true); +bigintVal = dataView.getBigUint64(2); +bigintVal = dataView.getBigUint64(2, true); + +// Test emitted declarations files +const w = 12n; // should emit as const w = 12n +const x = -12n; // should emit as const x = -12n +const y: 12n = 12n; // should emit type 12n +let z = 12n; // should emit type bigint in declaration file + +//// [bigintWithLib.js] +// Test BigInt functions +let bigintVal = BigInt(123); +bigintVal = BigInt("456"); +new BigInt(123); // should error +bigintVal = BigInt.asIntN(8, 0xffffn); +bigintVal = BigInt.asUintN(8, 0xffffn); +bigintVal = bigintVal.valueOf(); +let stringVal = bigintVal.toString(); +stringVal = bigintVal.toString(2); +stringVal = bigintVal.toLocaleString(); +// Test BigInt64Array +let bigIntArray = new BigInt64Array(); +bigIntArray = new BigInt64Array(10); +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +bigIntArray = new BigInt64Array([1, 2, 3]); // should error +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +let len = bigIntArray.length; +bigIntArray.length = 10; // should error +let arrayBufferLike = bigIntArray; +// Test BigUint64Array +let bigUintArray = new BigUint64Array(); +bigUintArray = new BigUint64Array(10); +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +bigUintArray = new BigUint64Array([1, 2, 3]); // should error +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +len = bigIntArray.length; +bigIntArray.length = 10; // should error +arrayBufferLike = bigIntArray; +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +dataView.setBigInt64(1, -1n); +dataView.setBigInt64(1, -1n, true); +dataView.setBigInt64(1, -1); // should error +dataView.setBigUint64(2, 123n); +dataView.setBigUint64(2, 123n, true); +dataView.setBigUint64(2, 123); // should error +bigintVal = dataView.getBigInt64(1); +bigintVal = dataView.getBigInt64(1, true); +bigintVal = dataView.getBigUint64(2); +bigintVal = dataView.getBigUint64(2, true); +// Test emitted declarations files +const w = 12n; // should emit as const w = 12n +const x = -12n; // should emit as const x = -12n +const y = 12n; // should emit type 12n +let z = 12n; // should emit type bigint in declaration file + + +//// [bigintWithLib.d.ts] +declare let bigintVal: bigint; +declare let stringVal: string; +declare let bigIntArray: BigInt64Array; +declare let len: number; +declare let arrayBufferLike: ArrayBufferView; +declare let bigUintArray: BigUint64Array; +declare const dataView: DataView; +declare const w = 12n; +declare const x = -12n; +declare const y: 12n; +declare let z: bigint; diff --git a/tests/baselines/reference/bigintWithLib.symbols b/tests/baselines/reference/bigintWithLib.symbols new file mode 100644 index 00000000000..cdc80161a45 --- /dev/null +++ b/tests/baselines/reference/bigintWithLib.symbols @@ -0,0 +1,219 @@ +=== tests/cases/compiler/bigintWithLib.ts === +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>BigInt : Symbol(BigInt, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = BigInt("456"); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>BigInt : Symbol(BigInt, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +new BigInt(123); // should error +>BigInt : Symbol(BigInt, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = BigInt.asIntN(8, 0xFFFFn); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>BigInt.asIntN : Symbol(BigIntConstructor.asIntN, Decl(lib.esnext.bigint.d.ts, --, --)) +>BigInt : Symbol(BigInt, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>asIntN : Symbol(BigIntConstructor.asIntN, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = BigInt.asUintN(8, 0xFFFFn); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>BigInt.asUintN : Symbol(BigIntConstructor.asUintN, Decl(lib.esnext.bigint.d.ts, --, --)) +>BigInt : Symbol(BigInt, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>asUintN : Symbol(BigIntConstructor.asUintN, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = bigintVal.valueOf(); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>bigintVal.valueOf : Symbol(BigInt.valueOf, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>valueOf : Symbol(BigInt.valueOf, Decl(lib.esnext.bigint.d.ts, --, --)) + +let stringVal: string = bigintVal.toString(); +>stringVal : Symbol(stringVal, Decl(bigintWithLib.ts, 7, 3)) +>bigintVal.toString : Symbol(BigInt.toString, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>toString : Symbol(BigInt.toString, Decl(lib.esnext.bigint.d.ts, --, --)) + +stringVal = bigintVal.toString(2); +>stringVal : Symbol(stringVal, Decl(bigintWithLib.ts, 7, 3)) +>bigintVal.toString : Symbol(BigInt.toString, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>toString : Symbol(BigInt.toString, Decl(lib.esnext.bigint.d.ts, --, --)) + +stringVal = bigintVal.toLocaleString(); +>stringVal : Symbol(stringVal, Decl(bigintWithLib.ts, 7, 3)) +>bigintVal.toLocaleString : Symbol(BigInt.toLocaleString, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>toLocaleString : Symbol(BigInt.toLocaleString, Decl(lib.esnext.bigint.d.ts, --, --)) + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigIntArray = new BigInt64Array(10); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigIntArray = new BigInt64Array([1, 2, 3]); // should error +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>BigInt64Array : Symbol(BigInt64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +let len: number = bigIntArray.length; +>len : Symbol(len, Decl(bigintWithLib.ts, 19, 3)) +>bigIntArray.length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigIntArray.length = 10; // should error +>bigIntArray.length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) + +let arrayBufferLike: ArrayBufferView = bigIntArray; +>arrayBufferLike : Symbol(arrayBufferLike, Decl(bigintWithLib.ts, 21, 3)) +>ArrayBufferView : Symbol(ArrayBufferView, Decl(lib.es5.d.ts, --, --)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigUintArray = new BigUint64Array(10); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigUintArray = new BigUint64Array([1, 2, 3]); // should error +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) + +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithLib.ts, 24, 3)) +>BigUint64Array : Symbol(BigUint64Array, Decl(lib.esnext.bigint.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +len = bigIntArray.length; +>len : Symbol(len, Decl(bigintWithLib.ts, 19, 3)) +>bigIntArray.length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigIntArray.length = 10; // should error +>bigIntArray.length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) +>length : Symbol(BigInt64Array.length, Decl(lib.esnext.bigint.d.ts, --, --)) + +arrayBufferLike = bigIntArray; +>arrayBufferLike : Symbol(arrayBufferLike, Decl(bigintWithLib.ts, 21, 3)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithLib.ts, 12, 3)) + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>DataView : Symbol(DataView, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.bigint.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) + +dataView.setBigInt64(1, -1n); +>dataView.setBigInt64 : Symbol(DataView.setBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>setBigInt64 : Symbol(DataView.setBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) + +dataView.setBigInt64(1, -1n, true); +>dataView.setBigInt64 : Symbol(DataView.setBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>setBigInt64 : Symbol(DataView.setBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) + +dataView.setBigInt64(1, -1); // should error +>dataView.setBigInt64 : Symbol(DataView.setBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>setBigInt64 : Symbol(DataView.setBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) + +dataView.setBigUint64(2, 123n); +>dataView.setBigUint64 : Symbol(DataView.setBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>setBigUint64 : Symbol(DataView.setBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) + +dataView.setBigUint64(2, 123n, true); +>dataView.setBigUint64 : Symbol(DataView.setBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>setBigUint64 : Symbol(DataView.setBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) + +dataView.setBigUint64(2, 123); // should error +>dataView.setBigUint64 : Symbol(DataView.setBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>setBigUint64 : Symbol(DataView.setBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = dataView.getBigInt64(1); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>dataView.getBigInt64 : Symbol(DataView.getBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>getBigInt64 : Symbol(DataView.getBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = dataView.getBigInt64(1, true); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>dataView.getBigInt64 : Symbol(DataView.getBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>getBigInt64 : Symbol(DataView.getBigInt64, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = dataView.getBigUint64(2); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>dataView.getBigUint64 : Symbol(DataView.getBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>getBigUint64 : Symbol(DataView.getBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) + +bigintVal = dataView.getBigUint64(2, true); +>bigintVal : Symbol(bigintVal, Decl(bigintWithLib.ts, 1, 3)) +>dataView.getBigUint64 : Symbol(DataView.getBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) +>dataView : Symbol(dataView, Decl(bigintWithLib.ts, 36, 5)) +>getBigUint64 : Symbol(DataView.getBigUint64, Decl(lib.esnext.bigint.d.ts, --, --)) + +// Test emitted declarations files +const w = 12n; // should emit as const w = 12n +>w : Symbol(w, Decl(bigintWithLib.ts, 49, 5)) + +const x = -12n; // should emit as const x = -12n +>x : Symbol(x, Decl(bigintWithLib.ts, 50, 5)) + +const y: 12n = 12n; // should emit type 12n +>y : Symbol(y, Decl(bigintWithLib.ts, 51, 5)) + +let z = 12n; // should emit type bigint in declaration file +>z : Symbol(z, Decl(bigintWithLib.ts, 52, 3)) + diff --git a/tests/baselines/reference/bigintWithLib.types b/tests/baselines/reference/bigintWithLib.types new file mode 100644 index 00000000000..a1d79119cf6 --- /dev/null +++ b/tests/baselines/reference/bigintWithLib.types @@ -0,0 +1,352 @@ +=== tests/cases/compiler/bigintWithLib.ts === +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +>bigintVal : bigint +>BigInt(123) : bigint +>BigInt : BigIntConstructor +>123 : 123 + +bigintVal = BigInt("456"); +>bigintVal = BigInt("456") : bigint +>bigintVal : bigint +>BigInt("456") : bigint +>BigInt : BigIntConstructor +>"456" : "456" + +new BigInt(123); // should error +>new BigInt(123) : any +>BigInt : BigIntConstructor +>123 : 123 + +bigintVal = BigInt.asIntN(8, 0xFFFFn); +>bigintVal = BigInt.asIntN(8, 0xFFFFn) : bigint +>bigintVal : bigint +>BigInt.asIntN(8, 0xFFFFn) : bigint +>BigInt.asIntN : (bits: number, int: bigint) => bigint +>BigInt : BigIntConstructor +>asIntN : (bits: number, int: bigint) => bigint +>8 : 8 +>0xFFFFn : 65535n + +bigintVal = BigInt.asUintN(8, 0xFFFFn); +>bigintVal = BigInt.asUintN(8, 0xFFFFn) : bigint +>bigintVal : bigint +>BigInt.asUintN(8, 0xFFFFn) : bigint +>BigInt.asUintN : (bits: number, int: bigint) => bigint +>BigInt : BigIntConstructor +>asUintN : (bits: number, int: bigint) => bigint +>8 : 8 +>0xFFFFn : 65535n + +bigintVal = bigintVal.valueOf(); +>bigintVal = bigintVal.valueOf() : bigint +>bigintVal : bigint +>bigintVal.valueOf() : bigint +>bigintVal.valueOf : () => bigint +>bigintVal : bigint +>valueOf : () => bigint + +let stringVal: string = bigintVal.toString(); +>stringVal : string +>bigintVal.toString() : string +>bigintVal.toString : (radix?: number) => string +>bigintVal : bigint +>toString : (radix?: number) => string + +stringVal = bigintVal.toString(2); +>stringVal = bigintVal.toString(2) : string +>stringVal : string +>bigintVal.toString(2) : string +>bigintVal.toString : (radix?: number) => string +>bigintVal : bigint +>toString : (radix?: number) => string +>2 : 2 + +stringVal = bigintVal.toLocaleString(); +>stringVal = bigintVal.toLocaleString() : string +>stringVal : string +>bigintVal.toLocaleString() : string +>bigintVal.toLocaleString : () => string +>bigintVal : bigint +>toLocaleString : () => string + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +>bigIntArray : BigInt64Array +>new BigInt64Array() : BigInt64Array +>BigInt64Array : BigInt64ArrayConstructor + +bigIntArray = new BigInt64Array(10); +>bigIntArray = new BigInt64Array(10) : BigInt64Array +>bigIntArray : BigInt64Array +>new BigInt64Array(10) : BigInt64Array +>BigInt64Array : BigInt64ArrayConstructor +>10 : 10 + +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +>bigIntArray = new BigInt64Array([1n, 2n, 3n]) : BigInt64Array +>bigIntArray : BigInt64Array +>new BigInt64Array([1n, 2n, 3n]) : BigInt64Array +>BigInt64Array : BigInt64ArrayConstructor +>[1n, 2n, 3n] : bigint[] +>1n : 1n +>2n : 2n +>3n : 3n + +bigIntArray = new BigInt64Array([1, 2, 3]); // should error +>bigIntArray = new BigInt64Array([1, 2, 3]) : any +>bigIntArray : BigInt64Array +>new BigInt64Array([1, 2, 3]) : any +>BigInt64Array : BigInt64ArrayConstructor +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 + +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +>bigIntArray = new BigInt64Array(new ArrayBuffer(80)) : BigInt64Array +>bigIntArray : BigInt64Array +>new BigInt64Array(new ArrayBuffer(80)) : BigInt64Array +>BigInt64Array : BigInt64ArrayConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +>bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8) : BigInt64Array +>bigIntArray : BigInt64Array +>new BigInt64Array(new ArrayBuffer(80), 8) : BigInt64Array +>BigInt64Array : BigInt64ArrayConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +>bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3) : BigInt64Array +>bigIntArray : BigInt64Array +>new BigInt64Array(new ArrayBuffer(80), 8, 3) : BigInt64Array +>BigInt64Array : BigInt64ArrayConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 +>3 : 3 + +let len: number = bigIntArray.length; +>len : number +>bigIntArray.length : number +>bigIntArray : BigInt64Array +>length : number + +bigIntArray.length = 10; // should error +>bigIntArray.length = 10 : 10 +>bigIntArray.length : any +>bigIntArray : BigInt64Array +>length : any +>10 : 10 + +let arrayBufferLike: ArrayBufferView = bigIntArray; +>arrayBufferLike : ArrayBufferView +>bigIntArray : BigInt64Array + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +>bigUintArray : BigUint64Array +>new BigUint64Array() : BigUint64Array +>BigUint64Array : BigUint64ArrayConstructor + +bigUintArray = new BigUint64Array(10); +>bigUintArray = new BigUint64Array(10) : BigUint64Array +>bigUintArray : BigUint64Array +>new BigUint64Array(10) : BigUint64Array +>BigUint64Array : BigUint64ArrayConstructor +>10 : 10 + +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +>bigUintArray = new BigUint64Array([1n, 2n, 3n]) : BigUint64Array +>bigUintArray : BigUint64Array +>new BigUint64Array([1n, 2n, 3n]) : BigUint64Array +>BigUint64Array : BigUint64ArrayConstructor +>[1n, 2n, 3n] : bigint[] +>1n : 1n +>2n : 2n +>3n : 3n + +bigUintArray = new BigUint64Array([1, 2, 3]); // should error +>bigUintArray = new BigUint64Array([1, 2, 3]) : any +>bigUintArray : BigUint64Array +>new BigUint64Array([1, 2, 3]) : any +>BigUint64Array : BigUint64ArrayConstructor +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 + +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +>bigUintArray = new BigUint64Array(new ArrayBuffer(80)) : BigUint64Array +>bigUintArray : BigUint64Array +>new BigUint64Array(new ArrayBuffer(80)) : BigUint64Array +>BigUint64Array : BigUint64ArrayConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +>bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8) : BigUint64Array +>bigUintArray : BigUint64Array +>new BigUint64Array(new ArrayBuffer(80), 8) : BigUint64Array +>BigUint64Array : BigUint64ArrayConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +>bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3) : BigUint64Array +>bigUintArray : BigUint64Array +>new BigUint64Array(new ArrayBuffer(80), 8, 3) : BigUint64Array +>BigUint64Array : BigUint64ArrayConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 +>3 : 3 + +len = bigIntArray.length; +>len = bigIntArray.length : number +>len : number +>bigIntArray.length : number +>bigIntArray : BigInt64Array +>length : number + +bigIntArray.length = 10; // should error +>bigIntArray.length = 10 : 10 +>bigIntArray.length : any +>bigIntArray : BigInt64Array +>length : any +>10 : 10 + +arrayBufferLike = bigIntArray; +>arrayBufferLike = bigIntArray : BigInt64Array +>arrayBufferLike : ArrayBufferView +>bigIntArray : BigInt64Array + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +>dataView : DataView +>new DataView(new ArrayBuffer(80)) : DataView +>DataView : DataViewConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 + +dataView.setBigInt64(1, -1n); +>dataView.setBigInt64(1, -1n) : void +>dataView.setBigInt64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>dataView : DataView +>setBigInt64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>1 : 1 +>-1n : -1n +>1n : 1n + +dataView.setBigInt64(1, -1n, true); +>dataView.setBigInt64(1, -1n, true) : void +>dataView.setBigInt64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>dataView : DataView +>setBigInt64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>1 : 1 +>-1n : -1n +>1n : 1n +>true : true + +dataView.setBigInt64(1, -1); // should error +>dataView.setBigInt64(1, -1) : void +>dataView.setBigInt64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>dataView : DataView +>setBigInt64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>1 : 1 +>-1 : -1 +>1 : 1 + +dataView.setBigUint64(2, 123n); +>dataView.setBigUint64(2, 123n) : void +>dataView.setBigUint64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>dataView : DataView +>setBigUint64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>2 : 2 +>123n : 123n + +dataView.setBigUint64(2, 123n, true); +>dataView.setBigUint64(2, 123n, true) : void +>dataView.setBigUint64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>dataView : DataView +>setBigUint64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>2 : 2 +>123n : 123n +>true : true + +dataView.setBigUint64(2, 123); // should error +>dataView.setBigUint64(2, 123) : void +>dataView.setBigUint64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>dataView : DataView +>setBigUint64 : (byteOffset: number, value: bigint, littleEndian?: boolean) => void +>2 : 2 +>123 : 123 + +bigintVal = dataView.getBigInt64(1); +>bigintVal = dataView.getBigInt64(1) : bigint +>bigintVal : bigint +>dataView.getBigInt64(1) : bigint +>dataView.getBigInt64 : (byteOffset: number, littleEndian?: boolean) => bigint +>dataView : DataView +>getBigInt64 : (byteOffset: number, littleEndian?: boolean) => bigint +>1 : 1 + +bigintVal = dataView.getBigInt64(1, true); +>bigintVal = dataView.getBigInt64(1, true) : bigint +>bigintVal : bigint +>dataView.getBigInt64(1, true) : bigint +>dataView.getBigInt64 : (byteOffset: number, littleEndian?: boolean) => bigint +>dataView : DataView +>getBigInt64 : (byteOffset: number, littleEndian?: boolean) => bigint +>1 : 1 +>true : true + +bigintVal = dataView.getBigUint64(2); +>bigintVal = dataView.getBigUint64(2) : bigint +>bigintVal : bigint +>dataView.getBigUint64(2) : bigint +>dataView.getBigUint64 : (byteOffset: number, littleEndian?: boolean) => bigint +>dataView : DataView +>getBigUint64 : (byteOffset: number, littleEndian?: boolean) => bigint +>2 : 2 + +bigintVal = dataView.getBigUint64(2, true); +>bigintVal = dataView.getBigUint64(2, true) : bigint +>bigintVal : bigint +>dataView.getBigUint64(2, true) : bigint +>dataView.getBigUint64 : (byteOffset: number, littleEndian?: boolean) => bigint +>dataView : DataView +>getBigUint64 : (byteOffset: number, littleEndian?: boolean) => bigint +>2 : 2 +>true : true + +// Test emitted declarations files +const w = 12n; // should emit as const w = 12n +>w : 12n +>12n : 12n + +const x = -12n; // should emit as const x = -12n +>x : -12n +>-12n : -12n +>12n : 12n + +const y: 12n = 12n; // should emit type 12n +>y : 12n +>12n : 12n + +let z = 12n; // should emit type bigint in declaration file +>z : bigint +>12n : 12n + diff --git a/tests/baselines/reference/bigintWithoutLib.errors.txt b/tests/baselines/reference/bigintWithoutLib.errors.txt new file mode 100644 index 00000000000..7d2c38b29df --- /dev/null +++ b/tests/baselines/reference/bigintWithoutLib.errors.txt @@ -0,0 +1,191 @@ +tests/cases/compiler/bigintWithoutLib.ts(4,25): error TS2304: Cannot find name 'BigInt'. +tests/cases/compiler/bigintWithoutLib.ts(5,13): error TS2304: Cannot find name 'BigInt'. +tests/cases/compiler/bigintWithoutLib.ts(6,5): error TS2304: Cannot find name 'BigInt'. +tests/cases/compiler/bigintWithoutLib.ts(7,13): error TS2304: Cannot find name 'BigInt'. +tests/cases/compiler/bigintWithoutLib.ts(7,30): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(8,13): error TS2304: Cannot find name 'BigInt'. +tests/cases/compiler/bigintWithoutLib.ts(8,31): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(9,1): error TS2322: Type 'Object' is not assignable to type 'bigint'. +tests/cases/compiler/bigintWithoutLib.ts(11,13): error TS2554: Expected 0 arguments, but got 1. +tests/cases/compiler/bigintWithoutLib.ts(15,18): error TS2304: Cannot find name 'BigInt64Array'. +tests/cases/compiler/bigintWithoutLib.ts(15,38): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +tests/cases/compiler/bigintWithoutLib.ts(16,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +tests/cases/compiler/bigintWithoutLib.ts(17,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +tests/cases/compiler/bigintWithoutLib.ts(17,34): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(17,38): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(17,42): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(18,19): error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +tests/cases/compiler/bigintWithoutLib.ts(19,19): error TS2304: Cannot find name 'BigInt64Array'. +tests/cases/compiler/bigintWithoutLib.ts(20,19): error TS2304: Cannot find name 'BigInt64Array'. +tests/cases/compiler/bigintWithoutLib.ts(21,19): error TS2304: Cannot find name 'BigInt64Array'. +tests/cases/compiler/bigintWithoutLib.ts(27,19): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(27,40): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(28,20): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(29,20): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(29,36): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(29,40): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(29,44): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(30,20): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(31,20): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(32,20): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(33,20): error TS2304: Cannot find name 'BigUint64Array'. +tests/cases/compiler/bigintWithoutLib.ts(40,10): error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(40,26): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(41,10): error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(41,26): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(42,10): error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(43,10): error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(43,26): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(44,10): error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(44,26): error TS2737: BigInt literals are not available when targeting lower than ESNext. +tests/cases/compiler/bigintWithoutLib.ts(45,10): error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(46,22): error TS2339: Property 'getBigInt64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(47,22): error TS2339: Property 'getBigInt64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(48,22): error TS2339: Property 'getBigUint64' does not exist on type 'DataView'. +tests/cases/compiler/bigintWithoutLib.ts(49,22): error TS2339: Property 'getBigUint64' does not exist on type 'DataView'. + + +==== tests/cases/compiler/bigintWithoutLib.ts (45 errors) ==== + // Every line should error because these builtins are not declared + + // Test BigInt functions + let bigintVal: bigint = BigInt(123); + ~~~~~~ +!!! error TS2304: Cannot find name 'BigInt'. + bigintVal = BigInt("456"); + ~~~~~~ +!!! error TS2304: Cannot find name 'BigInt'. + new BigInt(123); + ~~~~~~ +!!! error TS2304: Cannot find name 'BigInt'. + bigintVal = BigInt.asIntN(8, 0xFFFFn); + ~~~~~~ +!!! error TS2304: Cannot find name 'BigInt'. + ~~~~~~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + bigintVal = BigInt.asUintN(8, 0xFFFFn); + ~~~~~~ +!!! error TS2304: Cannot find name 'BigInt'. + ~~~~~~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} + ~~~~~~~~~ +!!! error TS2322: Type 'Object' is not assignable to type 'bigint'. + let stringVal: string = bigintVal.toString(); // should not error - bigintVal inferred as {} + stringVal = bigintVal.toString(2); // should error - bigintVal inferred as {} + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2554: Expected 0 arguments, but got 1. + stringVal = bigintVal.toLocaleString(); // should not error - bigintVal inferred as {} + + // Test BigInt64Array + let bigIntArray: BigInt64Array = new BigInt64Array(); + ~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigInt64Array'. + ~~~~~~~~~~~~~ +!!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +!!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:15:5: 'bigIntArray' is declared here. + bigIntArray = new BigInt64Array(10); + ~~~~~~~~~~~~~ +!!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +!!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:15:5: 'bigIntArray' is declared here. + bigIntArray = new BigInt64Array([1n, 2n, 3n]); + ~~~~~~~~~~~~~ +!!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +!!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:15:5: 'bigIntArray' is declared here. + ~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + ~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + ~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + bigIntArray = new BigInt64Array([1, 2, 3]); + ~~~~~~~~~~~~~ +!!! error TS2552: Cannot find name 'BigInt64Array'. Did you mean 'bigIntArray'? +!!! related TS2728 tests/cases/compiler/bigintWithoutLib.ts:15:5: 'bigIntArray' is declared here. + bigIntArray = new BigInt64Array(new ArrayBuffer(80)); + ~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigInt64Array'. + bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); + ~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigInt64Array'. + bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); + ~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigInt64Array'. + let len: number = bigIntArray.length; + bigIntArray.length = 10; + let arrayBufferLike: ArrayBufferView = bigIntArray; + + // Test BigUint64Array + let bigUintArray: BigUint64Array = new BigUint64Array(); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + bigUintArray = new BigUint64Array(10); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + bigUintArray = new BigUint64Array([1n, 2n, 3n]); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + ~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + ~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + ~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + bigUintArray = new BigUint64Array([1, 2, 3]); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + bigUintArray = new BigUint64Array(new ArrayBuffer(80)); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); + ~~~~~~~~~~~~~~ +!!! error TS2304: Cannot find name 'BigUint64Array'. + len = bigIntArray.length; + bigIntArray.length = 10; + arrayBufferLike = bigIntArray; + + // Test added DataView methods + const dataView = new DataView(new ArrayBuffer(80)); + dataView.setBigInt64(1, -1n); + ~~~~~~~~~~~ +!!! error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. + ~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + dataView.setBigInt64(1, -1n, true); + ~~~~~~~~~~~ +!!! error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. + ~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + dataView.setBigInt64(1, -1); + ~~~~~~~~~~~ +!!! error TS2339: Property 'setBigInt64' does not exist on type 'DataView'. + dataView.setBigUint64(2, 123n); + ~~~~~~~~~~~~ +!!! error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. + ~~~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + dataView.setBigUint64(2, 123n, true); + ~~~~~~~~~~~~ +!!! error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. + ~~~~ +!!! error TS2737: BigInt literals are not available when targeting lower than ESNext. + dataView.setBigUint64(2, 123); + ~~~~~~~~~~~~ +!!! error TS2339: Property 'setBigUint64' does not exist on type 'DataView'. + bigintVal = dataView.getBigInt64(1); + ~~~~~~~~~~~ +!!! error TS2339: Property 'getBigInt64' does not exist on type 'DataView'. + bigintVal = dataView.getBigInt64(1, true); + ~~~~~~~~~~~ +!!! error TS2339: Property 'getBigInt64' does not exist on type 'DataView'. + bigintVal = dataView.getBigUint64(2); + ~~~~~~~~~~~~ +!!! error TS2339: Property 'getBigUint64' does not exist on type 'DataView'. + bigintVal = dataView.getBigUint64(2, true); + ~~~~~~~~~~~~ +!!! error TS2339: Property 'getBigUint64' does not exist on type 'DataView'. \ No newline at end of file diff --git a/tests/baselines/reference/bigintWithoutLib.js b/tests/baselines/reference/bigintWithoutLib.js new file mode 100644 index 00000000000..31a59fcbaf0 --- /dev/null +++ b/tests/baselines/reference/bigintWithoutLib.js @@ -0,0 +1,97 @@ +//// [bigintWithoutLib.ts] +// Every line should error because these builtins are not declared + +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +bigintVal = BigInt("456"); +new BigInt(123); +bigintVal = BigInt.asIntN(8, 0xFFFFn); +bigintVal = BigInt.asUintN(8, 0xFFFFn); +bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} +let stringVal: string = bigintVal.toString(); // should not error - bigintVal inferred as {} +stringVal = bigintVal.toString(2); // should error - bigintVal inferred as {} +stringVal = bigintVal.toLocaleString(); // should not error - bigintVal inferred as {} + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +bigIntArray = new BigInt64Array(10); +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +bigIntArray = new BigInt64Array([1, 2, 3]); +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +let len: number = bigIntArray.length; +bigIntArray.length = 10; +let arrayBufferLike: ArrayBufferView = bigIntArray; + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +bigUintArray = new BigUint64Array(10); +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +bigUintArray = new BigUint64Array([1, 2, 3]); +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +len = bigIntArray.length; +bigIntArray.length = 10; +arrayBufferLike = bigIntArray; + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +dataView.setBigInt64(1, -1n); +dataView.setBigInt64(1, -1n, true); +dataView.setBigInt64(1, -1); +dataView.setBigUint64(2, 123n); +dataView.setBigUint64(2, 123n, true); +dataView.setBigUint64(2, 123); +bigintVal = dataView.getBigInt64(1); +bigintVal = dataView.getBigInt64(1, true); +bigintVal = dataView.getBigUint64(2); +bigintVal = dataView.getBigUint64(2, true); + +//// [bigintWithoutLib.js] +// Every line should error because these builtins are not declared +// Test BigInt functions +var bigintVal = BigInt(123); +bigintVal = BigInt("456"); +new BigInt(123); +bigintVal = BigInt.asIntN(8, 0xffffn); +bigintVal = BigInt.asUintN(8, 0xffffn); +bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} +var stringVal = bigintVal.toString(); // should not error - bigintVal inferred as {} +stringVal = bigintVal.toString(2); // should error - bigintVal inferred as {} +stringVal = bigintVal.toLocaleString(); // should not error - bigintVal inferred as {} +// Test BigInt64Array +var bigIntArray = new BigInt64Array(); +bigIntArray = new BigInt64Array(10); +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +bigIntArray = new BigInt64Array([1, 2, 3]); +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +var len = bigIntArray.length; +bigIntArray.length = 10; +var arrayBufferLike = bigIntArray; +// Test BigUint64Array +var bigUintArray = new BigUint64Array(); +bigUintArray = new BigUint64Array(10); +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +bigUintArray = new BigUint64Array([1, 2, 3]); +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +len = bigIntArray.length; +bigIntArray.length = 10; +arrayBufferLike = bigIntArray; +// Test added DataView methods +var dataView = new DataView(new ArrayBuffer(80)); +dataView.setBigInt64(1, -1n); +dataView.setBigInt64(1, -1n, true); +dataView.setBigInt64(1, -1); +dataView.setBigUint64(2, 123n); +dataView.setBigUint64(2, 123n, true); +dataView.setBigUint64(2, 123); +bigintVal = dataView.getBigInt64(1); +bigintVal = dataView.getBigInt64(1, true); +bigintVal = dataView.getBigUint64(2); +bigintVal = dataView.getBigUint64(2, true); diff --git a/tests/baselines/reference/bigintWithoutLib.symbols b/tests/baselines/reference/bigintWithoutLib.symbols new file mode 100644 index 00000000000..35e69305e18 --- /dev/null +++ b/tests/baselines/reference/bigintWithoutLib.symbols @@ -0,0 +1,154 @@ +=== tests/cases/compiler/bigintWithoutLib.ts === +// Every line should error because these builtins are not declared + +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) + +bigintVal = BigInt("456"); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) + +new BigInt(123); +bigintVal = BigInt.asIntN(8, 0xFFFFn); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) + +bigintVal = BigInt.asUintN(8, 0xFFFFn); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) + +bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>bigintVal.valueOf : Symbol(Object.valueOf, Decl(lib.es5.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>valueOf : Symbol(Object.valueOf, Decl(lib.es5.d.ts, --, --)) + +let stringVal: string = bigintVal.toString(); // should not error - bigintVal inferred as {} +>stringVal : Symbol(stringVal, Decl(bigintWithoutLib.ts, 9, 3)) +>bigintVal.toString : Symbol(Object.toString, Decl(lib.es5.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>toString : Symbol(Object.toString, Decl(lib.es5.d.ts, --, --)) + +stringVal = bigintVal.toString(2); // should error - bigintVal inferred as {} +>stringVal : Symbol(stringVal, Decl(bigintWithoutLib.ts, 9, 3)) +>bigintVal.toString : Symbol(Object.toString, Decl(lib.es5.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>toString : Symbol(Object.toString, Decl(lib.es5.d.ts, --, --)) + +stringVal = bigintVal.toLocaleString(); // should not error - bigintVal inferred as {} +>stringVal : Symbol(stringVal, Decl(bigintWithoutLib.ts, 9, 3)) +>bigintVal.toLocaleString : Symbol(Object.toLocaleString, Decl(lib.es5.d.ts, --, --)) +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>toLocaleString : Symbol(Object.toLocaleString, Decl(lib.es5.d.ts, --, --)) + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +bigIntArray = new BigInt64Array(10); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +bigIntArray = new BigInt64Array([1, 2, 3]); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +let len: number = bigIntArray.length; +>len : Symbol(len, Decl(bigintWithoutLib.ts, 21, 3)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +bigIntArray.length = 10; +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +let arrayBufferLike: ArrayBufferView = bigIntArray; +>arrayBufferLike : Symbol(arrayBufferLike, Decl(bigintWithoutLib.ts, 23, 3)) +>ArrayBufferView : Symbol(ArrayBufferView, Decl(lib.es5.d.ts, --, --)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) + +bigUintArray = new BigUint64Array(10); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) + +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) + +bigUintArray = new BigUint64Array([1, 2, 3]); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) + +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +>bigUintArray : Symbol(bigUintArray, Decl(bigintWithoutLib.ts, 26, 3)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +len = bigIntArray.length; +>len : Symbol(len, Decl(bigintWithoutLib.ts, 21, 3)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +bigIntArray.length = 10; +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +arrayBufferLike = bigIntArray; +>arrayBufferLike : Symbol(arrayBufferLike, Decl(bigintWithoutLib.ts, 23, 3)) +>bigIntArray : Symbol(bigIntArray, Decl(bigintWithoutLib.ts, 14, 3)) + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) +>DataView : Symbol(DataView, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>ArrayBuffer : Symbol(ArrayBuffer, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +dataView.setBigInt64(1, -1n); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +dataView.setBigInt64(1, -1n, true); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +dataView.setBigInt64(1, -1); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +dataView.setBigUint64(2, 123n); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +dataView.setBigUint64(2, 123n, true); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +dataView.setBigUint64(2, 123); +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +bigintVal = dataView.getBigInt64(1); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +bigintVal = dataView.getBigInt64(1, true); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +bigintVal = dataView.getBigUint64(2); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + +bigintVal = dataView.getBigUint64(2, true); +>bigintVal : Symbol(bigintVal, Decl(bigintWithoutLib.ts, 3, 3)) +>dataView : Symbol(dataView, Decl(bigintWithoutLib.ts, 38, 5)) + diff --git a/tests/baselines/reference/bigintWithoutLib.types b/tests/baselines/reference/bigintWithoutLib.types new file mode 100644 index 00000000000..6881b53b7da --- /dev/null +++ b/tests/baselines/reference/bigintWithoutLib.types @@ -0,0 +1,336 @@ +=== tests/cases/compiler/bigintWithoutLib.ts === +// Every line should error because these builtins are not declared + +// Test BigInt functions +let bigintVal: bigint = BigInt(123); +>bigintVal : bigint +>BigInt(123) : any +>BigInt : any +>123 : 123 + +bigintVal = BigInt("456"); +>bigintVal = BigInt("456") : any +>bigintVal : bigint +>BigInt("456") : any +>BigInt : any +>"456" : "456" + +new BigInt(123); +>new BigInt(123) : any +>BigInt : any +>123 : 123 + +bigintVal = BigInt.asIntN(8, 0xFFFFn); +>bigintVal = BigInt.asIntN(8, 0xFFFFn) : any +>bigintVal : bigint +>BigInt.asIntN(8, 0xFFFFn) : any +>BigInt.asIntN : any +>BigInt : any +>asIntN : any +>8 : 8 +>0xFFFFn : 65535n + +bigintVal = BigInt.asUintN(8, 0xFFFFn); +>bigintVal = BigInt.asUintN(8, 0xFFFFn) : any +>bigintVal : bigint +>BigInt.asUintN(8, 0xFFFFn) : any +>BigInt.asUintN : any +>BigInt : any +>asUintN : any +>8 : 8 +>0xFFFFn : 65535n + +bigintVal = bigintVal.valueOf(); // should error - bigintVal inferred as {} +>bigintVal = bigintVal.valueOf() : Object +>bigintVal : bigint +>bigintVal.valueOf() : Object +>bigintVal.valueOf : () => Object +>bigintVal : bigint +>valueOf : () => Object + +let stringVal: string = bigintVal.toString(); // should not error - bigintVal inferred as {} +>stringVal : string +>bigintVal.toString() : string +>bigintVal.toString : () => string +>bigintVal : bigint +>toString : () => string + +stringVal = bigintVal.toString(2); // should error - bigintVal inferred as {} +>stringVal = bigintVal.toString(2) : any +>stringVal : string +>bigintVal.toString(2) : string +>bigintVal.toString : () => string +>bigintVal : bigint +>toString : () => string +>2 : 2 + +stringVal = bigintVal.toLocaleString(); // should not error - bigintVal inferred as {} +>stringVal = bigintVal.toLocaleString() : string +>stringVal : string +>bigintVal.toLocaleString() : string +>bigintVal.toLocaleString : () => string +>bigintVal : bigint +>toLocaleString : () => string + +// Test BigInt64Array +let bigIntArray: BigInt64Array = new BigInt64Array(); +>bigIntArray : any +>new BigInt64Array() : any +>BigInt64Array : any + +bigIntArray = new BigInt64Array(10); +>bigIntArray = new BigInt64Array(10) : any +>bigIntArray : any +>new BigInt64Array(10) : any +>BigInt64Array : any +>10 : 10 + +bigIntArray = new BigInt64Array([1n, 2n, 3n]); +>bigIntArray = new BigInt64Array([1n, 2n, 3n]) : any +>bigIntArray : any +>new BigInt64Array([1n, 2n, 3n]) : any +>BigInt64Array : any +>[1n, 2n, 3n] : bigint[] +>1n : 1n +>2n : 2n +>3n : 3n + +bigIntArray = new BigInt64Array([1, 2, 3]); +>bigIntArray = new BigInt64Array([1, 2, 3]) : any +>bigIntArray : any +>new BigInt64Array([1, 2, 3]) : any +>BigInt64Array : any +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 + +bigIntArray = new BigInt64Array(new ArrayBuffer(80)); +>bigIntArray = new BigInt64Array(new ArrayBuffer(80)) : any +>bigIntArray : any +>new BigInt64Array(new ArrayBuffer(80)) : any +>BigInt64Array : any +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8); +>bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8) : any +>bigIntArray : any +>new BigInt64Array(new ArrayBuffer(80), 8) : any +>BigInt64Array : any +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 + +bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3); +>bigIntArray = new BigInt64Array(new ArrayBuffer(80), 8, 3) : any +>bigIntArray : any +>new BigInt64Array(new ArrayBuffer(80), 8, 3) : any +>BigInt64Array : any +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 +>3 : 3 + +let len: number = bigIntArray.length; +>len : number +>bigIntArray.length : any +>bigIntArray : any +>length : any + +bigIntArray.length = 10; +>bigIntArray.length = 10 : 10 +>bigIntArray.length : any +>bigIntArray : any +>length : any +>10 : 10 + +let arrayBufferLike: ArrayBufferView = bigIntArray; +>arrayBufferLike : ArrayBufferView +>bigIntArray : any + +// Test BigUint64Array +let bigUintArray: BigUint64Array = new BigUint64Array(); +>bigUintArray : any +>new BigUint64Array() : any +>BigUint64Array : any + +bigUintArray = new BigUint64Array(10); +>bigUintArray = new BigUint64Array(10) : any +>bigUintArray : any +>new BigUint64Array(10) : any +>BigUint64Array : any +>10 : 10 + +bigUintArray = new BigUint64Array([1n, 2n, 3n]); +>bigUintArray = new BigUint64Array([1n, 2n, 3n]) : any +>bigUintArray : any +>new BigUint64Array([1n, 2n, 3n]) : any +>BigUint64Array : any +>[1n, 2n, 3n] : bigint[] +>1n : 1n +>2n : 2n +>3n : 3n + +bigUintArray = new BigUint64Array([1, 2, 3]); +>bigUintArray = new BigUint64Array([1, 2, 3]) : any +>bigUintArray : any +>new BigUint64Array([1, 2, 3]) : any +>BigUint64Array : any +>[1, 2, 3] : number[] +>1 : 1 +>2 : 2 +>3 : 3 + +bigUintArray = new BigUint64Array(new ArrayBuffer(80)); +>bigUintArray = new BigUint64Array(new ArrayBuffer(80)) : any +>bigUintArray : any +>new BigUint64Array(new ArrayBuffer(80)) : any +>BigUint64Array : any +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8); +>bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8) : any +>bigUintArray : any +>new BigUint64Array(new ArrayBuffer(80), 8) : any +>BigUint64Array : any +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 + +bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3); +>bigUintArray = new BigUint64Array(new ArrayBuffer(80), 8, 3) : any +>bigUintArray : any +>new BigUint64Array(new ArrayBuffer(80), 8, 3) : any +>BigUint64Array : any +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 +>8 : 8 +>3 : 3 + +len = bigIntArray.length; +>len = bigIntArray.length : any +>len : number +>bigIntArray.length : any +>bigIntArray : any +>length : any + +bigIntArray.length = 10; +>bigIntArray.length = 10 : 10 +>bigIntArray.length : any +>bigIntArray : any +>length : any +>10 : 10 + +arrayBufferLike = bigIntArray; +>arrayBufferLike = bigIntArray : any +>arrayBufferLike : ArrayBufferView +>bigIntArray : any + +// Test added DataView methods +const dataView = new DataView(new ArrayBuffer(80)); +>dataView : DataView +>new DataView(new ArrayBuffer(80)) : DataView +>DataView : DataViewConstructor +>new ArrayBuffer(80) : ArrayBuffer +>ArrayBuffer : ArrayBufferConstructor +>80 : 80 + +dataView.setBigInt64(1, -1n); +>dataView.setBigInt64(1, -1n) : any +>dataView.setBigInt64 : any +>dataView : DataView +>setBigInt64 : any +>1 : 1 +>-1n : -1n +>1n : 1n + +dataView.setBigInt64(1, -1n, true); +>dataView.setBigInt64(1, -1n, true) : any +>dataView.setBigInt64 : any +>dataView : DataView +>setBigInt64 : any +>1 : 1 +>-1n : -1n +>1n : 1n +>true : true + +dataView.setBigInt64(1, -1); +>dataView.setBigInt64(1, -1) : any +>dataView.setBigInt64 : any +>dataView : DataView +>setBigInt64 : any +>1 : 1 +>-1 : -1 +>1 : 1 + +dataView.setBigUint64(2, 123n); +>dataView.setBigUint64(2, 123n) : any +>dataView.setBigUint64 : any +>dataView : DataView +>setBigUint64 : any +>2 : 2 +>123n : 123n + +dataView.setBigUint64(2, 123n, true); +>dataView.setBigUint64(2, 123n, true) : any +>dataView.setBigUint64 : any +>dataView : DataView +>setBigUint64 : any +>2 : 2 +>123n : 123n +>true : true + +dataView.setBigUint64(2, 123); +>dataView.setBigUint64(2, 123) : any +>dataView.setBigUint64 : any +>dataView : DataView +>setBigUint64 : any +>2 : 2 +>123 : 123 + +bigintVal = dataView.getBigInt64(1); +>bigintVal = dataView.getBigInt64(1) : any +>bigintVal : bigint +>dataView.getBigInt64(1) : any +>dataView.getBigInt64 : any +>dataView : DataView +>getBigInt64 : any +>1 : 1 + +bigintVal = dataView.getBigInt64(1, true); +>bigintVal = dataView.getBigInt64(1, true) : any +>bigintVal : bigint +>dataView.getBigInt64(1, true) : any +>dataView.getBigInt64 : any +>dataView : DataView +>getBigInt64 : any +>1 : 1 +>true : true + +bigintVal = dataView.getBigUint64(2); +>bigintVal = dataView.getBigUint64(2) : any +>bigintVal : bigint +>dataView.getBigUint64(2) : any +>dataView.getBigUint64 : any +>dataView : DataView +>getBigUint64 : any +>2 : 2 + +bigintVal = dataView.getBigUint64(2, true); +>bigintVal = dataView.getBigUint64(2, true) : any +>bigintVal : bigint +>dataView.getBigUint64(2, true) : any +>dataView.getBigUint64 : any +>dataView : DataView +>getBigUint64 : any +>2 : 2 +>true : true + diff --git a/tests/baselines/reference/bitwiseCompoundAssignmentOperators.errors.txt b/tests/baselines/reference/bitwiseCompoundAssignmentOperators.errors.txt index ae7a8fdce0a..221ac478cd6 100644 --- a/tests/baselines/reference/bitwiseCompoundAssignmentOperators.errors.txt +++ b/tests/baselines/reference/bitwiseCompoundAssignmentOperators.errors.txt @@ -1,11 +1,11 @@ tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(3,1): error TS2447: The '^=' operator is not allowed for boolean types. Consider using '!==' instead. -tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(9,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(7,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(9,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(14,1): error TS2447: The '&=' operator is not allowed for boolean types. Consider using '&&' instead. -tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. -tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(20,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(18,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(20,6): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(24,1): error TS2447: The '|=' operator is not allowed for boolean types. Consider using '||' instead. -tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(28,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(28,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts (8 errors) ==== @@ -19,11 +19,11 @@ tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(28,1): error TS2362: b = 1; a ^= b; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. a = true; b ^= a; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. b = 1; var c = false; @@ -36,11 +36,11 @@ tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(28,1): error TS2362: d = 2; c &= d; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. c = false; d &= c; ~ -!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. var e = true; var f = 0; @@ -52,7 +52,7 @@ tests/cases/compiler/bitwiseCompoundAssignmentOperators.ts(28,1): error TS2362: f = 0; e |= f; ~ -!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. e = true; f |= f; diff --git a/tests/baselines/reference/bivariantInferences.js b/tests/baselines/reference/bivariantInferences.js new file mode 100644 index 00000000000..a910ca15e93 --- /dev/null +++ b/tests/baselines/reference/bivariantInferences.js @@ -0,0 +1,17 @@ +//// [bivariantInferences.ts] +// Repro from #27337 + +interface Array { + equalsShallow(this: ReadonlyArray, other: ReadonlyArray): boolean; +} + +declare const a: (string | number)[] | null[] | undefined[] | {}[]; +declare const b: (string | number)[] | null[] | undefined[] | {}[]; + +let x = a.equalsShallow(b); + + +//// [bivariantInferences.js] +"use strict"; +// Repro from #27337 +var x = a.equalsShallow(b); diff --git a/tests/baselines/reference/bivariantInferences.symbols b/tests/baselines/reference/bivariantInferences.symbols new file mode 100644 index 00000000000..63cc239f040 --- /dev/null +++ b/tests/baselines/reference/bivariantInferences.symbols @@ -0,0 +1,31 @@ +=== tests/cases/conformance/types/typeRelationships/typeInference/bivariantInferences.ts === +// Repro from #27337 + +interface Array { +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(bivariantInferences.ts, 0, 0)) +>T : Symbol(T, Decl(lib.es5.d.ts, --, --), Decl(bivariantInferences.ts, 2, 16)) + + equalsShallow(this: ReadonlyArray, other: ReadonlyArray): boolean; +>equalsShallow : Symbol(Array.equalsShallow, Decl(bivariantInferences.ts, 2, 20)) +>T : Symbol(T, Decl(bivariantInferences.ts, 3, 18)) +>this : Symbol(this, Decl(bivariantInferences.ts, 3, 21)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(bivariantInferences.ts, 3, 18)) +>other : Symbol(other, Decl(bivariantInferences.ts, 3, 44)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(bivariantInferences.ts, 3, 18)) +} + +declare const a: (string | number)[] | null[] | undefined[] | {}[]; +>a : Symbol(a, Decl(bivariantInferences.ts, 6, 13)) + +declare const b: (string | number)[] | null[] | undefined[] | {}[]; +>b : Symbol(b, Decl(bivariantInferences.ts, 7, 13)) + +let x = a.equalsShallow(b); +>x : Symbol(x, Decl(bivariantInferences.ts, 9, 3)) +>a.equalsShallow : Symbol(equalsShallow, Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20)) +>a : Symbol(a, Decl(bivariantInferences.ts, 6, 13)) +>equalsShallow : Symbol(equalsShallow, Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20), Decl(bivariantInferences.ts, 2, 20)) +>b : Symbol(b, Decl(bivariantInferences.ts, 7, 13)) + diff --git a/tests/baselines/reference/bivariantInferences.types b/tests/baselines/reference/bivariantInferences.types new file mode 100644 index 00000000000..e9bf31dad8e --- /dev/null +++ b/tests/baselines/reference/bivariantInferences.types @@ -0,0 +1,26 @@ +=== tests/cases/conformance/types/typeRelationships/typeInference/bivariantInferences.ts === +// Repro from #27337 + +interface Array { + equalsShallow(this: ReadonlyArray, other: ReadonlyArray): boolean; +>equalsShallow : (this: ReadonlyArray, other: ReadonlyArray) => boolean +>this : ReadonlyArray +>other : ReadonlyArray +} + +declare const a: (string | number)[] | null[] | undefined[] | {}[]; +>a : (string | number)[] | null[] | undefined[] | {}[] +>null : null + +declare const b: (string | number)[] | null[] | undefined[] | {}[]; +>b : (string | number)[] | null[] | undefined[] | {}[] +>null : null + +let x = a.equalsShallow(b); +>x : boolean +>a.equalsShallow(b) : boolean +>a.equalsShallow : ((this: ReadonlyArray, other: ReadonlyArray) => boolean) | ((this: ReadonlyArray, other: ReadonlyArray) => boolean) | ((this: ReadonlyArray, other: ReadonlyArray) => boolean) | ((this: ReadonlyArray, other: ReadonlyArray) => boolean) +>a : (string | number)[] | null[] | undefined[] | {}[] +>equalsShallow : ((this: ReadonlyArray, other: ReadonlyArray) => boolean) | ((this: ReadonlyArray, other: ReadonlyArray) => boolean) | ((this: ReadonlyArray, other: ReadonlyArray) => boolean) | ((this: ReadonlyArray, other: ReadonlyArray) => boolean) +>b : (string | number)[] | null[] | undefined[] | {}[] + diff --git a/tests/baselines/reference/blockScopedBindingUsedBeforeDef.errors.txt b/tests/baselines/reference/blockScopedBindingUsedBeforeDef.errors.txt index 042f5e6de4f..4f04f2babc5 100644 --- a/tests/baselines/reference/blockScopedBindingUsedBeforeDef.errors.txt +++ b/tests/baselines/reference/blockScopedBindingUsedBeforeDef.errors.txt @@ -1,23 +1,32 @@ tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts(2,12): error TS2448: Block-scoped variable 'a' used before its declaration. +tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts(2,12): error TS2538: Type 'any' cannot be used as an index type. tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts(5,12): error TS2448: Block-scoped variable 'a' used before its declaration. +tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts(5,12): error TS2538: Type 'any' cannot be used as an index type. tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts(8,7): error TS2448: Block-scoped variable 'b' used before its declaration. +tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts(8,7): error TS2538: Type 'any' cannot be used as an index type. -==== tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts (3 errors) ==== +==== tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts (6 errors) ==== // 1: for (let {[a]: a} of [{ }]) continue; ~ !!! error TS2448: Block-scoped variable 'a' used before its declaration. !!! related TS2728 tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts:2:16: 'a' is declared here. + ~ +!!! error TS2538: Type 'any' cannot be used as an index type. // 2: for (let {[a]: a} = { }; false; ) continue; ~ !!! error TS2448: Block-scoped variable 'a' used before its declaration. !!! related TS2728 tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts:5:16: 'a' is declared here. + ~ +!!! error TS2538: Type 'any' cannot be used as an index type. // 3: let {[b]: b} = { }; ~ !!! error TS2448: Block-scoped variable 'b' used before its declaration. -!!! related TS2728 tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts:8:11: 'b' is declared here. \ No newline at end of file +!!! related TS2728 tests/cases/compiler/blockScopedBindingUsedBeforeDef.ts:8:11: 'b' is declared here. + ~ +!!! error TS2538: Type 'any' cannot be used as an index type. \ No newline at end of file diff --git a/tests/baselines/reference/bluebirdStaticThis.errors.txt b/tests/baselines/reference/bluebirdStaticThis.errors.txt index b9e28711715..257cc1bb823 100644 --- a/tests/baselines/reference/bluebirdStaticThis.errors.txt +++ b/tests/baselines/reference/bluebirdStaticThis.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/bluebirdStaticThis.ts(5,22): error TS2420: Class 'Promise' incorrectly implements interface 'Thenable'. - Property 'then' is missing in type 'Promise'. + Property 'then' is missing in type 'Promise' but required in type 'Thenable'. tests/cases/compiler/bluebirdStaticThis.ts(22,51): error TS2694: Namespace '"tests/cases/compiler/bluebirdStaticThis".Promise' has no exported member 'Resolver'. tests/cases/compiler/bluebirdStaticThis.ts(57,109): error TS2694: Namespace '"tests/cases/compiler/bluebirdStaticThis".Promise' has no exported member 'Inspection'. tests/cases/compiler/bluebirdStaticThis.ts(58,91): error TS2694: Namespace '"tests/cases/compiler/bluebirdStaticThis".Promise' has no exported member 'Inspection'. @@ -15,7 +15,8 @@ tests/cases/compiler/bluebirdStaticThis.ts(60,73): error TS2694: Namespace '"tes export declare class Promise implements Promise.Thenable { ~~~~~~~ !!! error TS2420: Class 'Promise' incorrectly implements interface 'Thenable'. -!!! error TS2420: Property 'then' is missing in type 'Promise'. +!!! error TS2420: Property 'then' is missing in type 'Promise' but required in type 'Thenable'. +!!! related TS2728 tests/cases/compiler/bluebirdStaticThis.ts:113:3: 'then' is declared here. constructor(callback: (resolve: (thenableOrResult: R | Promise.Thenable) => void, reject: (error: any) => void) => void); static try(dit: typeof Promise, fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; static try(dit: typeof Promise, fn: () => R, args?: any[], ctx?: any): Promise; diff --git a/tests/baselines/reference/booleanLiteralTypes1.types b/tests/baselines/reference/booleanLiteralTypes1.types index 8cd0a4331a7..c50ee4ab0ad 100644 --- a/tests/baselines/reference/booleanLiteralTypes1.types +++ b/tests/baselines/reference/booleanLiteralTypes1.types @@ -82,13 +82,13 @@ function f4(t: true, f: false) { >false : false var x1 = t && f; ->x1 : boolean +>x1 : false >t && f : false >t : true >f : false var x2 = f && t; ->x2 : boolean +>x2 : false >f && t : false >f : false >t : true @@ -100,7 +100,7 @@ function f4(t: true, f: false) { >f : false var x4 = f || t; ->x4 : boolean +>x4 : true >f || t : true >f : false >t : true diff --git a/tests/baselines/reference/booleanLiteralTypes2.types b/tests/baselines/reference/booleanLiteralTypes2.types index 52e4d85e0bd..15c8f1e9c53 100644 --- a/tests/baselines/reference/booleanLiteralTypes2.types +++ b/tests/baselines/reference/booleanLiteralTypes2.types @@ -82,25 +82,25 @@ function f4(t: true, f: false) { >false : false var x1 = t && f; ->x1 : boolean +>x1 : false >t && f : false >t : true >f : false var x2 = f && t; ->x2 : boolean +>x2 : false >f && t : false >f : false >t : true var x3 = t || f; ->x3 : boolean +>x3 : true >t || f : true >t : true >f : false var x4 = f || t; ->x4 : boolean +>x4 : true >f || t : true >f : false >t : true diff --git a/tests/baselines/reference/booleanLiteralsContextuallyTypedFromUnion.errors.txt b/tests/baselines/reference/booleanLiteralsContextuallyTypedFromUnion.errors.txt new file mode 100644 index 00000000000..5b8fb9b0ea8 --- /dev/null +++ b/tests/baselines/reference/booleanLiteralsContextuallyTypedFromUnion.errors.txt @@ -0,0 +1,31 @@ +error TS2318: Cannot find global type 'CallableFunction'. +error TS2318: Cannot find global type 'NewableFunction'. + + +!!! error TS2318: Cannot find global type 'CallableFunction'. +!!! error TS2318: Cannot find global type 'NewableFunction'. +==== tests/cases/compiler/booleanLiteralsContextuallyTypedFromUnion.tsx (0 errors) ==== + interface A { isIt: true; text: string; } + interface B { isIt: false; value: number; } + type C = A | B; + const isIt = Math.random() > 0.5; + const c: C = isIt ? { isIt, text: 'hey' } : { isIt, value: 123 }; + const cc: C = isIt ? { isIt: isIt, text: 'hey' } : { isIt: isIt, value: 123 }; + + type ComponentProps = + | { + optionalBool: true; + mandatoryFn: () => void; + } + | { + optionalBool: false; + }; + + let Funk = (_props: ComponentProps) =>
Hello
; + + let Fail1 = () => { }} optionalBool={true} /> + let Fail2 = () => { }} optionalBool={true as true} /> + let True = true as true; + let Fail3 = () => { }} optionalBool={True} /> + let attrs2 = { optionalBool: true as true, mandatoryFn: () => { } } + let Success = () => \ No newline at end of file diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance2.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance2.js index fe8f9330a5f..e139bcca598 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance2.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance2.js @@ -77,7 +77,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; } diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance3.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance3.js index 27112f8d3c3..b8a024a8a09 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance3.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance3.js @@ -122,7 +122,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; } diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance4.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance4.js index 0928f8ebc29..a969d77fb03 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance4.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance4.js @@ -57,7 +57,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; } diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance5.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance5.js index 9d7dbc9eab6..cf8889cbf27 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance5.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance5.js @@ -57,7 +57,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; } diff --git a/tests/baselines/reference/callSignatureAssignabilityInInheritance6.js b/tests/baselines/reference/callSignatureAssignabilityInInheritance6.js index aa189c78f8f..baa98cb72d5 100644 --- a/tests/baselines/reference/callSignatureAssignabilityInInheritance6.js +++ b/tests/baselines/reference/callSignatureAssignabilityInInheritance6.js @@ -60,7 +60,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; } diff --git a/tests/baselines/reference/callSignatureWithoutReturnTypeAnnotationInference.types b/tests/baselines/reference/callSignatureWithoutReturnTypeAnnotationInference.types index a7ccc2cd4e0..d07126c148e 100644 --- a/tests/baselines/reference/callSignatureWithoutReturnTypeAnnotationInference.types +++ b/tests/baselines/reference/callSignatureWithoutReturnTypeAnnotationInference.types @@ -100,17 +100,17 @@ var r6 = foo6(1); >1 : 1 function foo7(x) { ->foo7 : (x: any) => "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>foo7 : (x: any) => "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any return typeof x; ->typeof x : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >x : any } var r7 = foo7(1); ->r7 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->foo7(1) : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" ->foo7 : (x: any) => "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>r7 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>foo7(1) : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>foo7 : (x: any) => "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >1 : 1 // object types diff --git a/tests/baselines/reference/callWithMissingVoid.errors.txt b/tests/baselines/reference/callWithMissingVoid.errors.txt new file mode 100644 index 00000000000..7ad2a481f2e --- /dev/null +++ b/tests/baselines/reference/callWithMissingVoid.errors.txt @@ -0,0 +1,131 @@ +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(16,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(19,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(22,1): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(35,31): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(36,35): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(37,33): error TS2554: Expected 1 arguments, but got 0. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(48,1): error TS2554: Expected 3 arguments, but got 1. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(55,1): error TS2554: Expected 4 arguments, but got 2. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(56,1): error TS2554: Expected 4 arguments, but got 3. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(57,1): error TS2554: Expected 4 arguments, but got 1. +tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts(75,1): error TS2554: Expected 3 arguments, but got 1. + + +==== tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts (11 errors) ==== + // From #4260 + class X { + f(t: T) { + return { a: t }; + } + } + + declare const x: X; + x.f() // no error because f expects void + + declare const xUnion: X; + xUnion.f(42) // no error because f accepts number + xUnion.f() // no error because f accepts void + + declare const xAny: X; + xAny.f() // error, any still expects an argument + ~~~~~~~~ +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:3:7: An argument for 't' was not provided. + + declare const xUnknown: X; + xUnknown.f() // error, unknown still expects an argument + ~~~~~~~~~~~~ +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:3:7: An argument for 't' was not provided. + + declare const xNever: X; + xNever.f() // error, never still expects an argument + ~~~~~~~~~~ +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:3:7: An argument for 't' was not provided. + + + // Promise has previously been updated to work without arguments, but to show this fixes the issue too. + + class MyPromise { + constructor(executor: (resolve: (value: X) => void) => void) { + + } + } + + new MyPromise(resolve => resolve()); // no error + new MyPromise(resolve => resolve()); // no error + new MyPromise(resolve => resolve()); // error, `any` arguments cannot be omitted + ~~~~~~~~~ +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:28:38: An argument for 'value' was not provided. + new MyPromise(resolve => resolve()); // error, `unknown` arguments cannot be omitted + ~~~~~~~~~ +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:28:38: An argument for 'value' was not provided. + new MyPromise(resolve => resolve()); // error, `never` arguments cannot be omitted + ~~~~~~~~~ +!!! error TS2554: Expected 1 arguments, but got 0. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:28:38: An argument for 'value' was not provided. + + + // Multiple parameters + + function a(x: number, y: string, z: void): void { + + } + + a(4, "hello"); // ok + a(4, "hello", void 0); // ok + a(4); // not ok + ~~~~ +!!! error TS2554: Expected 3 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:42:23: An argument for 'y' was not provided. + + function b(x: number, y: string, z: void, what: number): void { + + } + + b(4, "hello", void 0, 2); // ok + b(4, "hello"); // not ok + ~~~~~~~~~~~~~ +!!! error TS2554: Expected 4 arguments, but got 2. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:50:34: An argument for 'z' was not provided. + b(4, "hello", void 0); // not ok + ~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2554: Expected 4 arguments, but got 3. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:50:43: An argument for 'what' was not provided. + b(4); // not ok + ~~~~ +!!! error TS2554: Expected 4 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:50:23: An argument for 'y' was not provided. + + function c(x: number | void, y: void, z: void | string | number): void { + + } + + c(3, void 0, void 0); // ok + c(3, void 0); // ok + c(3); // ok + c(); // ok + + + // Spread Parameters + + declare function call( + handler: (...args: TS) => unknown, + ...args: TS): void; + + call((x: number, y: number) => x + y) // error + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +!!! error TS2554: Expected 3 arguments, but got 1. +!!! related TS6210 tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts:73:5: An argument for 'args' was not provided. + call((x: number, y: number) => x + y, 4, 2) // ok + + call((x: number, y: void) => x, 4, void 0) // ok + call((x: number, y: void) => x, 4) // ok + call((x: void, y: void) => 42) // ok + call((x: number | void, y: number | void) => 42) // ok + call((x: number | void, y: number | void) => 42, 4) // ok + call((x: number | void, y: number | void) => 42, 4, 2) // ok + \ No newline at end of file diff --git a/tests/baselines/reference/callWithMissingVoid.js b/tests/baselines/reference/callWithMissingVoid.js new file mode 100644 index 00000000000..50282931fa6 --- /dev/null +++ b/tests/baselines/reference/callWithMissingVoid.js @@ -0,0 +1,140 @@ +//// [callWithMissingVoid.ts] +// From #4260 +class X { + f(t: T) { + return { a: t }; + } +} + +declare const x: X; +x.f() // no error because f expects void + +declare const xUnion: X; +xUnion.f(42) // no error because f accepts number +xUnion.f() // no error because f accepts void + +declare const xAny: X; +xAny.f() // error, any still expects an argument + +declare const xUnknown: X; +xUnknown.f() // error, unknown still expects an argument + +declare const xNever: X; +xNever.f() // error, never still expects an argument + + +// Promise has previously been updated to work without arguments, but to show this fixes the issue too. + +class MyPromise { + constructor(executor: (resolve: (value: X) => void) => void) { + + } +} + +new MyPromise(resolve => resolve()); // no error +new MyPromise(resolve => resolve()); // no error +new MyPromise(resolve => resolve()); // error, `any` arguments cannot be omitted +new MyPromise(resolve => resolve()); // error, `unknown` arguments cannot be omitted +new MyPromise(resolve => resolve()); // error, `never` arguments cannot be omitted + + +// Multiple parameters + +function a(x: number, y: string, z: void): void { + +} + +a(4, "hello"); // ok +a(4, "hello", void 0); // ok +a(4); // not ok + +function b(x: number, y: string, z: void, what: number): void { + +} + +b(4, "hello", void 0, 2); // ok +b(4, "hello"); // not ok +b(4, "hello", void 0); // not ok +b(4); // not ok + +function c(x: number | void, y: void, z: void | string | number): void { + +} + +c(3, void 0, void 0); // ok +c(3, void 0); // ok +c(3); // ok +c(); // ok + + +// Spread Parameters + +declare function call( + handler: (...args: TS) => unknown, + ...args: TS): void; + +call((x: number, y: number) => x + y) // error +call((x: number, y: number) => x + y, 4, 2) // ok + +call((x: number, y: void) => x, 4, void 0) // ok +call((x: number, y: void) => x, 4) // ok +call((x: void, y: void) => 42) // ok +call((x: number | void, y: number | void) => 42) // ok +call((x: number | void, y: number | void) => 42, 4) // ok +call((x: number | void, y: number | void) => 42, 4, 2) // ok + + +//// [callWithMissingVoid.js] +"use strict"; +// From #4260 +var X = /** @class */ (function () { + function X() { + } + X.prototype.f = function (t) { + return { a: t }; + }; + return X; +}()); +x.f(); // no error because f expects void +xUnion.f(42); // no error because f accepts number +xUnion.f(); // no error because f accepts void +xAny.f(); // error, any still expects an argument +xUnknown.f(); // error, unknown still expects an argument +xNever.f(); // error, never still expects an argument +// Promise has previously been updated to work without arguments, but to show this fixes the issue too. +var MyPromise = /** @class */ (function () { + function MyPromise(executor) { + } + return MyPromise; +}()); +new MyPromise(function (resolve) { return resolve(); }); // no error +new MyPromise(function (resolve) { return resolve(); }); // no error +new MyPromise(function (resolve) { return resolve(); }); // error, `any` arguments cannot be omitted +new MyPromise(function (resolve) { return resolve(); }); // error, `unknown` arguments cannot be omitted +new MyPromise(function (resolve) { return resolve(); }); // error, `never` arguments cannot be omitted +// Multiple parameters +function a(x, y, z) { +} +a(4, "hello"); // ok +a(4, "hello", void 0); // ok +a(4); // not ok +function b(x, y, z, what) { +} +b(4, "hello", void 0, 2); // ok +b(4, "hello"); // not ok +b(4, "hello", void 0); // not ok +b(4); // not ok +function c(x, y, z) { +} +c(3, void 0, void 0); // ok +c(3, void 0); // ok +c(3); // ok +c(); // ok +call(function (x, y) { return x + y; }); // error +call(function (x, y) { return x + y; }, 4, 2); // ok +call(function (x, y) { return x; }, 4, void 0); // ok +call(function (x, y) { return x; }, 4); // ok +call(function (x, y) { return 42; }); // ok +call(function (x, y) { return 42; }); // ok +call(function (x, y) { return 42; }, 4); // ok +call(function (x, y) { return 42; }, 4, 2); // ok diff --git a/tests/baselines/reference/callWithMissingVoid.symbols b/tests/baselines/reference/callWithMissingVoid.symbols new file mode 100644 index 00000000000..22a198b7433 --- /dev/null +++ b/tests/baselines/reference/callWithMissingVoid.symbols @@ -0,0 +1,231 @@ +=== tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts === +// From #4260 +class X { +>X : Symbol(X, Decl(callWithMissingVoid.ts, 0, 0)) +>T : Symbol(T, Decl(callWithMissingVoid.ts, 1, 8)) + + f(t: T) { +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>t : Symbol(t, Decl(callWithMissingVoid.ts, 2, 6)) +>T : Symbol(T, Decl(callWithMissingVoid.ts, 1, 8)) + + return { a: t }; +>a : Symbol(a, Decl(callWithMissingVoid.ts, 3, 16)) +>t : Symbol(t, Decl(callWithMissingVoid.ts, 2, 6)) + } +} + +declare const x: X; +>x : Symbol(x, Decl(callWithMissingVoid.ts, 7, 13)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 0, 0)) + +x.f() // no error because f expects void +>x.f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 7, 13)) +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) + +declare const xUnion: X; +>xUnion : Symbol(xUnion, Decl(callWithMissingVoid.ts, 10, 13)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 0, 0)) + +xUnion.f(42) // no error because f accepts number +>xUnion.f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>xUnion : Symbol(xUnion, Decl(callWithMissingVoid.ts, 10, 13)) +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) + +xUnion.f() // no error because f accepts void +>xUnion.f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>xUnion : Symbol(xUnion, Decl(callWithMissingVoid.ts, 10, 13)) +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) + +declare const xAny: X; +>xAny : Symbol(xAny, Decl(callWithMissingVoid.ts, 14, 13)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 0, 0)) + +xAny.f() // error, any still expects an argument +>xAny.f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>xAny : Symbol(xAny, Decl(callWithMissingVoid.ts, 14, 13)) +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) + +declare const xUnknown: X; +>xUnknown : Symbol(xUnknown, Decl(callWithMissingVoid.ts, 17, 13)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 0, 0)) + +xUnknown.f() // error, unknown still expects an argument +>xUnknown.f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>xUnknown : Symbol(xUnknown, Decl(callWithMissingVoid.ts, 17, 13)) +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) + +declare const xNever: X; +>xNever : Symbol(xNever, Decl(callWithMissingVoid.ts, 20, 13)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 0, 0)) + +xNever.f() // error, never still expects an argument +>xNever.f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) +>xNever : Symbol(xNever, Decl(callWithMissingVoid.ts, 20, 13)) +>f : Symbol(X.f, Decl(callWithMissingVoid.ts, 1, 12)) + + +// Promise has previously been updated to work without arguments, but to show this fixes the issue too. + +class MyPromise { +>MyPromise : Symbol(MyPromise, Decl(callWithMissingVoid.ts, 21, 10)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 26, 16)) + + constructor(executor: (resolve: (value: X) => void) => void) { +>executor : Symbol(executor, Decl(callWithMissingVoid.ts, 27, 16)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 27, 27)) +>value : Symbol(value, Decl(callWithMissingVoid.ts, 27, 37)) +>X : Symbol(X, Decl(callWithMissingVoid.ts, 26, 16)) + + } +} + +new MyPromise(resolve => resolve()); // no error +>MyPromise : Symbol(MyPromise, Decl(callWithMissingVoid.ts, 21, 10)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 32, 20)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 32, 20)) + +new MyPromise(resolve => resolve()); // no error +>MyPromise : Symbol(MyPromise, Decl(callWithMissingVoid.ts, 21, 10)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 33, 29)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 33, 29)) + +new MyPromise(resolve => resolve()); // error, `any` arguments cannot be omitted +>MyPromise : Symbol(MyPromise, Decl(callWithMissingVoid.ts, 21, 10)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 34, 19)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 34, 19)) + +new MyPromise(resolve => resolve()); // error, `unknown` arguments cannot be omitted +>MyPromise : Symbol(MyPromise, Decl(callWithMissingVoid.ts, 21, 10)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 35, 23)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 35, 23)) + +new MyPromise(resolve => resolve()); // error, `never` arguments cannot be omitted +>MyPromise : Symbol(MyPromise, Decl(callWithMissingVoid.ts, 21, 10)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 36, 21)) +>resolve : Symbol(resolve, Decl(callWithMissingVoid.ts, 36, 21)) + + +// Multiple parameters + +function a(x: number, y: string, z: void): void { +>a : Symbol(a, Decl(callWithMissingVoid.ts, 36, 43)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 41, 11)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 41, 21)) +>z : Symbol(z, Decl(callWithMissingVoid.ts, 41, 32)) + +} + +a(4, "hello"); // ok +>a : Symbol(a, Decl(callWithMissingVoid.ts, 36, 43)) + +a(4, "hello", void 0); // ok +>a : Symbol(a, Decl(callWithMissingVoid.ts, 36, 43)) + +a(4); // not ok +>a : Symbol(a, Decl(callWithMissingVoid.ts, 36, 43)) + +function b(x: number, y: string, z: void, what: number): void { +>b : Symbol(b, Decl(callWithMissingVoid.ts, 47, 5)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 49, 11)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 49, 21)) +>z : Symbol(z, Decl(callWithMissingVoid.ts, 49, 32)) +>what : Symbol(what, Decl(callWithMissingVoid.ts, 49, 41)) + +} + +b(4, "hello", void 0, 2); // ok +>b : Symbol(b, Decl(callWithMissingVoid.ts, 47, 5)) + +b(4, "hello"); // not ok +>b : Symbol(b, Decl(callWithMissingVoid.ts, 47, 5)) + +b(4, "hello", void 0); // not ok +>b : Symbol(b, Decl(callWithMissingVoid.ts, 47, 5)) + +b(4); // not ok +>b : Symbol(b, Decl(callWithMissingVoid.ts, 47, 5)) + +function c(x: number | void, y: void, z: void | string | number): void { +>c : Symbol(c, Decl(callWithMissingVoid.ts, 56, 5)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 58, 11)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 58, 28)) +>z : Symbol(z, Decl(callWithMissingVoid.ts, 58, 37)) + +} + +c(3, void 0, void 0); // ok +>c : Symbol(c, Decl(callWithMissingVoid.ts, 56, 5)) + +c(3, void 0); // ok +>c : Symbol(c, Decl(callWithMissingVoid.ts, 56, 5)) + +c(3); // ok +>c : Symbol(c, Decl(callWithMissingVoid.ts, 56, 5)) + +c(); // ok +>c : Symbol(c, Decl(callWithMissingVoid.ts, 56, 5)) + + +// Spread Parameters + +declare function call( +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>TS : Symbol(TS, Decl(callWithMissingVoid.ts, 70, 22)) + + handler: (...args: TS) => unknown, +>handler : Symbol(handler, Decl(callWithMissingVoid.ts, 70, 44)) +>args : Symbol(args, Decl(callWithMissingVoid.ts, 71, 14)) +>TS : Symbol(TS, Decl(callWithMissingVoid.ts, 70, 22)) + + ...args: TS): void; +>args : Symbol(args, Decl(callWithMissingVoid.ts, 71, 38)) +>TS : Symbol(TS, Decl(callWithMissingVoid.ts, 70, 22)) + +call((x: number, y: number) => x + y) // error +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 74, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 74, 16)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 74, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 74, 16)) + +call((x: number, y: number) => x + y, 4, 2) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 75, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 75, 16)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 75, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 75, 16)) + +call((x: number, y: void) => x, 4, void 0) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 77, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 77, 16)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 77, 6)) + +call((x: number, y: void) => x, 4) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 78, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 78, 16)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 78, 6)) + +call((x: void, y: void) => 42) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 79, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 79, 14)) + +call((x: number | void, y: number | void) => 42) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 80, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 80, 23)) + +call((x: number | void, y: number | void) => 42, 4) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 81, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 81, 23)) + +call((x: number | void, y: number | void) => 42, 4, 2) // ok +>call : Symbol(call, Decl(callWithMissingVoid.ts, 65, 4)) +>x : Symbol(x, Decl(callWithMissingVoid.ts, 82, 6)) +>y : Symbol(y, Decl(callWithMissingVoid.ts, 82, 23)) + diff --git a/tests/baselines/reference/callWithMissingVoid.types b/tests/baselines/reference/callWithMissingVoid.types new file mode 100644 index 00000000000..4fbcbbf5d1b --- /dev/null +++ b/tests/baselines/reference/callWithMissingVoid.types @@ -0,0 +1,312 @@ +=== tests/cases/conformance/expressions/functionCalls/callWithMissingVoid.ts === +// From #4260 +class X { +>X : X + + f(t: T) { +>f : (t: T) => { a: T; } +>t : T + + return { a: t }; +>{ a: t } : { a: T; } +>a : T +>t : T + } +} + +declare const x: X; +>x : X + +x.f() // no error because f expects void +>x.f() : { a: void; } +>x.f : (t: void) => { a: void; } +>x : X +>f : (t: void) => { a: void; } + +declare const xUnion: X; +>xUnion : X + +xUnion.f(42) // no error because f accepts number +>xUnion.f(42) : { a: number | void; } +>xUnion.f : (t: number | void) => { a: number | void; } +>xUnion : X +>f : (t: number | void) => { a: number | void; } +>42 : 42 + +xUnion.f() // no error because f accepts void +>xUnion.f() : { a: number | void; } +>xUnion.f : (t: number | void) => { a: number | void; } +>xUnion : X +>f : (t: number | void) => { a: number | void; } + +declare const xAny: X; +>xAny : X + +xAny.f() // error, any still expects an argument +>xAny.f() : { a: any; } +>xAny.f : (t: any) => { a: any; } +>xAny : X +>f : (t: any) => { a: any; } + +declare const xUnknown: X; +>xUnknown : X + +xUnknown.f() // error, unknown still expects an argument +>xUnknown.f() : { a: unknown; } +>xUnknown.f : (t: unknown) => { a: unknown; } +>xUnknown : X +>f : (t: unknown) => { a: unknown; } + +declare const xNever: X; +>xNever : X + +xNever.f() // error, never still expects an argument +>xNever.f() : { a: never; } +>xNever.f : (t: never) => { a: never; } +>xNever : X +>f : (t: never) => { a: never; } + + +// Promise has previously been updated to work without arguments, but to show this fixes the issue too. + +class MyPromise { +>MyPromise : MyPromise + + constructor(executor: (resolve: (value: X) => void) => void) { +>executor : (resolve: (value: X) => void) => void +>resolve : (value: X) => void +>value : X + + } +} + +new MyPromise(resolve => resolve()); // no error +>new MyPromise(resolve => resolve()) : MyPromise +>MyPromise : typeof MyPromise +>resolve => resolve() : (resolve: (value: void) => void) => void +>resolve : (value: void) => void +>resolve() : void +>resolve : (value: void) => void + +new MyPromise(resolve => resolve()); // no error +>new MyPromise(resolve => resolve()) : MyPromise +>MyPromise : typeof MyPromise +>resolve => resolve() : (resolve: (value: number | void) => void) => void +>resolve : (value: number | void) => void +>resolve() : void +>resolve : (value: number | void) => void + +new MyPromise(resolve => resolve()); // error, `any` arguments cannot be omitted +>new MyPromise(resolve => resolve()) : MyPromise +>MyPromise : typeof MyPromise +>resolve => resolve() : (resolve: (value: any) => void) => any +>resolve : (value: any) => void +>resolve() : void +>resolve : (value: any) => void + +new MyPromise(resolve => resolve()); // error, `unknown` arguments cannot be omitted +>new MyPromise(resolve => resolve()) : MyPromise +>MyPromise : typeof MyPromise +>resolve => resolve() : (resolve: (value: unknown) => void) => any +>resolve : (value: unknown) => void +>resolve() : void +>resolve : (value: unknown) => void + +new MyPromise(resolve => resolve()); // error, `never` arguments cannot be omitted +>new MyPromise(resolve => resolve()) : MyPromise +>MyPromise : typeof MyPromise +>resolve => resolve() : (resolve: (value: never) => void) => any +>resolve : (value: never) => void +>resolve() : void +>resolve : (value: never) => void + + +// Multiple parameters + +function a(x: number, y: string, z: void): void { +>a : (x: number, y: string, z: void) => void +>x : number +>y : string +>z : void + +} + +a(4, "hello"); // ok +>a(4, "hello") : void +>a : (x: number, y: string, z: void) => void +>4 : 4 +>"hello" : "hello" + +a(4, "hello", void 0); // ok +>a(4, "hello", void 0) : void +>a : (x: number, y: string, z: void) => void +>4 : 4 +>"hello" : "hello" +>void 0 : undefined +>0 : 0 + +a(4); // not ok +>a(4) : void +>a : (x: number, y: string, z: void) => void +>4 : 4 + +function b(x: number, y: string, z: void, what: number): void { +>b : (x: number, y: string, z: void, what: number) => void +>x : number +>y : string +>z : void +>what : number + +} + +b(4, "hello", void 0, 2); // ok +>b(4, "hello", void 0, 2) : void +>b : (x: number, y: string, z: void, what: number) => void +>4 : 4 +>"hello" : "hello" +>void 0 : undefined +>0 : 0 +>2 : 2 + +b(4, "hello"); // not ok +>b(4, "hello") : void +>b : (x: number, y: string, z: void, what: number) => void +>4 : 4 +>"hello" : "hello" + +b(4, "hello", void 0); // not ok +>b(4, "hello", void 0) : void +>b : (x: number, y: string, z: void, what: number) => void +>4 : 4 +>"hello" : "hello" +>void 0 : undefined +>0 : 0 + +b(4); // not ok +>b(4) : void +>b : (x: number, y: string, z: void, what: number) => void +>4 : 4 + +function c(x: number | void, y: void, z: void | string | number): void { +>c : (x: number | void, y: void, z: string | number | void) => void +>x : number | void +>y : void +>z : string | number | void + +} + +c(3, void 0, void 0); // ok +>c(3, void 0, void 0) : void +>c : (x: number | void, y: void, z: string | number | void) => void +>3 : 3 +>void 0 : undefined +>0 : 0 +>void 0 : undefined +>0 : 0 + +c(3, void 0); // ok +>c(3, void 0) : void +>c : (x: number | void, y: void, z: string | number | void) => void +>3 : 3 +>void 0 : undefined +>0 : 0 + +c(3); // ok +>c(3) : void +>c : (x: number | void, y: void, z: string | number | void) => void +>3 : 3 + +c(); // ok +>c() : void +>c : (x: number | void, y: void, z: string | number | void) => void + + +// Spread Parameters + +declare function call( +>call : (handler: (...args: TS) => unknown, ...args: TS) => void + + handler: (...args: TS) => unknown, +>handler : (...args: TS) => unknown +>args : TS + + ...args: TS): void; +>args : TS + +call((x: number, y: number) => x + y) // error +>call((x: number, y: number) => x + y) : any +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number, y: number) => x + y : (x: number, y: number) => number +>x : number +>y : number +>x + y : number +>x : number +>y : number + +call((x: number, y: number) => x + y, 4, 2) // ok +>call((x: number, y: number) => x + y, 4, 2) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number, y: number) => x + y : (x: number, y: number) => number +>x : number +>y : number +>x + y : number +>x : number +>y : number +>4 : 4 +>2 : 2 + +call((x: number, y: void) => x, 4, void 0) // ok +>call((x: number, y: void) => x, 4, void 0) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number, y: void) => x : (x: number, y: void) => number +>x : number +>y : void +>x : number +>4 : 4 +>void 0 : undefined +>0 : 0 + +call((x: number, y: void) => x, 4) // ok +>call((x: number, y: void) => x, 4) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number, y: void) => x : (x: number, y: void) => number +>x : number +>y : void +>x : number +>4 : 4 + +call((x: void, y: void) => 42) // ok +>call((x: void, y: void) => 42) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: void, y: void) => 42 : (x: void, y: void) => number +>x : void +>y : void +>42 : 42 + +call((x: number | void, y: number | void) => 42) // ok +>call((x: number | void, y: number | void) => 42) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number | void, y: number | void) => 42 : (x: number | void, y: number | void) => number +>x : number | void +>y : number | void +>42 : 42 + +call((x: number | void, y: number | void) => 42, 4) // ok +>call((x: number | void, y: number | void) => 42, 4) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number | void, y: number | void) => 42 : (x: number | void, y: number | void) => number +>x : number | void +>y : number | void +>42 : 42 +>4 : 4 + +call((x: number | void, y: number | void) => 42, 4, 2) // ok +>call((x: number | void, y: number | void) => 42, 4, 2) : void +>call : (handler: (...args: TS) => unknown, ...args: TS) => void +>(x: number | void, y: number | void) => 42 : (x: number | void, y: number | void) => number +>x : number | void +>y : number | void +>42 : 42 +>4 : 4 +>2 : 2 + diff --git a/tests/baselines/reference/callWithSpread.js b/tests/baselines/reference/callWithSpread.js index 423721645ad..f8f1959d2bb 100644 --- a/tests/baselines/reference/callWithSpread.js +++ b/tests/baselines/reference/callWithSpread.js @@ -65,7 +65,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; } diff --git a/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.js b/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.js index 2b8eb4e62aa..dd433fc1db7 100644 --- a/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.js +++ b/tests/baselines/reference/captureSuperPropertyAccessInSuperCall01.js @@ -18,7 +18,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; } diff --git a/tests/baselines/reference/captureThisInSuperCall.js b/tests/baselines/reference/captureThisInSuperCall.js index 9406feca945..919f8491114 100644 --- a/tests/baselines/reference/captureThisInSuperCall.js +++ b/tests/baselines/reference/captureThisInSuperCall.js @@ -15,7 +15,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; } diff --git a/tests/baselines/reference/capturedLetConstInLoop1.js b/tests/baselines/reference/capturedLetConstInLoop1.js index 3c064059cb0..7acaf851cc2 100644 --- a/tests/baselines/reference/capturedLetConstInLoop1.js +++ b/tests/baselines/reference/capturedLetConstInLoop1.js @@ -1,4 +1,6 @@ //// [capturedLetConstInLoop1.ts] +declare function use(x: any): any; + //==== let for (let x in {}) { (function() { return x}); @@ -56,6 +58,19 @@ for (let y = 0; y < 1; ++y) { (() => x + y); } +for (let y = (use(() => y), 0); y < 1; ++y) { +} + +for (let y = 0; use(() => y), y < 1; ++y) { +} + +for (let y = 0; y < 1; use(() => y), ++y) { +} + +for (let y = (use(() => y), 0); use(() => y), y < 1; use(() => y), ++y) { + use(() => y); +} + //=========const for (const x in {}) { (function() { return x}); @@ -202,93 +217,145 @@ var _loop_10 = function (y) { for (var y = 0; y < 1; ++y) { _loop_10(y); } -var _loop_11 = function (x) { +var _loop_init_1 = function () { + var y = (use(function () { return y; }), 0); + out_y_1 = y; +}; +var out_y_1; +_loop_init_1(); +for (var y = out_y_1; y < 1; ++y) { +} +var _loop_11 = function (y) { + if (inc_1) + ++y; + else + inc_1 = true; + if (!(use(function () { return y; }), y < 1)) + return "break"; +}; +var inc_1 = false; +for (var y = 0;;) { + var state_1 = _loop_11(y); + if (state_1 === "break") + break; +} +var _loop_12 = function (y) { + if (inc_2) + use(function () { return y; }), ++y; + else + inc_2 = true; +}; +var inc_2 = false; +for (var y = 0; y < 1;) { + _loop_12(y); +} +var _loop_init_2 = function () { + var y = (use(function () { return y; }), 0); + out_y_2 = y; +}; +var _loop_13 = function (y) { + if (inc_3) + use(function () { return y; }), ++y; + else + inc_3 = true; + if (!(use(function () { return y; }), y < 1)) + return out_y_2 = y, "break"; + use(function () { return y; }); +}; +var out_y_2, inc_3 = false; +_loop_init_2(); +for (var y = out_y_2;;) { + var state_2 = _loop_13(y); + if (state_2 === "break") + break; +} +var _loop_14 = function (x) { (function () { return x; }); (function () { return x; }); }; //=========const for (var x in {}) { - _loop_11(x); + _loop_14(x); } -var _loop_12 = function (x) { +var _loop_15 = function (x) { (function () { return x; }); (function () { return x; }); }; for (var _b = 0, _c = []; _b < _c.length; _b++) { var x = _c[_b]; - _loop_12(x); + _loop_15(x); } -var _loop_13 = function (x) { +var _loop_16 = function (x) { (function () { return x; }); (function () { return x; }); }; for (var x = 0; x < 1;) { - _loop_13(x); + _loop_16(x); } -var _loop_14 = function () { +var _loop_17 = function () { var x = 1; (function () { return x; }); (function () { return x; }); }; while (1 === 1) { - _loop_14(); + _loop_17(); } -var _loop_15 = function () { +var _loop_18 = function () { var x = 1; (function () { return x; }); (function () { return x; }); }; do { - _loop_15(); + _loop_18(); } while (1 === 1); -var _loop_16 = function (y) { +var _loop_19 = function (y) { var x = 1; (function () { return x; }); (function () { return x; }); }; for (var y = 0; y < 1;) { - _loop_16(y); + _loop_19(y); } -var _loop_17 = function (x, y) { +var _loop_20 = function (x, y) { (function () { return x + y; }); (function () { return x + y; }); }; for (var x = 0, y = 1; x < 1;) { - _loop_17(x, y); + _loop_20(x, y); } -var _loop_18 = function () { +var _loop_21 = function () { var x = 1, y = 1; (function () { return x + y; }); (function () { return x + y; }); }; while (1 === 1) { - _loop_18(); + _loop_21(); } -var _loop_19 = function () { +var _loop_22 = function () { var x = 1, y = 1; (function () { return x + y; }); (function () { return x + y; }); }; do { - _loop_19(); + _loop_22(); } while (1 === 1); -var _loop_20 = function (y) { +var _loop_23 = function (y) { var x = 1; (function () { return x + y; }); (function () { return x + y; }); }; for (var y = 0; y < 1;) { - _loop_20(y); + _loop_23(y); } -var _loop_21 = function (sx) { +var _loop_24 = function (sx) { (function () { return sobj[sx]; }); }; for (var sx in sobj) { - _loop_21(sx); + _loop_24(sx); } -var _loop_22 = function (ix) { +var _loop_25 = function (ix) { (function () { return iobj[ix]; }); }; for (var ix in iobj) { - _loop_22(ix); + _loop_25(ix); } diff --git a/tests/baselines/reference/capturedLetConstInLoop1.symbols b/tests/baselines/reference/capturedLetConstInLoop1.symbols index afa7898a258..43f263bd73a 100644 --- a/tests/baselines/reference/capturedLetConstInLoop1.symbols +++ b/tests/baselines/reference/capturedLetConstInLoop1.symbols @@ -1,286 +1,330 @@ === tests/cases/compiler/capturedLetConstInLoop1.ts === +declare function use(x: any): any; +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 0, 21)) + //==== let for (let x in {}) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 1, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 3, 8)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 1, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 3, 8)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 1, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 3, 8)) } for (let x of []) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 6, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 8, 8)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 6, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 8, 8)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 6, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 8, 8)) } for (let x = 0; x < 1; ++x) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 11, 8)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 11, 8)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 11, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 13, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 13, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 13, 8)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 11, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 13, 8)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 11, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 13, 8)) } while (1 === 1) { let x; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 17, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 19, 7)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 17, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 19, 7)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 17, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 19, 7)) } do { let x; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 23, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 25, 7)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 23, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 25, 7)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 23, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 25, 7)) } while (1 === 1) for (let y = 0; y < 1; ++y) { ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 28, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 28, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 28, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 30, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 30, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 30, 8)) let x = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 29, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 31, 7)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 29, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 31, 7)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 29, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 31, 7)) } for (let x = 0, y = 1; x < 1; ++x) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 34, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 34, 15)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 34, 8)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 34, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 36, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 36, 15)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 36, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 36, 8)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 34, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 34, 15)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 36, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 36, 15)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 34, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 34, 15)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 36, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 36, 15)) } while (1 === 1) { let x, y; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 40, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 40, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 42, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 42, 10)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 40, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 40, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 42, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 42, 10)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 40, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 40, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 42, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 42, 10)) } do { let x, y; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 46, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 46, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 48, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 48, 10)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 46, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 46, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 48, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 48, 10)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 46, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 46, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 48, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 48, 10)) } while (1 === 1) for (let y = 0; y < 1; ++y) { ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 51, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 51, 8)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 51, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 53, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 53, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 53, 8)) let x = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 52, 7)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 54, 7)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 52, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 51, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 54, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 53, 8)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 52, 7)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 51, 8)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 54, 7)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 53, 8)) +} + +for (let y = (use(() => y), 0); y < 1; ++y) { +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 59, 8)) +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 59, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 59, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 59, 8)) +} + +for (let y = 0; use(() => y), y < 1; ++y) { +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 62, 8)) +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 62, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 62, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 62, 8)) +} + +for (let y = 0; y < 1; use(() => y), ++y) { +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 65, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 65, 8)) +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 65, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 65, 8)) +} + +for (let y = (use(() => y), 0); use(() => y), y < 1; use(() => y), ++y) { +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) + + use(() => y); +>use : Symbol(use, Decl(capturedLetConstInLoop1.ts, 0, 0)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 68, 8)) } //=========const for (const x in {}) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 58, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 73, 10)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 58, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 73, 10)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 58, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 73, 10)) } for (const x of []) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 63, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 78, 10)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 63, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 78, 10)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 63, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 78, 10)) } for (const x = 0; x < 1;) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 68, 10)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 68, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 83, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 83, 10)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 68, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 83, 10)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 68, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 83, 10)) } while (1 === 1) { const x = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 74, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 89, 9)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 74, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 89, 9)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 74, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 89, 9)) } do { const x = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 80, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 95, 9)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 80, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 95, 9)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 80, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 95, 9)) } while (1 === 1) for (const y = 0; y < 1;) { ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 85, 10)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 85, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 100, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 100, 10)) const x = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 86, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 101, 9)) (function() { return x}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 86, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 101, 9)) (() => x); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 86, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 101, 9)) } for (const x = 0, y = 1; x < 1;) { ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 91, 10)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 91, 17)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 91, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 106, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 106, 17)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 106, 10)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 91, 10)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 91, 17)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 106, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 106, 17)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 91, 10)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 91, 17)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 106, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 106, 17)) } while (1 === 1) { const x = 1, y = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 97, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 97, 16)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 112, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 112, 16)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 97, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 97, 16)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 112, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 112, 16)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 97, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 97, 16)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 112, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 112, 16)) } do { const x = 1, y = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 103, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 103, 16)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 118, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 118, 16)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 103, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 103, 16)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 118, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 118, 16)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 103, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 103, 16)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 118, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 118, 16)) } while (1 === 1) for (const y = 0; y < 1;) { ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 108, 10)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 108, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 123, 10)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 123, 10)) const x = 1; ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 109, 9)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 124, 9)) (function() { return x + y}); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 109, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 108, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 124, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 123, 10)) (() => x + y); ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 109, 9)) ->y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 108, 10)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 124, 9)) +>y : Symbol(y, Decl(capturedLetConstInLoop1.ts, 123, 10)) } // https://github.com/Microsoft/TypeScript/issues/20594 declare const sobj: { [x: string]: any }; ->sobj : Symbol(sobj, Decl(capturedLetConstInLoop1.ts, 115, 13)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 115, 23)) +>sobj : Symbol(sobj, Decl(capturedLetConstInLoop1.ts, 130, 13)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 130, 23)) for (let sx in sobj) { ->sx : Symbol(sx, Decl(capturedLetConstInLoop1.ts, 116, 8)) ->sobj : Symbol(sobj, Decl(capturedLetConstInLoop1.ts, 115, 13)) +>sx : Symbol(sx, Decl(capturedLetConstInLoop1.ts, 131, 8)) +>sobj : Symbol(sobj, Decl(capturedLetConstInLoop1.ts, 130, 13)) (() => sobj[sx]); ->sobj : Symbol(sobj, Decl(capturedLetConstInLoop1.ts, 115, 13)) ->sx : Symbol(sx, Decl(capturedLetConstInLoop1.ts, 116, 8)) +>sobj : Symbol(sobj, Decl(capturedLetConstInLoop1.ts, 130, 13)) +>sx : Symbol(sx, Decl(capturedLetConstInLoop1.ts, 131, 8)) } declare const iobj: { [x: number]: any }; ->iobj : Symbol(iobj, Decl(capturedLetConstInLoop1.ts, 119, 13)) ->x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 119, 23)) +>iobj : Symbol(iobj, Decl(capturedLetConstInLoop1.ts, 134, 13)) +>x : Symbol(x, Decl(capturedLetConstInLoop1.ts, 134, 23)) for (let ix in iobj) { ->ix : Symbol(ix, Decl(capturedLetConstInLoop1.ts, 120, 8)) ->iobj : Symbol(iobj, Decl(capturedLetConstInLoop1.ts, 119, 13)) +>ix : Symbol(ix, Decl(capturedLetConstInLoop1.ts, 135, 8)) +>iobj : Symbol(iobj, Decl(capturedLetConstInLoop1.ts, 134, 13)) (() => iobj[ix]); ->iobj : Symbol(iobj, Decl(capturedLetConstInLoop1.ts, 119, 13)) ->ix : Symbol(ix, Decl(capturedLetConstInLoop1.ts, 120, 8)) +>iobj : Symbol(iobj, Decl(capturedLetConstInLoop1.ts, 134, 13)) +>ix : Symbol(ix, Decl(capturedLetConstInLoop1.ts, 135, 8)) } diff --git a/tests/baselines/reference/capturedLetConstInLoop1.types b/tests/baselines/reference/capturedLetConstInLoop1.types index 34ba101752b..a7d3094268c 100644 --- a/tests/baselines/reference/capturedLetConstInLoop1.types +++ b/tests/baselines/reference/capturedLetConstInLoop1.types @@ -1,4 +1,8 @@ === tests/cases/compiler/capturedLetConstInLoop1.ts === +declare function use(x: any): any; +>use : (x: any) => any +>x : any + //==== let for (let x in {}) { >x : string @@ -214,6 +218,84 @@ for (let y = 0; y < 1; ++y) { >y : number } +for (let y = (use(() => y), 0); y < 1; ++y) { +>y : number +>(use(() => y), 0) : 0 +>use(() => y), 0 : 0 +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +>0 : 0 +>y < 1 : boolean +>y : number +>1 : 1 +>++y : number +>y : number +} + +for (let y = 0; use(() => y), y < 1; ++y) { +>y : number +>0 : 0 +>use(() => y), y < 1 : boolean +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +>y < 1 : boolean +>y : number +>1 : 1 +>++y : number +>y : number +} + +for (let y = 0; y < 1; use(() => y), ++y) { +>y : number +>0 : 0 +>y < 1 : boolean +>y : number +>1 : 1 +>use(() => y), ++y : number +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +>++y : number +>y : number +} + +for (let y = (use(() => y), 0); use(() => y), y < 1; use(() => y), ++y) { +>y : number +>(use(() => y), 0) : 0 +>use(() => y), 0 : 0 +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +>0 : 0 +>use(() => y), y < 1 : boolean +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +>y < 1 : boolean +>y : number +>1 : 1 +>use(() => y), ++y : number +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +>++y : number +>y : number + + use(() => y); +>use(() => y) : any +>use : (x: any) => any +>() => y : () => number +>y : number +} + //=========const for (const x in {}) { >x : string diff --git a/tests/baselines/reference/castExpressionParentheses.types b/tests/baselines/reference/castExpressionParentheses.types index 5f6e5b2122b..db38aad5a47 100644 --- a/tests/baselines/reference/castExpressionParentheses.types +++ b/tests/baselines/reference/castExpressionParentheses.types @@ -182,7 +182,7 @@ declare var A; >(typeof A).x : any >(typeof A) : any >typeof A : any ->typeof A : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof A : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >A : any >x : any diff --git a/tests/baselines/reference/castOfAwait.types b/tests/baselines/reference/castOfAwait.types index afe075b67d9..34934b89128 100644 --- a/tests/baselines/reference/castOfAwait.types +++ b/tests/baselines/reference/castOfAwait.types @@ -8,7 +8,7 @@ async function f() { >0 : 0 typeof await 0; ->typeof await 0 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof await 0 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >await 0 : 0 >0 : 0 @@ -21,7 +21,7 @@ async function f() { >await void typeof void await 0 : undefined >void typeof void await 0 : undefined > typeof void await 0 : string ->typeof void await 0 : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof void await 0 : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" > void await 0 : number >void await 0 : undefined >await 0 : 0 diff --git a/tests/baselines/reference/castingTuple.errors.txt b/tests/baselines/reference/castingTuple.errors.txt index e8bc9133a8a..4587612cb76 100644 --- a/tests/baselines/reference/castingTuple.errors.txt +++ b/tests/baselines/reference/castingTuple.errors.txt @@ -1,17 +1,16 @@ tests/cases/conformance/types/tuple/castingTuple.ts(13,23): error TS2352: Conversion of type '[number, string]' to type '[number, string, boolean]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. - Property '2' is missing in type '[number, string]'. + Property '2' is missing in type '[number, string]' but required in type '[number, string, boolean]'. tests/cases/conformance/types/tuple/castingTuple.ts(14,15): error TS2352: Conversion of type '[number, string, boolean]' to type '[number, string]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Types of property 'length' are incompatible. Type '3' is not comparable to type '2'. tests/cases/conformance/types/tuple/castingTuple.ts(15,14): error TS2352: Conversion of type '[number, string]' to type '[number, string, boolean]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. tests/cases/conformance/types/tuple/castingTuple.ts(18,21): error TS2352: Conversion of type '[C, D]' to type '[C, D, A]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. - Property '2' is missing in type '[C, D]'. -tests/cases/conformance/types/tuple/castingTuple.ts(20,33): error TS2733: Index '5' is out-of-bounds in tuple of length 3. + Property '2' is missing in type '[C, D]' but required in type '[C, D, A]'. +tests/cases/conformance/types/tuple/castingTuple.ts(20,33): error TS2339: Property '5' does not exist on type '[C, D, A]'. tests/cases/conformance/types/tuple/castingTuple.ts(30,10): error TS2352: Conversion of type '[number, string]' to type '[number, number]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type 'string' is not comparable to type 'number'. tests/cases/conformance/types/tuple/castingTuple.ts(31,10): error TS2352: Conversion of type '[C, D]' to type '[A, I]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. - Type 'C' is not comparable to type 'A'. - Property 'a' is missing in type 'C'. + Property 'a' is missing in type 'C' but required in type 'A'. tests/cases/conformance/types/tuple/castingTuple.ts(32,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'array1' must be of type '{}[]', but here has type 'number[]'. tests/cases/conformance/types/tuple/castingTuple.ts(33,1): error TS2304: Cannot find name 't4'. @@ -32,7 +31,7 @@ tests/cases/conformance/types/tuple/castingTuple.ts(33,1): error TS2304: Cannot var numStrBoolTuple = <[number, string, boolean]>numStrTuple; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2352: Conversion of type '[number, string]' to type '[number, string, boolean]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. -!!! error TS2352: Property '2' is missing in type '[number, string]'. +!!! error TS2352: Property '2' is missing in type '[number, string]' but required in type '[number, string, boolean]'. var shorter = numStrBoolTuple as [number, string] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2352: Conversion of type '[number, string, boolean]' to type '[number, string]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. @@ -46,11 +45,11 @@ tests/cases/conformance/types/tuple/castingTuple.ts(33,1): error TS2304: Cannot var classCDATuple = <[C, D, A]>classCDTuple; ~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2352: Conversion of type '[C, D]' to type '[C, D, A]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. -!!! error TS2352: Property '2' is missing in type '[C, D]'. +!!! error TS2352: Property '2' is missing in type '[C, D]' but required in type '[C, D, A]'. var eleFromCDA1 = classCDATuple[2]; // A var eleFromCDA2 = classCDATuple[5]; // C | D | A ~ -!!! error TS2733: Index '5' is out-of-bounds in tuple of length 3. +!!! error TS2339: Property '5' does not exist on type '[C, D, A]'. var t10: [E1, E2] = [E1.one, E2.one]; var t11 = <[number, number]>t10; var array1 = <{}[]>emptyObjTuple; @@ -67,8 +66,8 @@ tests/cases/conformance/types/tuple/castingTuple.ts(33,1): error TS2304: Cannot var t9 = <[A, I]>classCDTuple; ~~~~~~~~~~~~~~~~~~~~ !!! error TS2352: Conversion of type '[C, D]' to type '[A, I]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. -!!! error TS2352: Type 'C' is not comparable to type 'A'. -!!! error TS2352: Property 'a' is missing in type 'C'. +!!! error TS2352: Property 'a' is missing in type 'C' but required in type 'A'. +!!! related TS2728 tests/cases/conformance/types/tuple/castingTuple.ts:2:11: 'a' is declared here. var array1 = numStrTuple; ~~~~~~ !!! error TS2403: Subsequent variable declarations must have the same type. Variable 'array1' must be of type '{}[]', but here has type 'number[]'. diff --git a/tests/baselines/reference/castingTuple.js b/tests/baselines/reference/castingTuple.js index 4bb4f5f788b..ac21b229a3c 100644 --- a/tests/baselines/reference/castingTuple.js +++ b/tests/baselines/reference/castingTuple.js @@ -41,7 +41,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; } diff --git a/tests/baselines/reference/castingTuple.types b/tests/baselines/reference/castingTuple.types index 729c090e1ca..0c20dadc2be 100644 --- a/tests/baselines/reference/castingTuple.types +++ b/tests/baselines/reference/castingTuple.types @@ -83,8 +83,8 @@ var eleFromCDA1 = classCDATuple[2]; // A >2 : 2 var eleFromCDA2 = classCDATuple[5]; // C | D | A ->eleFromCDA2 : A | C | D ->classCDATuple[5] : A | C | D +>eleFromCDA2 : undefined +>classCDATuple[5] : undefined >classCDATuple : [C, D, A] >5 : 5 diff --git a/tests/baselines/reference/chainedAssignment1.errors.txt b/tests/baselines/reference/chainedAssignment1.errors.txt index 3fa654c62cc..32ae0f63dc7 100644 --- a/tests/baselines/reference/chainedAssignment1.errors.txt +++ b/tests/baselines/reference/chainedAssignment1.errors.txt @@ -1,7 +1,5 @@ -tests/cases/compiler/chainedAssignment1.ts(21,1): error TS2322: Type 'Z' is not assignable to type 'X'. - Property 'a' is missing in type 'Z'. -tests/cases/compiler/chainedAssignment1.ts(21,6): error TS2322: Type 'Z' is not assignable to type 'Y'. - Property 'a' is missing in type 'Z'. +tests/cases/compiler/chainedAssignment1.ts(21,1): error TS2741: Property 'a' is missing in type 'Z' but required in type 'X'. +tests/cases/compiler/chainedAssignment1.ts(21,6): error TS2739: Type 'Z' is missing the following properties from type 'Y': a, b tests/cases/compiler/chainedAssignment1.ts(22,1): error TS2322: Type 'Z' is not assignable to type 'Y'. @@ -28,11 +26,10 @@ tests/cases/compiler/chainedAssignment1.ts(22,1): error TS2322: Type 'Z' is not var c3 = new Z(); c1 = c2 = c3; // a bug made this not report the same error as below ~~ -!!! error TS2322: Type 'Z' is not assignable to type 'X'. -!!! error TS2322: Property 'a' is missing in type 'Z'. +!!! error TS2741: Property 'a' is missing in type 'Z' but required in type 'X'. +!!! related TS2728 tests/cases/compiler/chainedAssignment1.ts:3:5: 'a' is declared here. ~~ -!!! error TS2322: Type 'Z' is not assignable to type 'Y'. -!!! error TS2322: Property 'a' is missing in type 'Z'. +!!! error TS2739: Type 'Z' is missing the following properties from type 'Y': a, b c2 = c3; // Error TS111: Cannot convert Z to Y ~~ !!! error TS2322: Type 'Z' is not assignable to type 'Y'. \ No newline at end of file diff --git a/tests/baselines/reference/chainedAssignment3.errors.txt b/tests/baselines/reference/chainedAssignment3.errors.txt index 8a64a35cbc0..16f6b2fe652 100644 --- a/tests/baselines/reference/chainedAssignment3.errors.txt +++ b/tests/baselines/reference/chainedAssignment3.errors.txt @@ -1,5 +1,4 @@ -tests/cases/compiler/chainedAssignment3.ts(18,1): error TS2322: Type 'A' is not assignable to type 'B'. - Property 'value' is missing in type 'A'. +tests/cases/compiler/chainedAssignment3.ts(18,1): error TS2741: Property 'value' is missing in type 'A' but required in type 'B'. tests/cases/compiler/chainedAssignment3.ts(19,5): error TS2322: Type 'A' is not assignable to type 'B'. @@ -23,8 +22,8 @@ tests/cases/compiler/chainedAssignment3.ts(19,5): error TS2322: Type 'A' is not // error cases b = a = new A(); ~ -!!! error TS2322: Type 'A' is not assignable to type 'B'. -!!! error TS2322: Property 'value' is missing in type 'A'. +!!! error TS2741: Property 'value' is missing in type 'A' but required in type 'B'. +!!! related TS2728 tests/cases/compiler/chainedAssignment3.ts:6:5: 'value' is declared here. a = b = new A(); ~ !!! error TS2322: Type 'A' is not assignable to type 'B'. diff --git a/tests/baselines/reference/chainedAssignment3.js b/tests/baselines/reference/chainedAssignment3.js index acb96e5b9cf..c3e73310188 100644 --- a/tests/baselines/reference/chainedAssignment3.js +++ b/tests/baselines/reference/chainedAssignment3.js @@ -29,7 +29,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; } diff --git a/tests/baselines/reference/chainedAssignmentChecking.errors.txt b/tests/baselines/reference/chainedAssignmentChecking.errors.txt index ac3bade0aae..567a599b63e 100644 --- a/tests/baselines/reference/chainedAssignmentChecking.errors.txt +++ b/tests/baselines/reference/chainedAssignmentChecking.errors.txt @@ -1,7 +1,5 @@ -tests/cases/compiler/chainedAssignmentChecking.ts(21,1): error TS2322: Type 'Z' is not assignable to type 'X'. - Property 'a' is missing in type 'Z'. -tests/cases/compiler/chainedAssignmentChecking.ts(21,6): error TS2322: Type 'Z' is not assignable to type 'Y'. - Property 'a' is missing in type 'Z'. +tests/cases/compiler/chainedAssignmentChecking.ts(21,1): error TS2741: Property 'a' is missing in type 'Z' but required in type 'X'. +tests/cases/compiler/chainedAssignmentChecking.ts(21,6): error TS2739: Type 'Z' is missing the following properties from type 'Y': a, b ==== tests/cases/compiler/chainedAssignmentChecking.ts (2 errors) ==== @@ -27,9 +25,8 @@ tests/cases/compiler/chainedAssignmentChecking.ts(21,6): error TS2322: Type 'Z' c1 = c2 = c3; // Should be error ~~ -!!! error TS2322: Type 'Z' is not assignable to type 'X'. -!!! error TS2322: Property 'a' is missing in type 'Z'. +!!! error TS2741: Property 'a' is missing in type 'Z' but required in type 'X'. +!!! related TS2728 tests/cases/compiler/chainedAssignmentChecking.ts:3:3: 'a' is declared here. ~~ -!!! error TS2322: Type 'Z' is not assignable to type 'Y'. -!!! error TS2322: Property 'a' is missing in type 'Z'. +!!! error TS2739: Type 'Z' is missing the following properties from type 'Y': a, b \ No newline at end of file diff --git a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.errors.txt b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.errors.txt index 181bfcc907d..2e39f19d86a 100644 --- a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.errors.txt +++ b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.errors.txt @@ -1,6 +1,4 @@ -tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.ts(19,59): error TS2345: Argument of type '(c: C) => B' is not assignable to parameter of type '(x: C) => C'. - Type 'B' is not assignable to type 'C'. - Property 'z' is missing in type 'B'. +tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.ts(19,64): error TS2741: Property 'z' is missing in type 'B' but required in type 'C'. ==== tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.ts (1 errors) ==== @@ -23,7 +21,7 @@ tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParamete // Ok to go down the chain, but error to try to climb back up (new Chain(new A)).then(a => new B).then(b => new C).then(c => new B).then(b => new A); - ~~~~~~~~~~ -!!! error TS2345: Argument of type '(c: C) => B' is not assignable to parameter of type '(x: C) => C'. -!!! error TS2345: Type 'B' is not assignable to type 'C'. -!!! error TS2345: Property 'z' is missing in type 'B'. \ No newline at end of file + ~~~~~ +!!! error TS2741: Property 'z' is missing in type 'B' but required in type 'C'. +!!! related TS2728 tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.ts:15:5: 'z' is declared here. +!!! related TS6502 tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.ts:3:27: The expected type comes from the return type of this signature. \ No newline at end of file diff --git a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.js b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.js index 8b272b582a4..69ecf8cd52d 100644 --- a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.js +++ b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter.js @@ -26,7 +26,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; } diff --git a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.errors.txt b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.errors.txt index 56f4cad5a47..6f03e711886 100644 --- a/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.errors.txt +++ b/tests/baselines/reference/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.errors.txt @@ -1,7 +1,5 @@ -tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(7,43): error TS2345: Argument of type '(ss: S) => T' is not assignable to parameter of type '(x: S) => S'. - Type 'T' is not assignable to type 'S'. -tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(10,29): error TS2345: Argument of type '(ss: S) => T' is not assignable to parameter of type '(x: S) => S'. - Type 'T' is not assignable to type 'S'. +tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(7,49): error TS2322: Type 'T' is not assignable to type 'S'. +tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(10,35): error TS2322: Type 'T' is not assignable to type 'S'. tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(32,9): error TS2322: Type '""' is not assignable to type 'number'. tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(36,9): error TS2322: Type '""' is not assignable to type 'number'. tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts(37,9): error TS2322: Type '""' is not assignable to type 'number'. @@ -15,15 +13,15 @@ tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParamete var s: S; // Ok to go down the chain, but error to climb up the chain (new Chain(t)).then(tt => s).then(ss => t); - ~~~~~~~ -!!! error TS2345: Argument of type '(ss: S) => T' is not assignable to parameter of type '(x: S) => S'. -!!! error TS2345: Type 'T' is not assignable to type 'S'. + ~ +!!! error TS2322: Type 'T' is not assignable to type 'S'. +!!! related TS6502 tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts:3:27: The expected type comes from the return type of this signature. // But error to try to climb up the chain (new Chain(s)).then(ss => t); - ~~~~~~~ -!!! error TS2345: Argument of type '(ss: S) => T' is not assignable to parameter of type '(x: S) => S'. -!!! error TS2345: Type 'T' is not assignable to type 'S'. + ~ +!!! error TS2322: Type 'T' is not assignable to type 'S'. +!!! related TS6502 tests/cases/compiler/chainedCallsWithTypeParameterConstrainedToOtherTypeParameter2.ts:3:27: The expected type comes from the return type of this signature. // Staying at T or S should be fine (new Chain(t)).then(tt => t).then(tt => t).then(tt => t); diff --git a/tests/baselines/reference/checkExportsObjectAssignProperty.errors.txt b/tests/baselines/reference/checkExportsObjectAssignProperty.errors.txt new file mode 100644 index 00000000000..cce3d89a761 --- /dev/null +++ b/tests/baselines/reference/checkExportsObjectAssignProperty.errors.txt @@ -0,0 +1,110 @@ +tests/cases/conformance/jsdoc/validator.ts(17,4): error TS2540: Cannot assign to 'readonlyProp' because it is a read-only property. +tests/cases/conformance/jsdoc/validator.ts(18,4): error TS2540: Cannot assign to 'readonlyAccessor' because it is a read-only property. +tests/cases/conformance/jsdoc/validator.ts(19,1): error TS2322: Type '"no"' is not assignable to type 'number'. +tests/cases/conformance/jsdoc/validator.ts(20,1): error TS2322: Type '"no"' is not assignable to type 'number'. +tests/cases/conformance/jsdoc/validator.ts(21,1): error TS2322: Type '0' is not assignable to type 'string'. +tests/cases/conformance/jsdoc/validator.ts(37,4): error TS2540: Cannot assign to 'readonlyProp' because it is a read-only property. +tests/cases/conformance/jsdoc/validator.ts(38,4): error TS2540: Cannot assign to 'readonlyAccessor' because it is a read-only property. +tests/cases/conformance/jsdoc/validator.ts(39,1): error TS2322: Type '0' is not assignable to type 'string'. +tests/cases/conformance/jsdoc/validator.ts(40,1): error TS2322: Type '"no"' is not assignable to type 'number'. +tests/cases/conformance/jsdoc/validator.ts(41,1): error TS2322: Type '0' is not assignable to type 'string'. + + +==== tests/cases/conformance/jsdoc/validator.ts (10 errors) ==== + import "./"; + + import m1 = require("./mod1"); + + m1.thing; + m1.readonlyProp; + m1.rwAccessors; + m1.readonlyAccessor; + m1.setonlyAccessor; + + // allowed assignments + m1.thing = 10; + m1.rwAccessors = 11; + m1.setonlyAccessor = "yes"; + + // disallowed assignments + m1.readonlyProp = "name"; + ~~~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'readonlyProp' because it is a read-only property. + m1.readonlyAccessor = 12; + ~~~~~~~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'readonlyAccessor' because it is a read-only property. + m1.thing = "no"; + ~~~~~~~~ +!!! error TS2322: Type '"no"' is not assignable to type 'number'. + m1.rwAccessors = "no"; + ~~~~~~~~~~~~~~ +!!! error TS2322: Type '"no"' is not assignable to type 'number'. + m1.setonlyAccessor = 0; + ~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '0' is not assignable to type 'string'. + + import m2 = require("./mod2"); + + m2.thing; + m2.readonlyProp; + m2.rwAccessors; + m2.readonlyAccessor; + m2.setonlyAccessor; + + // allowed assignments + m2.thing = "ok"; + m2.rwAccessors = 11; + m2.setonlyAccessor = "yes"; + + // disallowed assignments + m2.readonlyProp = "name"; + ~~~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'readonlyProp' because it is a read-only property. + m2.readonlyAccessor = 12; + ~~~~~~~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'readonlyAccessor' because it is a read-only property. + m2.thing = 0; + ~~~~~~~~ +!!! error TS2322: Type '0' is not assignable to type 'string'. + m2.rwAccessors = "no"; + ~~~~~~~~~~~~~~ +!!! error TS2322: Type '"no"' is not assignable to type 'number'. + m2.setonlyAccessor = 0; + ~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '0' is not assignable to type 'string'. + +==== tests/cases/conformance/jsdoc/mod1.js (0 errors) ==== + Object.defineProperty(exports, "thing", { value: 42, writable: true }); + Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false }); + Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); + Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }); + Object.defineProperty(exports, "setonlyAccessor", { + /** @param {string} str */ + set(str) { + this.rwAccessors = Number(str) + } + }); + +==== tests/cases/conformance/jsdoc/mod2.js (0 errors) ==== + Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }); + Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable: false }); + Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); + Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 } }); + Object.defineProperty(module.exports, "setonlyAccessor", { + /** @param {string} str */ + set(str) { + this.rwAccessors = Number(str) + } + }); + +==== tests/cases/conformance/jsdoc/index.js (0 errors) ==== + /** + * @type {number} + */ + const q = require("./mod1").thing; + + /** + * @type {string} + */ + const u = require("./mod2").thing; + \ No newline at end of file diff --git a/tests/baselines/reference/checkExportsObjectAssignProperty.symbols b/tests/baselines/reference/checkExportsObjectAssignProperty.symbols new file mode 100644 index 00000000000..e1dcacbfe2c --- /dev/null +++ b/tests/baselines/reference/checkExportsObjectAssignProperty.symbols @@ -0,0 +1,286 @@ +=== tests/cases/conformance/jsdoc/validator.ts === +import "./"; + +import m1 = require("./mod1"); +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) + +m1.thing; +>m1.thing : Symbol(m1.thing, Decl(mod1.js, 0, 0)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>thing : Symbol(m1.thing, Decl(mod1.js, 0, 0)) + +m1.readonlyProp; +>m1.readonlyProp : Symbol(m1.readonlyProp, Decl(mod1.js, 0, 71)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>readonlyProp : Symbol(m1.readonlyProp, Decl(mod1.js, 0, 71)) + +m1.rwAccessors; +>m1.rwAccessors : Symbol(m1.rwAccessors, Decl(mod1.js, 1, 84)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>rwAccessors : Symbol(m1.rwAccessors, Decl(mod1.js, 1, 84)) + +m1.readonlyAccessor; +>m1.readonlyAccessor : Symbol(m1.readonlyAccessor, Decl(mod1.js, 2, 97)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>readonlyAccessor : Symbol(m1.readonlyAccessor, Decl(mod1.js, 2, 97)) + +m1.setonlyAccessor; +>m1.setonlyAccessor : Symbol(m1.setonlyAccessor, Decl(mod1.js, 3, 79)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>setonlyAccessor : Symbol(m1.setonlyAccessor, Decl(mod1.js, 3, 79)) + +// allowed assignments +m1.thing = 10; +>m1.thing : Symbol(m1.thing, Decl(mod1.js, 0, 0)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>thing : Symbol(m1.thing, Decl(mod1.js, 0, 0)) + +m1.rwAccessors = 11; +>m1.rwAccessors : Symbol(m1.rwAccessors, Decl(mod1.js, 1, 84)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>rwAccessors : Symbol(m1.rwAccessors, Decl(mod1.js, 1, 84)) + +m1.setonlyAccessor = "yes"; +>m1.setonlyAccessor : Symbol(m1.setonlyAccessor, Decl(mod1.js, 3, 79)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>setonlyAccessor : Symbol(m1.setonlyAccessor, Decl(mod1.js, 3, 79)) + +// disallowed assignments +m1.readonlyProp = "name"; +>m1.readonlyProp : Symbol(m1.readonlyProp, Decl(mod1.js, 0, 71)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>readonlyProp : Symbol(m1.readonlyProp, Decl(mod1.js, 0, 71)) + +m1.readonlyAccessor = 12; +>m1.readonlyAccessor : Symbol(m1.readonlyAccessor, Decl(mod1.js, 2, 97)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>readonlyAccessor : Symbol(m1.readonlyAccessor, Decl(mod1.js, 2, 97)) + +m1.thing = "no"; +>m1.thing : Symbol(m1.thing, Decl(mod1.js, 0, 0)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>thing : Symbol(m1.thing, Decl(mod1.js, 0, 0)) + +m1.rwAccessors = "no"; +>m1.rwAccessors : Symbol(m1.rwAccessors, Decl(mod1.js, 1, 84)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>rwAccessors : Symbol(m1.rwAccessors, Decl(mod1.js, 1, 84)) + +m1.setonlyAccessor = 0; +>m1.setonlyAccessor : Symbol(m1.setonlyAccessor, Decl(mod1.js, 3, 79)) +>m1 : Symbol(m1, Decl(validator.ts, 0, 12)) +>setonlyAccessor : Symbol(m1.setonlyAccessor, Decl(mod1.js, 3, 79)) + +import m2 = require("./mod2"); +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) + +m2.thing; +>m2.thing : Symbol(m2.thing, Decl(mod2.js, 0, 0)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>thing : Symbol(m2.thing, Decl(mod2.js, 0, 0)) + +m2.readonlyProp; +>m2.readonlyProp : Symbol(m2.readonlyProp, Decl(mod2.js, 0, 81)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>readonlyProp : Symbol(m2.readonlyProp, Decl(mod2.js, 0, 81)) + +m2.rwAccessors; +>m2.rwAccessors : Symbol(m2.rwAccessors, Decl(mod2.js, 1, 91)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>rwAccessors : Symbol(m2.rwAccessors, Decl(mod2.js, 1, 91)) + +m2.readonlyAccessor; +>m2.readonlyAccessor : Symbol(m2.readonlyAccessor, Decl(mod2.js, 2, 104)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>readonlyAccessor : Symbol(m2.readonlyAccessor, Decl(mod2.js, 2, 104)) + +m2.setonlyAccessor; +>m2.setonlyAccessor : Symbol(m2.setonlyAccessor, Decl(mod2.js, 3, 86)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>setonlyAccessor : Symbol(m2.setonlyAccessor, Decl(mod2.js, 3, 86)) + +// allowed assignments +m2.thing = "ok"; +>m2.thing : Symbol(m2.thing, Decl(mod2.js, 0, 0)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>thing : Symbol(m2.thing, Decl(mod2.js, 0, 0)) + +m2.rwAccessors = 11; +>m2.rwAccessors : Symbol(m2.rwAccessors, Decl(mod2.js, 1, 91)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>rwAccessors : Symbol(m2.rwAccessors, Decl(mod2.js, 1, 91)) + +m2.setonlyAccessor = "yes"; +>m2.setonlyAccessor : Symbol(m2.setonlyAccessor, Decl(mod2.js, 3, 86)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>setonlyAccessor : Symbol(m2.setonlyAccessor, Decl(mod2.js, 3, 86)) + +// disallowed assignments +m2.readonlyProp = "name"; +>m2.readonlyProp : Symbol(m2.readonlyProp, Decl(mod2.js, 0, 81)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>readonlyProp : Symbol(m2.readonlyProp, Decl(mod2.js, 0, 81)) + +m2.readonlyAccessor = 12; +>m2.readonlyAccessor : Symbol(m2.readonlyAccessor, Decl(mod2.js, 2, 104)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>readonlyAccessor : Symbol(m2.readonlyAccessor, Decl(mod2.js, 2, 104)) + +m2.thing = 0; +>m2.thing : Symbol(m2.thing, Decl(mod2.js, 0, 0)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>thing : Symbol(m2.thing, Decl(mod2.js, 0, 0)) + +m2.rwAccessors = "no"; +>m2.rwAccessors : Symbol(m2.rwAccessors, Decl(mod2.js, 1, 91)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>rwAccessors : Symbol(m2.rwAccessors, Decl(mod2.js, 1, 91)) + +m2.setonlyAccessor = 0; +>m2.setonlyAccessor : Symbol(m2.setonlyAccessor, Decl(mod2.js, 3, 86)) +>m2 : Symbol(m2, Decl(validator.ts, 20, 23)) +>setonlyAccessor : Symbol(m2.setonlyAccessor, Decl(mod2.js, 3, 86)) + +=== tests/cases/conformance/jsdoc/mod1.js === +Object.defineProperty(exports, "thing", { value: 42, writable: true }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"thing" : Symbol(thing, Decl(mod1.js, 0, 0)) +>value : Symbol(value, Decl(mod1.js, 0, 41)) +>writable : Symbol(writable, Decl(mod1.js, 0, 52)) + +Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"readonlyProp" : Symbol(readonlyProp, Decl(mod1.js, 0, 71)) +>value : Symbol(value, Decl(mod1.js, 1, 48)) +>writable : Symbol(writable, Decl(mod1.js, 1, 64)) + +Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"rwAccessors" : Symbol(rwAccessors, Decl(mod1.js, 1, 84)) +>get : Symbol(get, Decl(mod1.js, 2, 47)) +>set : Symbol(set, Decl(mod1.js, 2, 71)) +>_ : Symbol(_, Decl(mod1.js, 2, 76)) + +Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"readonlyAccessor" : Symbol(readonlyAccessor, Decl(mod1.js, 2, 97)) +>get : Symbol(get, Decl(mod1.js, 3, 52)) + +Object.defineProperty(exports, "setonlyAccessor", { +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>"setonlyAccessor" : Symbol(setonlyAccessor, Decl(mod1.js, 3, 79)) + + /** @param {string} str */ + set(str) { +>set : Symbol(set, Decl(mod1.js, 4, 51)) +>str : Symbol(str, Decl(mod1.js, 6, 8)) + + this.rwAccessors = Number(str) +>rwAccessors : Symbol(rwAccessors, Decl(mod1.js, 6, 14)) +>Number : Symbol(Number, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>str : Symbol(str, Decl(mod1.js, 6, 8)) + } +}); + +=== tests/cases/conformance/jsdoc/mod2.js === +Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>module : Symbol(module, Decl(mod2.js, 0, 22)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>"thing" : Symbol(thing, Decl(mod2.js, 0, 0)) +>value : Symbol(value, Decl(mod2.js, 0, 48)) +>writable : Symbol(writable, Decl(mod2.js, 0, 62)) + +Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable: false }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>module : Symbol(module, Decl(mod2.js, 0, 22)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>"readonlyProp" : Symbol(readonlyProp, Decl(mod2.js, 0, 81)) +>value : Symbol(value, Decl(mod2.js, 1, 55)) +>writable : Symbol(writable, Decl(mod2.js, 1, 71)) + +Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>module : Symbol(module, Decl(mod2.js, 0, 22)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>"rwAccessors" : Symbol(rwAccessors, Decl(mod2.js, 1, 91)) +>get : Symbol(get, Decl(mod2.js, 2, 54)) +>set : Symbol(set, Decl(mod2.js, 2, 78)) +>_ : Symbol(_, Decl(mod2.js, 2, 83)) + +Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>module : Symbol(module, Decl(mod2.js, 0, 22)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>"readonlyAccessor" : Symbol(readonlyAccessor, Decl(mod2.js, 2, 104)) +>get : Symbol(get, Decl(mod2.js, 3, 59)) + +Object.defineProperty(module.exports, "setonlyAccessor", { +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>module.exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>module : Symbol(module, Decl(mod2.js, 0, 22)) +>exports : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>"setonlyAccessor" : Symbol(setonlyAccessor, Decl(mod2.js, 3, 86)) + + /** @param {string} str */ + set(str) { +>set : Symbol(set, Decl(mod2.js, 4, 58)) +>str : Symbol(str, Decl(mod2.js, 6, 8)) + + this.rwAccessors = Number(str) +>rwAccessors : Symbol(rwAccessors, Decl(mod2.js, 6, 14)) +>Number : Symbol(Number, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>str : Symbol(str, Decl(mod2.js, 6, 8)) + } +}); + +=== tests/cases/conformance/jsdoc/index.js === +/** + * @type {number} + */ +const q = require("./mod1").thing; +>q : Symbol(q, Decl(index.js, 3, 5)) +>require("./mod1").thing : Symbol(thing, Decl(mod1.js, 0, 0)) +>require : Symbol(require) +>"./mod1" : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>thing : Symbol(thing, Decl(mod1.js, 0, 0)) + +/** + * @type {string} + */ +const u = require("./mod2").thing; +>u : Symbol(u, Decl(index.js, 8, 5)) +>require("./mod2").thing : Symbol(thing, Decl(mod2.js, 0, 0)) +>require : Symbol(require) +>"./mod2" : Symbol("tests/cases/conformance/jsdoc/mod2", Decl(mod2.js, 0, 0)) +>thing : Symbol(thing, Decl(mod2.js, 0, 0)) + diff --git a/tests/baselines/reference/checkExportsObjectAssignProperty.types b/tests/baselines/reference/checkExportsObjectAssignProperty.types new file mode 100644 index 00000000000..847ac720d75 --- /dev/null +++ b/tests/baselines/reference/checkExportsObjectAssignProperty.types @@ -0,0 +1,360 @@ +=== tests/cases/conformance/jsdoc/validator.ts === +import "./"; + +import m1 = require("./mod1"); +>m1 : typeof m1 + +m1.thing; +>m1.thing : number +>m1 : typeof m1 +>thing : number + +m1.readonlyProp; +>m1.readonlyProp : string +>m1 : typeof m1 +>readonlyProp : string + +m1.rwAccessors; +>m1.rwAccessors : number +>m1 : typeof m1 +>rwAccessors : number + +m1.readonlyAccessor; +>m1.readonlyAccessor : number +>m1 : typeof m1 +>readonlyAccessor : number + +m1.setonlyAccessor; +>m1.setonlyAccessor : string +>m1 : typeof m1 +>setonlyAccessor : string + +// allowed assignments +m1.thing = 10; +>m1.thing = 10 : 10 +>m1.thing : number +>m1 : typeof m1 +>thing : number +>10 : 10 + +m1.rwAccessors = 11; +>m1.rwAccessors = 11 : 11 +>m1.rwAccessors : number +>m1 : typeof m1 +>rwAccessors : number +>11 : 11 + +m1.setonlyAccessor = "yes"; +>m1.setonlyAccessor = "yes" : "yes" +>m1.setonlyAccessor : string +>m1 : typeof m1 +>setonlyAccessor : string +>"yes" : "yes" + +// disallowed assignments +m1.readonlyProp = "name"; +>m1.readonlyProp = "name" : "name" +>m1.readonlyProp : any +>m1 : typeof m1 +>readonlyProp : any +>"name" : "name" + +m1.readonlyAccessor = 12; +>m1.readonlyAccessor = 12 : 12 +>m1.readonlyAccessor : any +>m1 : typeof m1 +>readonlyAccessor : any +>12 : 12 + +m1.thing = "no"; +>m1.thing = "no" : "no" +>m1.thing : number +>m1 : typeof m1 +>thing : number +>"no" : "no" + +m1.rwAccessors = "no"; +>m1.rwAccessors = "no" : "no" +>m1.rwAccessors : number +>m1 : typeof m1 +>rwAccessors : number +>"no" : "no" + +m1.setonlyAccessor = 0; +>m1.setonlyAccessor = 0 : 0 +>m1.setonlyAccessor : string +>m1 : typeof m1 +>setonlyAccessor : string +>0 : 0 + +import m2 = require("./mod2"); +>m2 : typeof m2 + +m2.thing; +>m2.thing : string +>m2 : typeof m2 +>thing : string + +m2.readonlyProp; +>m2.readonlyProp : string +>m2 : typeof m2 +>readonlyProp : string + +m2.rwAccessors; +>m2.rwAccessors : number +>m2 : typeof m2 +>rwAccessors : number + +m2.readonlyAccessor; +>m2.readonlyAccessor : number +>m2 : typeof m2 +>readonlyAccessor : number + +m2.setonlyAccessor; +>m2.setonlyAccessor : string +>m2 : typeof m2 +>setonlyAccessor : string + +// allowed assignments +m2.thing = "ok"; +>m2.thing = "ok" : "ok" +>m2.thing : string +>m2 : typeof m2 +>thing : string +>"ok" : "ok" + +m2.rwAccessors = 11; +>m2.rwAccessors = 11 : 11 +>m2.rwAccessors : number +>m2 : typeof m2 +>rwAccessors : number +>11 : 11 + +m2.setonlyAccessor = "yes"; +>m2.setonlyAccessor = "yes" : "yes" +>m2.setonlyAccessor : string +>m2 : typeof m2 +>setonlyAccessor : string +>"yes" : "yes" + +// disallowed assignments +m2.readonlyProp = "name"; +>m2.readonlyProp = "name" : "name" +>m2.readonlyProp : any +>m2 : typeof m2 +>readonlyProp : any +>"name" : "name" + +m2.readonlyAccessor = 12; +>m2.readonlyAccessor = 12 : 12 +>m2.readonlyAccessor : any +>m2 : typeof m2 +>readonlyAccessor : any +>12 : 12 + +m2.thing = 0; +>m2.thing = 0 : 0 +>m2.thing : string +>m2 : typeof m2 +>thing : string +>0 : 0 + +m2.rwAccessors = "no"; +>m2.rwAccessors = "no" : "no" +>m2.rwAccessors : number +>m2 : typeof m2 +>rwAccessors : number +>"no" : "no" + +m2.setonlyAccessor = 0; +>m2.setonlyAccessor = 0 : 0 +>m2.setonlyAccessor : string +>m2 : typeof m2 +>setonlyAccessor : string +>0 : 0 + +=== tests/cases/conformance/jsdoc/mod1.js === +Object.defineProperty(exports, "thing", { value: 42, writable: true }); +>Object.defineProperty(exports, "thing", { value: 42, writable: true }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"thing" : "thing" +>{ value: 42, writable: true } : { value: number; writable: true; } +>value : number +>42 : 42 +>writable : true +>true : true + +Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false }); +>Object.defineProperty(exports, "readonlyProp", { value: "Smith", writable: false }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"readonlyProp" : "readonlyProp" +>{ value: "Smith", writable: false } : { value: string; writable: false; } +>value : string +>"Smith" : "Smith" +>writable : false +>false : false + +Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty(exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"rwAccessors" : "rwAccessors" +>{ get() { return 98122 }, set(_) { /*ignore*/ } } : { get(): number; set(_: any): void; } +>get : () => number +>98122 : 98122 +>set : (_: any) => void +>_ : any + +Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }); +>Object.defineProperty(exports, "readonlyAccessor", { get() { return 21.75 } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"readonlyAccessor" : "readonlyAccessor" +>{ get() { return 21.75 } } : { get(): number; } +>get : () => number +>21.75 : 21.75 + +Object.defineProperty(exports, "setonlyAccessor", { +>Object.defineProperty(exports, "setonlyAccessor", { /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }}) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>exports : typeof import("tests/cases/conformance/jsdoc/mod1") +>"setonlyAccessor" : "setonlyAccessor" +>{ /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }} : { set(str: string): void; } + + /** @param {string} str */ + set(str) { +>set : (str: string) => void +>str : string + + this.rwAccessors = Number(str) +>this.rwAccessors = Number(str) : number +>this.rwAccessors : any +>this : any +>rwAccessors : any +>Number(str) : number +>Number : NumberConstructor +>str : string + } +}); + +=== tests/cases/conformance/jsdoc/mod2.js === +Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }); +>Object.defineProperty(module.exports, "thing", { value: "yes", writable: true }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>module.exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>module : { "tests/cases/conformance/jsdoc/mod2": typeof import("tests/cases/conformance/jsdoc/mod2"); } +>exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>"thing" : "thing" +>{ value: "yes", writable: true } : { value: string; writable: true; } +>value : string +>"yes" : "yes" +>writable : true +>true : true + +Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable: false }); +>Object.defineProperty(module.exports, "readonlyProp", { value: "Smith", writable: false }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>module.exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>module : { "tests/cases/conformance/jsdoc/mod2": typeof import("tests/cases/conformance/jsdoc/mod2"); } +>exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>"readonlyProp" : "readonlyProp" +>{ value: "Smith", writable: false } : { value: string; writable: false; } +>value : string +>"Smith" : "Smith" +>writable : false +>false : false + +Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty(module.exports, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>module.exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>module : { "tests/cases/conformance/jsdoc/mod2": typeof import("tests/cases/conformance/jsdoc/mod2"); } +>exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>"rwAccessors" : "rwAccessors" +>{ get() { return 98122 }, set(_) { /*ignore*/ } } : { get(): number; set(_: any): void; } +>get : () => number +>98122 : 98122 +>set : (_: any) => void +>_ : any + +Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 } }); +>Object.defineProperty(module.exports, "readonlyAccessor", { get() { return 21.75 } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>module.exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>module : { "tests/cases/conformance/jsdoc/mod2": typeof import("tests/cases/conformance/jsdoc/mod2"); } +>exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>"readonlyAccessor" : "readonlyAccessor" +>{ get() { return 21.75 } } : { get(): number; } +>get : () => number +>21.75 : 21.75 + +Object.defineProperty(module.exports, "setonlyAccessor", { +>Object.defineProperty(module.exports, "setonlyAccessor", { /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }}) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>module.exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>module : { "tests/cases/conformance/jsdoc/mod2": typeof import("tests/cases/conformance/jsdoc/mod2"); } +>exports : typeof import("tests/cases/conformance/jsdoc/mod2") +>"setonlyAccessor" : "setonlyAccessor" +>{ /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }} : { set(str: string): void; } + + /** @param {string} str */ + set(str) { +>set : (str: string) => void +>str : string + + this.rwAccessors = Number(str) +>this.rwAccessors = Number(str) : number +>this.rwAccessors : any +>this : any +>rwAccessors : any +>Number(str) : number +>Number : NumberConstructor +>str : string + } +}); + +=== tests/cases/conformance/jsdoc/index.js === +/** + * @type {number} + */ +const q = require("./mod1").thing; +>q : number +>require("./mod1").thing : number +>require("./mod1") : typeof import("tests/cases/conformance/jsdoc/mod1") +>require : any +>"./mod1" : "./mod1" +>thing : number + +/** + * @type {string} + */ +const u = require("./mod2").thing; +>u : string +>require("./mod2").thing : string +>require("./mod2") : typeof import("tests/cases/conformance/jsdoc/mod2") +>require : any +>"./mod2" : "./mod2" +>thing : string + diff --git a/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.errors.txt b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.errors.txt new file mode 100644 index 00000000000..4d9ced85253 --- /dev/null +++ b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.errors.txt @@ -0,0 +1,66 @@ +tests/cases/conformance/jsdoc/validator.ts(19,4): error TS2540: Cannot assign to 'readonlyProp' because it is a read-only property. +tests/cases/conformance/jsdoc/validator.ts(20,4): error TS2540: Cannot assign to 'readonlyAccessor' because it is a read-only property. +tests/cases/conformance/jsdoc/validator.ts(21,1): error TS2322: Type '"no"' is not assignable to type 'number'. +tests/cases/conformance/jsdoc/validator.ts(22,1): error TS2322: Type '"no"' is not assignable to type 'number'. +tests/cases/conformance/jsdoc/validator.ts(23,1): error TS2322: Type '0' is not assignable to type 'string'. + + +==== tests/cases/conformance/jsdoc/validator.ts (5 errors) ==== + import "./"; + + import Person = require("./mod1"); + + const m1 = new Person("Name") + + m1.thing; + m1.readonlyProp; + m1.rwAccessors; + m1.readonlyAccessor; + m1.setonlyAccessor; + + // allowed assignments + m1.thing = 10; + m1.rwAccessors = 11; + m1.setonlyAccessor = "yes"; + + // disallowed assignments + m1.readonlyProp = "name"; + ~~~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'readonlyProp' because it is a read-only property. + m1.readonlyAccessor = 12; + ~~~~~~~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'readonlyAccessor' because it is a read-only property. + m1.thing = "no"; + ~~~~~~~~ +!!! error TS2322: Type '"no"' is not assignable to type 'number'. + m1.rwAccessors = "no"; + ~~~~~~~~~~~~~~ +!!! error TS2322: Type '"no"' is not assignable to type 'number'. + m1.setonlyAccessor = 0; + ~~~~~~~~~~~~~~~~~~ +!!! error TS2322: Type '0' is not assignable to type 'string'. + + +==== tests/cases/conformance/jsdoc/mod1.js (0 errors) ==== + /** + * @constructor + * @param {string} name + */ + function Person(name) { + this.name = name; + } + Person.prototype.describe = function () { + return "Person called " + this.name; + }; + Object.defineProperty(Person.prototype, "thing", { value: 42, writable: true }); + Object.defineProperty(Person.prototype, "readonlyProp", { value: "Smith", writable: false }); + Object.defineProperty(Person.prototype, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); + Object.defineProperty(Person.prototype, "readonlyAccessor", { get() { return 21.75 } }); + Object.defineProperty(Person.prototype, "setonlyAccessor", { + /** @param {string} str */ + set(str) { + this.rwAccessors = Number(str) + } + }); + module.exports = Person; + \ No newline at end of file diff --git a/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.symbols b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.symbols new file mode 100644 index 00000000000..051a342a2b5 --- /dev/null +++ b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.symbols @@ -0,0 +1,177 @@ +=== tests/cases/conformance/jsdoc/validator.ts === +import "./"; + +import Person = require("./mod1"); +>Person : Symbol(Person, Decl(validator.ts, 0, 12)) + +const m1 = new Person("Name") +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>Person : Symbol(Person, Decl(validator.ts, 0, 12)) + +m1.thing; +>m1.thing : Symbol(Person.thing, Decl(mod1.js, 9, 2)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>thing : Symbol(Person.thing, Decl(mod1.js, 9, 2)) + +m1.readonlyProp; +>m1.readonlyProp : Symbol(Person.readonlyProp, Decl(mod1.js, 10, 80)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>readonlyProp : Symbol(Person.readonlyProp, Decl(mod1.js, 10, 80)) + +m1.rwAccessors; +>m1.rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) + +m1.readonlyAccessor; +>m1.readonlyAccessor : Symbol(Person.readonlyAccessor, Decl(mod1.js, 12, 106)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>readonlyAccessor : Symbol(Person.readonlyAccessor, Decl(mod1.js, 12, 106)) + +m1.setonlyAccessor; +>m1.setonlyAccessor : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>setonlyAccessor : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) + +// allowed assignments +m1.thing = 10; +>m1.thing : Symbol(Person.thing, Decl(mod1.js, 9, 2)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>thing : Symbol(Person.thing, Decl(mod1.js, 9, 2)) + +m1.rwAccessors = 11; +>m1.rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) + +m1.setonlyAccessor = "yes"; +>m1.setonlyAccessor : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>setonlyAccessor : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) + +// disallowed assignments +m1.readonlyProp = "name"; +>m1.readonlyProp : Symbol(Person.readonlyProp, Decl(mod1.js, 10, 80)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>readonlyProp : Symbol(Person.readonlyProp, Decl(mod1.js, 10, 80)) + +m1.readonlyAccessor = 12; +>m1.readonlyAccessor : Symbol(Person.readonlyAccessor, Decl(mod1.js, 12, 106)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>readonlyAccessor : Symbol(Person.readonlyAccessor, Decl(mod1.js, 12, 106)) + +m1.thing = "no"; +>m1.thing : Symbol(Person.thing, Decl(mod1.js, 9, 2)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>thing : Symbol(Person.thing, Decl(mod1.js, 9, 2)) + +m1.rwAccessors = "no"; +>m1.rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) + +m1.setonlyAccessor = 0; +>m1.setonlyAccessor : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) +>m1 : Symbol(m1, Decl(validator.ts, 4, 5)) +>setonlyAccessor : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) + + +=== tests/cases/conformance/jsdoc/mod1.js === +/** + * @constructor + * @param {string} name + */ +function Person(name) { +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>name : Symbol(name, Decl(mod1.js, 4, 16)) + + this.name = name; +>this.name : Symbol(Person.name, Decl(mod1.js, 4, 23)) +>this : Symbol(Person, Decl(mod1.js, 0, 0)) +>name : Symbol(Person.name, Decl(mod1.js, 4, 23)) +>name : Symbol(name, Decl(mod1.js, 4, 16)) +} +Person.prototype.describe = function () { +>Person.prototype : Symbol(Person.describe, Decl(mod1.js, 6, 1)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>describe : Symbol(Person.describe, Decl(mod1.js, 6, 1)) + + return "Person called " + this.name; +>this.name : Symbol(Person.name, Decl(mod1.js, 4, 23)) +>this : Symbol(Person, Decl(mod1.js, 0, 0)) +>name : Symbol(Person.name, Decl(mod1.js, 4, 23)) + +}; +Object.defineProperty(Person.prototype, "thing", { value: 42, writable: true }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>"thing" : Symbol(Person.thing, Decl(mod1.js, 9, 2)) +>value : Symbol(value, Decl(mod1.js, 10, 50)) +>writable : Symbol(writable, Decl(mod1.js, 10, 61)) + +Object.defineProperty(Person.prototype, "readonlyProp", { value: "Smith", writable: false }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>"readonlyProp" : Symbol(Person.readonlyProp, Decl(mod1.js, 10, 80)) +>value : Symbol(value, Decl(mod1.js, 11, 57)) +>writable : Symbol(writable, Decl(mod1.js, 11, 73)) + +Object.defineProperty(Person.prototype, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>"rwAccessors" : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) +>get : Symbol(get, Decl(mod1.js, 12, 56)) +>set : Symbol(set, Decl(mod1.js, 12, 80)) +>_ : Symbol(_, Decl(mod1.js, 12, 85)) + +Object.defineProperty(Person.prototype, "readonlyAccessor", { get() { return 21.75 } }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>"readonlyAccessor" : Symbol(Person.readonlyAccessor, Decl(mod1.js, 12, 106)) +>get : Symbol(get, Decl(mod1.js, 13, 61)) + +Object.defineProperty(Person.prototype, "setonlyAccessor", { +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Person.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>"setonlyAccessor" : Symbol(Person.setonlyAccessor, Decl(mod1.js, 13, 88)) + + /** @param {string} str */ + set(str) { +>set : Symbol(set, Decl(mod1.js, 14, 60)) +>str : Symbol(str, Decl(mod1.js, 16, 8)) + + this.rwAccessors = Number(str) +>this.rwAccessors : Symbol(Person.rwAccessors, Decl(mod1.js, 11, 93)) +>this : Symbol(Person, Decl(mod1.js, 0, 0)) +>rwAccessors : Symbol(rwAccessors, Decl(mod1.js, 16, 14)) +>Number : Symbol(Number, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>str : Symbol(str, Decl(mod1.js, 16, 8)) + } +}); +module.exports = Person; +>module.exports : Symbol("tests/cases/conformance/jsdoc/mod1", Decl(mod1.js, 0, 0)) +>module : Symbol(export=, Decl(mod1.js, 19, 3)) +>exports : Symbol(export=, Decl(mod1.js, 19, 3)) +>Person : Symbol(Person, Decl(mod1.js, 0, 0)) + diff --git a/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.types b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.types new file mode 100644 index 00000000000..662c578701f --- /dev/null +++ b/tests/baselines/reference/checkExportsObjectAssignPrototypeProperty.types @@ -0,0 +1,220 @@ +=== tests/cases/conformance/jsdoc/validator.ts === +import "./"; + +import Person = require("./mod1"); +>Person : typeof Person + +const m1 = new Person("Name") +>m1 : Person +>new Person("Name") : Person +>Person : typeof Person +>"Name" : "Name" + +m1.thing; +>m1.thing : number +>m1 : Person +>thing : number + +m1.readonlyProp; +>m1.readonlyProp : string +>m1 : Person +>readonlyProp : string + +m1.rwAccessors; +>m1.rwAccessors : number +>m1 : Person +>rwAccessors : number + +m1.readonlyAccessor; +>m1.readonlyAccessor : number +>m1 : Person +>readonlyAccessor : number + +m1.setonlyAccessor; +>m1.setonlyAccessor : string +>m1 : Person +>setonlyAccessor : string + +// allowed assignments +m1.thing = 10; +>m1.thing = 10 : 10 +>m1.thing : number +>m1 : Person +>thing : number +>10 : 10 + +m1.rwAccessors = 11; +>m1.rwAccessors = 11 : 11 +>m1.rwAccessors : number +>m1 : Person +>rwAccessors : number +>11 : 11 + +m1.setonlyAccessor = "yes"; +>m1.setonlyAccessor = "yes" : "yes" +>m1.setonlyAccessor : string +>m1 : Person +>setonlyAccessor : string +>"yes" : "yes" + +// disallowed assignments +m1.readonlyProp = "name"; +>m1.readonlyProp = "name" : "name" +>m1.readonlyProp : any +>m1 : Person +>readonlyProp : any +>"name" : "name" + +m1.readonlyAccessor = 12; +>m1.readonlyAccessor = 12 : 12 +>m1.readonlyAccessor : any +>m1 : Person +>readonlyAccessor : any +>12 : 12 + +m1.thing = "no"; +>m1.thing = "no" : "no" +>m1.thing : number +>m1 : Person +>thing : number +>"no" : "no" + +m1.rwAccessors = "no"; +>m1.rwAccessors = "no" : "no" +>m1.rwAccessors : number +>m1 : Person +>rwAccessors : number +>"no" : "no" + +m1.setonlyAccessor = 0; +>m1.setonlyAccessor = 0 : 0 +>m1.setonlyAccessor : string +>m1 : Person +>setonlyAccessor : string +>0 : 0 + + +=== tests/cases/conformance/jsdoc/mod1.js === +/** + * @constructor + * @param {string} name + */ +function Person(name) { +>Person : typeof Person +>name : string + + this.name = name; +>this.name = name : string +>this.name : string +>this : Person +>name : string +>name : string +} +Person.prototype.describe = function () { +>Person.prototype.describe = function () { return "Person called " + this.name;} : () => string +>Person.prototype.describe : any +>Person.prototype : any +>Person : typeof Person +>prototype : any +>describe : any +>function () { return "Person called " + this.name;} : () => string + + return "Person called " + this.name; +>"Person called " + this.name : string +>"Person called " : "Person called " +>this.name : string +>this : Person +>name : string + +}; +Object.defineProperty(Person.prototype, "thing", { value: 42, writable: true }); +>Object.defineProperty(Person.prototype, "thing", { value: 42, writable: true }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Person.prototype : any +>Person : typeof Person +>prototype : any +>"thing" : "thing" +>{ value: 42, writable: true } : { value: number; writable: true; } +>value : number +>42 : 42 +>writable : true +>true : true + +Object.defineProperty(Person.prototype, "readonlyProp", { value: "Smith", writable: false }); +>Object.defineProperty(Person.prototype, "readonlyProp", { value: "Smith", writable: false }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Person.prototype : any +>Person : typeof Person +>prototype : any +>"readonlyProp" : "readonlyProp" +>{ value: "Smith", writable: false } : { value: string; writable: false; } +>value : string +>"Smith" : "Smith" +>writable : false +>false : false + +Object.defineProperty(Person.prototype, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }); +>Object.defineProperty(Person.prototype, "rwAccessors", { get() { return 98122 }, set(_) { /*ignore*/ } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Person.prototype : any +>Person : typeof Person +>prototype : any +>"rwAccessors" : "rwAccessors" +>{ get() { return 98122 }, set(_) { /*ignore*/ } } : { get(): number; set(_: any): void; } +>get : () => number +>98122 : 98122 +>set : (_: any) => void +>_ : any + +Object.defineProperty(Person.prototype, "readonlyAccessor", { get() { return 21.75 } }); +>Object.defineProperty(Person.prototype, "readonlyAccessor", { get() { return 21.75 } }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Person.prototype : any +>Person : typeof Person +>prototype : any +>"readonlyAccessor" : "readonlyAccessor" +>{ get() { return 21.75 } } : { get(): number; } +>get : () => number +>21.75 : 21.75 + +Object.defineProperty(Person.prototype, "setonlyAccessor", { +>Object.defineProperty(Person.prototype, "setonlyAccessor", { /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }}) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Person.prototype : any +>Person : typeof Person +>prototype : any +>"setonlyAccessor" : "setonlyAccessor" +>{ /** @param {string} str */ set(str) { this.rwAccessors = Number(str) }} : { set(str: string): void; } + + /** @param {string} str */ + set(str) { +>set : (str: string) => void +>str : string + + this.rwAccessors = Number(str) +>this.rwAccessors = Number(str) : number +>this.rwAccessors : number +>this : Person +>rwAccessors : number +>Number(str) : number +>Number : NumberConstructor +>str : string + } +}); +module.exports = Person; +>module.exports = Person : typeof Person +>module.exports : typeof Person +>module : { "tests/cases/conformance/jsdoc/mod1": typeof Person; } +>exports : typeof Person +>Person : typeof Person + diff --git a/tests/baselines/reference/checkForObjectTooStrict.js b/tests/baselines/reference/checkForObjectTooStrict.js index d8a30eac762..d03127eaa7d 100644 --- a/tests/baselines/reference/checkForObjectTooStrict.js +++ b/tests/baselines/reference/checkForObjectTooStrict.js @@ -38,7 +38,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; } diff --git a/tests/baselines/reference/checkJsdocOnEndOfFile.errors.txt b/tests/baselines/reference/checkJsdocOnEndOfFile.errors.txt new file mode 100644 index 00000000000..4dc2320dcd8 --- /dev/null +++ b/tests/baselines/reference/checkJsdocOnEndOfFile.errors.txt @@ -0,0 +1,10 @@ +tests/cases/conformance/jsdoc/eof.js(2,20): error TS2304: Cannot find name 'bad'. + + +==== tests/cases/conformance/jsdoc/eof.js (1 errors) ==== + /** + * @typedef {Array} Should have error here + ~~~ +!!! error TS2304: Cannot find name 'bad'. + */ + \ No newline at end of file diff --git a/tests/baselines/reference/checkJsdocOnEndOfFile.js b/tests/baselines/reference/checkJsdocOnEndOfFile.js new file mode 100644 index 00000000000..a9d07d45e54 --- /dev/null +++ b/tests/baselines/reference/checkJsdocOnEndOfFile.js @@ -0,0 +1,10 @@ +//// [eof.js] +/** + * @typedef {Array} Should have error here + */ + + +//// [output.js] +/** + * @typedef {Array} Should have error here + */ diff --git a/tests/baselines/reference/checkJsdocOnEndOfFile.symbols b/tests/baselines/reference/checkJsdocOnEndOfFile.symbols new file mode 100644 index 00000000000..bda09fa653e --- /dev/null +++ b/tests/baselines/reference/checkJsdocOnEndOfFile.symbols @@ -0,0 +1,6 @@ +=== tests/cases/conformance/jsdoc/eof.js === +/** +No type information for this code. * @typedef {Array} Should have error here +No type information for this code. */ +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/checkJsdocOnEndOfFile.types b/tests/baselines/reference/checkJsdocOnEndOfFile.types new file mode 100644 index 00000000000..bda09fa653e --- /dev/null +++ b/tests/baselines/reference/checkJsdocOnEndOfFile.types @@ -0,0 +1,6 @@ +=== tests/cases/conformance/jsdoc/eof.js === +/** +No type information for this code. * @typedef {Array} Should have error here +No type information for this code. */ +No type information for this code. +No type information for this code. \ No newline at end of file diff --git a/tests/baselines/reference/checkJsdocTypeTag1.errors.txt b/tests/baselines/reference/checkJsdocTypeTag1.errors.txt new file mode 100644 index 00000000000..ee915f6aea3 --- /dev/null +++ b/tests/baselines/reference/checkJsdocTypeTag1.errors.txt @@ -0,0 +1,47 @@ +tests/cases/conformance/jsdoc/0.js(24,12): error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. + + +==== tests/cases/conformance/jsdoc/0.js (1 errors) ==== + // @ts-check + /** @type {String} */ + var S = "hello world"; + + /** @type {number} */ + var n = 10; + + /** @type {*} */ + var anyT = 2; + anyT = "hello"; + + /** @type {?} */ + var anyT1 = 2; + anyT1 = "hi"; + + /** @type {Function} */ + const x = (a) => a + 1; + x(1); + + /** @type {function} */ + const y = (a) => a + 1; + y(1); + + /** @type {function (number)} */ + ~~~~~~~~~~~~~~~~~ +!!! error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. + const x1 = (a) => a + 1; + x1(0); + + /** @type {function (number): number} */ + const x2 = (a) => a + 1; + x2(0); + + /** + * @type {object} + */ + var props = {}; + + /** + * @type {Object} + */ + var props = {}; + \ No newline at end of file diff --git a/tests/baselines/reference/checkJsdocTypeTag2.errors.txt b/tests/baselines/reference/checkJsdocTypeTag2.errors.txt index 1f0feacd675..2f57ec7f542 100644 --- a/tests/baselines/reference/checkJsdocTypeTag2.errors.txt +++ b/tests/baselines/reference/checkJsdocTypeTag2.errors.txt @@ -1,12 +1,13 @@ tests/cases/conformance/jsdoc/0.js(3,5): error TS2322: Type 'true' is not assignable to type 'string'. tests/cases/conformance/jsdoc/0.js(6,5): error TS2322: Type '"hello"' is not assignable to type 'number'. +tests/cases/conformance/jsdoc/0.js(8,12): error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. tests/cases/conformance/jsdoc/0.js(10,4): error TS2345: Argument of type '"string"' is not assignable to parameter of type 'number'. tests/cases/conformance/jsdoc/0.js(17,1): error TS2322: Type 'number' is not assignable to type 'string'. tests/cases/conformance/jsdoc/0.js(20,21): error TS2339: Property 'concat' does not exist on type 'number'. tests/cases/conformance/jsdoc/0.js(24,19): error TS2322: Type 'number' is not assignable to type 'string'. -==== tests/cases/conformance/jsdoc/0.js (6 errors) ==== +==== tests/cases/conformance/jsdoc/0.js (7 errors) ==== // @ts-check /** @type {String} */ var S = true; @@ -19,6 +20,8 @@ tests/cases/conformance/jsdoc/0.js(24,19): error TS2322: Type 'number' is not as !!! error TS2322: Type '"hello"' is not assignable to type 'number'. /** @type {function (number)} */ + ~~~~~~~~~~~~~~~~~ +!!! error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. const x1 = (a) => a + 1; x1("string"); ~~~~~~~~ diff --git a/tests/baselines/reference/checkJsdocTypeTag5.types b/tests/baselines/reference/checkJsdocTypeTag5.types index b16904c700d..816f86a80a6 100644 --- a/tests/baselines/reference/checkJsdocTypeTag5.types +++ b/tests/baselines/reference/checkJsdocTypeTag5.types @@ -68,7 +68,7 @@ function monaLisa(sb) { return typeof sb === 'string' ? 1 : 2; >typeof sb === 'string' ? 1 : 2 : 1 | 2 >typeof sb === 'string' : boolean ->typeof sb : "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function" +>typeof sb : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" >sb : any >'string' : "string" >1 : 1 diff --git a/tests/baselines/reference/checkJsdocTypeTag6.errors.txt b/tests/baselines/reference/checkJsdocTypeTag6.errors.txt index cc86b6115af..bbc2e8cd6b1 100644 --- a/tests/baselines/reference/checkJsdocTypeTag6.errors.txt +++ b/tests/baselines/reference/checkJsdocTypeTag6.errors.txt @@ -1,6 +1,5 @@ tests/cases/conformance/jsdoc/test.js(1,5): error TS8030: The type of a function declaration must match the function's signature. -tests/cases/conformance/jsdoc/test.js(7,5): error TS2322: Type '(prop: any) => void' is not assignable to type '{ prop: string; }'. - Property 'prop' is missing in type '(prop: any) => void'. +tests/cases/conformance/jsdoc/test.js(7,5): error TS2741: Property 'prop' is missing in type '(prop: any) => void' but required in type '{ prop: string; }'. tests/cases/conformance/jsdoc/test.js(10,5): error TS8030: The type of a function declaration must match the function's signature. @@ -15,8 +14,8 @@ tests/cases/conformance/jsdoc/test.js(10,5): error TS8030: The type of a functio /** @type {{ prop: string }} */ var g = function (prop) { ~ -!!! error TS2322: Type '(prop: any) => void' is not assignable to type '{ prop: string; }'. -!!! error TS2322: Property 'prop' is missing in type '(prop: any) => void'. +!!! error TS2741: Property 'prop' is missing in type '(prop: any) => void' but required in type '{ prop: string; }'. +!!! related TS2728 tests/cases/conformance/jsdoc/test.js:6:14: 'prop' is declared here. } /** @type {(a: number) => number} */ diff --git a/tests/baselines/reference/checkJsxChildrenCanBeTupleType.errors.txt b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.errors.txt new file mode 100644 index 00000000000..66078776c5f --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.errors.txt @@ -0,0 +1,35 @@ +tests/cases/conformance/jsx/checkJsxChildrenCanBeTupleType.tsx(17,18): error TS2322: Type '{ children: [Element, Element, Element]; }' is not assignable to type 'Readonly'. + Types of property 'children' are incompatible. + Type '[Element, Element, Element]' is not assignable to type '[ReactNode, ReactNode]'. + Types of property 'length' are incompatible. + Type '3' is not assignable to type '2'. + + +==== tests/cases/conformance/jsx/checkJsxChildrenCanBeTupleType.tsx (1 errors) ==== + /// + + import React from 'react' + + interface ResizablePanelProps { + children: [React.ReactNode, React.ReactNode] + } + + class ResizablePanel extends React.Component< + ResizablePanelProps, any> {} + + const test = +
+
+ + + const testErr = + ~~~~~~~~~~~~~~ +!!! error TS2322: Type '{ children: [Element, Element, Element]; }' is not assignable to type 'Readonly'. +!!! error TS2322: Types of property 'children' are incompatible. +!!! error TS2322: Type '[Element, Element, Element]' is not assignable to type '[ReactNode, ReactNode]'. +!!! error TS2322: Types of property 'length' are incompatible. +!!! error TS2322: Type '3' is not assignable to type '2'. +
+
+
+ \ No newline at end of file diff --git a/tests/baselines/reference/checkJsxChildrenCanBeTupleType.js b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.js new file mode 100644 index 00000000000..30e59613eb9 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.js @@ -0,0 +1,58 @@ +//// [checkJsxChildrenCanBeTupleType.tsx] +/// + +import React from 'react' + +interface ResizablePanelProps { + children: [React.ReactNode, React.ReactNode] +} + +class ResizablePanel extends React.Component< + ResizablePanelProps, any> {} + +const test = +
+
+ + +const testErr = +
+
+
+ + +//// [checkJsxChildrenCanBeTupleType.js] +"use strict"; +/// +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return 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 __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +exports.__esModule = true; +var react_1 = __importDefault(require("react")); +var ResizablePanel = /** @class */ (function (_super) { + __extends(ResizablePanel, _super); + function ResizablePanel() { + return _super !== null && _super.apply(this, arguments) || this; + } + return ResizablePanel; +}(react_1["default"].Component)); +var test = react_1["default"].createElement(ResizablePanel, null, + react_1["default"].createElement("div", null), + react_1["default"].createElement("div", null)); +var testErr = react_1["default"].createElement(ResizablePanel, null, + react_1["default"].createElement("div", null), + react_1["default"].createElement("div", null), + react_1["default"].createElement("div", null)); diff --git a/tests/baselines/reference/checkJsxChildrenCanBeTupleType.symbols b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.symbols new file mode 100644 index 00000000000..05c7042ad10 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.symbols @@ -0,0 +1,55 @@ +=== tests/cases/conformance/jsx/checkJsxChildrenCanBeTupleType.tsx === +/// + +import React from 'react' +>React : Symbol(React, Decl(checkJsxChildrenCanBeTupleType.tsx, 2, 6)) + +interface ResizablePanelProps { +>ResizablePanelProps : Symbol(ResizablePanelProps, Decl(checkJsxChildrenCanBeTupleType.tsx, 2, 25)) + + children: [React.ReactNode, React.ReactNode] +>children : Symbol(ResizablePanelProps.children, Decl(checkJsxChildrenCanBeTupleType.tsx, 4, 31)) +>React : Symbol(React, Decl(checkJsxChildrenCanBeTupleType.tsx, 2, 6)) +>ReactNode : Symbol(React.ReactNode, Decl(react16.d.ts, 216, 49)) +>React : Symbol(React, Decl(checkJsxChildrenCanBeTupleType.tsx, 2, 6)) +>ReactNode : Symbol(React.ReactNode, Decl(react16.d.ts, 216, 49)) +} + +class ResizablePanel extends React.Component< +>ResizablePanel : Symbol(ResizablePanel, Decl(checkJsxChildrenCanBeTupleType.tsx, 6, 1)) +>React.Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) +>React : Symbol(React, Decl(checkJsxChildrenCanBeTupleType.tsx, 2, 6)) +>Component : Symbol(React.Component, Decl(react16.d.ts, 345, 54), Decl(react16.d.ts, 349, 94)) + + ResizablePanelProps, any> {} +>ResizablePanelProps : Symbol(ResizablePanelProps, Decl(checkJsxChildrenCanBeTupleType.tsx, 2, 25)) + +const test = +>test : Symbol(test, Decl(checkJsxChildrenCanBeTupleType.tsx, 11, 5)) +>ResizablePanel : Symbol(ResizablePanel, Decl(checkJsxChildrenCanBeTupleType.tsx, 6, 1)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + + +>ResizablePanel : Symbol(ResizablePanel, Decl(checkJsxChildrenCanBeTupleType.tsx, 6, 1)) + +const testErr = +>testErr : Symbol(testErr, Decl(checkJsxChildrenCanBeTupleType.tsx, 16, 5)) +>ResizablePanel : Symbol(ResizablePanel, Decl(checkJsxChildrenCanBeTupleType.tsx, 6, 1)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + +
+>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) + + +>ResizablePanel : Symbol(ResizablePanel, Decl(checkJsxChildrenCanBeTupleType.tsx, 6, 1)) + diff --git a/tests/baselines/reference/checkJsxChildrenCanBeTupleType.types b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.types new file mode 100644 index 00000000000..a710c9b1787 --- /dev/null +++ b/tests/baselines/reference/checkJsxChildrenCanBeTupleType.types @@ -0,0 +1,57 @@ +=== tests/cases/conformance/jsx/checkJsxChildrenCanBeTupleType.tsx === +/// + +import React from 'react' +>React : typeof React + +interface ResizablePanelProps { + children: [React.ReactNode, React.ReactNode] +>children : [React.ReactNode, React.ReactNode] +>React : any +>React : any +} + +class ResizablePanel extends React.Component< +>ResizablePanel : ResizablePanel +>React.Component : React.Component +>React : typeof React +>Component : typeof React.Component + + ResizablePanelProps, any> {} + +const test = +>test : JSX.Element +>
: JSX.Element +>ResizablePanel : typeof ResizablePanel + +
+>
: JSX.Element +>div : any + +
+>
: JSX.Element +>div : any + + +>ResizablePanel : typeof ResizablePanel + +const testErr = +>testErr : JSX.Element +>
: JSX.Element +>ResizablePanel : typeof ResizablePanel + +
+>
: JSX.Element +>div : any + +
+>
: JSX.Element +>div : any + +
+>
: JSX.Element +>div : any + + +>ResizablePanel : typeof ResizablePanel + diff --git a/tests/baselines/reference/checkJsxChildrenProperty12.js b/tests/baselines/reference/checkJsxChildrenProperty12.js index 5b1d1d1b794..44fe4e1053d 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty12.js +++ b/tests/baselines/reference/checkJsxChildrenProperty12.js @@ -40,7 +40,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; } diff --git a/tests/baselines/reference/checkJsxChildrenProperty13.js b/tests/baselines/reference/checkJsxChildrenProperty13.js index 45ef75b88b1..dcdf7ac1e88 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty13.js +++ b/tests/baselines/reference/checkJsxChildrenProperty13.js @@ -35,7 +35,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; } diff --git a/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt index cf999188ebc..b401345a5e1 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt +++ b/tests/baselines/reference/checkJsxChildrenProperty14.errors.txt @@ -1,7 +1,6 @@ tests/cases/conformance/jsx/file.tsx(42,11): error TS2322: Type '{ children: Element[]; a: number; b: string; }' is not assignable to type 'SingleChildProp'. Types of property 'children' are incompatible. - Type 'Element[]' is not assignable to type 'Element'. - Property 'type' is missing in type 'Element[]'. + Type 'Element[]' is missing the following properties from type 'Element': type, props ==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== @@ -50,5 +49,4 @@ tests/cases/conformance/jsx/file.tsx(42,11): error TS2322: Type '{ children: Ele ~~~~~~~~~~~~~~~ !!! error TS2322: Type '{ children: Element[]; a: number; b: string; }' is not assignable to type 'SingleChildProp'. !!! error TS2322: Types of property 'children' are incompatible. -!!! error TS2322: Type 'Element[]' is not assignable to type 'Element'. -!!! error TS2322: Property 'type' is missing in type 'Element[]'. \ No newline at end of file +!!! error TS2322: Type 'Element[]' is missing the following properties from type 'Element': type, props \ No newline at end of file diff --git a/tests/baselines/reference/checkJsxChildrenProperty14.js b/tests/baselines/reference/checkJsxChildrenProperty14.js index 833bd43155e..12051095b6a 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty14.js +++ b/tests/baselines/reference/checkJsxChildrenProperty14.js @@ -50,7 +50,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; } diff --git a/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt index ac342678508..0edadf6dc1b 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt +++ b/tests/baselines/reference/checkJsxChildrenProperty2.errors.txt @@ -1,26 +1,21 @@ -tests/cases/conformance/jsx/file.tsx(14,10): error TS2322: Type '{ a: number; b: string; }' is not assignable to type 'Prop'. - Property 'children' is missing in type '{ a: number; b: string; }'. +tests/cases/conformance/jsx/file.tsx(14,10): error TS2741: Property 'children' is missing in type '{ a: number; b: string; }' but required in type 'Prop'. tests/cases/conformance/jsx/file.tsx(17,11): error TS2710: 'children' are specified twice. The attribute named 'children' will be overwritten. tests/cases/conformance/jsx/file.tsx(31,6): error TS2322: Type '{ children: (Element | ((name: string) => Element))[]; a: number; b: string; }' is not assignable to type 'Prop'. Types of property 'children' are incompatible. Type '(Element | ((name: string) => Element))[]' is not assignable to type 'string | Element'. - Type '(Element | ((name: string) => Element))[]' is not assignable to type 'Element'. - Property 'type' is missing in type '(Element | ((name: string) => Element))[]'. + Type '(Element | ((name: string) => Element))[]' is missing the following properties from type 'Element': type, props tests/cases/conformance/jsx/file.tsx(37,6): error TS2322: Type '{ children: (number | Element)[]; a: number; b: string; }' is not assignable to type 'Prop'. Types of property 'children' are incompatible. Type '(number | Element)[]' is not assignable to type 'string | Element'. - Type '(number | Element)[]' is not assignable to type 'Element'. - Property 'type' is missing in type '(number | Element)[]'. + Type '(number | Element)[]' is missing the following properties from type 'Element': type, props tests/cases/conformance/jsx/file.tsx(43,6): error TS2322: Type '{ children: (string | Element)[]; a: number; b: string; }' is not assignable to type 'Prop'. Types of property 'children' are incompatible. Type '(string | Element)[]' is not assignable to type 'string | Element'. - Type '(string | Element)[]' is not assignable to type 'Element'. - Property 'type' is missing in type '(string | Element)[]'. + Type '(string | Element)[]' is missing the following properties from type 'Element': type, props tests/cases/conformance/jsx/file.tsx(49,6): error TS2322: Type '{ children: Element[]; a: number; b: string; }' is not assignable to type 'Prop'. Types of property 'children' are incompatible. Type 'Element[]' is not assignable to type 'string | Element'. - Type 'Element[]' is not assignable to type 'Element'. - Property 'type' is missing in type 'Element[]'. + Type 'Element[]' is missing the following properties from type 'Element': type, props ==== tests/cases/conformance/jsx/file.tsx (6 errors) ==== @@ -39,8 +34,8 @@ tests/cases/conformance/jsx/file.tsx(49,6): error TS2322: Type '{ children: Elem // Error: missing children let k = ; ~~~~ -!!! error TS2322: Type '{ a: number; b: string; }' is not assignable to type 'Prop'. -!!! error TS2322: Property 'children' is missing in type '{ a: number; b: string; }'. +!!! error TS2741: Property 'children' is missing in type '{ a: number; b: string; }' but required in type 'Prop'. +!!! related TS2728 tests/cases/conformance/jsx/file.tsx:6:5: 'children' is declared here. let k0 = @@ -64,8 +59,7 @@ tests/cases/conformance/jsx/file.tsx(49,6): error TS2322: Type '{ children: Elem !!! error TS2322: Type '{ children: (Element | ((name: string) => Element))[]; a: number; b: string; }' is not assignable to type 'Prop'. !!! error TS2322: Types of property 'children' are incompatible. !!! error TS2322: Type '(Element | ((name: string) => Element))[]' is not assignable to type 'string | Element'. -!!! error TS2322: Type '(Element | ((name: string) => Element))[]' is not assignable to type 'Element'. -!!! error TS2322: Property 'type' is missing in type '(Element | ((name: string) => Element))[]'. +!!! error TS2322: Type '(Element | ((name: string) => Element))[]' is missing the following properties from type 'Element': type, props
My Div
{(name: string) =>
My name {name}
}
; @@ -76,8 +70,7 @@ tests/cases/conformance/jsx/file.tsx(49,6): error TS2322: Type '{ children: Elem !!! error TS2322: Type '{ children: (number | Element)[]; a: number; b: string; }' is not assignable to type 'Prop'. !!! error TS2322: Types of property 'children' are incompatible. !!! error TS2322: Type '(number | Element)[]' is not assignable to type 'string | Element'. -!!! error TS2322: Type '(number | Element)[]' is not assignable to type 'Element'. -!!! error TS2322: Property 'type' is missing in type '(number | Element)[]'. +!!! error TS2322: Type '(number | Element)[]' is missing the following properties from type 'Element': type, props
My Div
{1000000}
; @@ -88,8 +81,7 @@ tests/cases/conformance/jsx/file.tsx(49,6): error TS2322: Type '{ children: Elem !!! error TS2322: Type '{ children: (string | Element)[]; a: number; b: string; }' is not assignable to type 'Prop'. !!! error TS2322: Types of property 'children' are incompatible. !!! error TS2322: Type '(string | Element)[]' is not assignable to type 'string | Element'. -!!! error TS2322: Type '(string | Element)[]' is not assignable to type 'Element'. -!!! error TS2322: Property 'type' is missing in type '(string | Element)[]'. +!!! error TS2322: Type '(string | Element)[]' is missing the following properties from type 'Element': type, props
My Div
hi hi hi! ; @@ -100,8 +92,7 @@ tests/cases/conformance/jsx/file.tsx(49,6): error TS2322: Type '{ children: Elem !!! error TS2322: Type '{ children: Element[]; a: number; b: string; }' is not assignable to type 'Prop'. !!! error TS2322: Types of property 'children' are incompatible. !!! error TS2322: Type 'Element[]' is not assignable to type 'string | Element'. -!!! error TS2322: Type 'Element[]' is not assignable to type 'Element'. -!!! error TS2322: Property 'type' is missing in type 'Element[]'. +!!! error TS2322: Type 'Element[]' is missing the following properties from type 'Element': type, props
My Div
My Div
; \ No newline at end of file diff --git a/tests/baselines/reference/checkJsxChildrenProperty3.js b/tests/baselines/reference/checkJsxChildrenProperty3.js index 7ad2717e61b..7ebf2ec717a 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty3.js +++ b/tests/baselines/reference/checkJsxChildrenProperty3.js @@ -47,7 +47,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; } diff --git a/tests/baselines/reference/checkJsxChildrenProperty4.js b/tests/baselines/reference/checkJsxChildrenProperty4.js index 1568ef748af..02480bc17c9 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty4.js +++ b/tests/baselines/reference/checkJsxChildrenProperty4.js @@ -52,7 +52,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; } diff --git a/tests/baselines/reference/checkJsxChildrenProperty5.errors.txt b/tests/baselines/reference/checkJsxChildrenProperty5.errors.txt index 8aa860f4889..536d1e65483 100644 --- a/tests/baselines/reference/checkJsxChildrenProperty5.errors.txt +++ b/tests/baselines/reference/checkJsxChildrenProperty5.errors.txt @@ -1,13 +1,10 @@ -tests/cases/conformance/jsx/file.tsx(20,10): error TS2322: Type '{ a: number; b: string; }' is not assignable to type 'Prop'. - Property 'children' is missing in type '{ a: number; b: string; }'. +tests/cases/conformance/jsx/file.tsx(20,10): error TS2741: Property 'children' is missing in type '{ a: number; b: string; }' but required in type 'Prop'. tests/cases/conformance/jsx/file.tsx(24,6): error TS2322: Type '{ children: Element; a: number; b: string; }' is not assignable to type 'Prop'. Types of property 'children' are incompatible. - Type 'Element' is not assignable to type 'Button'. - Property 'render' is missing in type 'Element'. + Type 'Element' is missing the following properties from type 'Button': render, setState, forceUpdate, state, and 2 more. tests/cases/conformance/jsx/file.tsx(28,6): error TS2322: Type '{ children: typeof Button; a: number; b: string; }' is not assignable to type 'Prop'. Types of property 'children' are incompatible. - Type 'typeof Button' is not assignable to type 'Button'. - Property 'render' is missing in type 'typeof Button'. + Type 'typeof Button' is missing the following properties from type 'Button': render, setState, forceUpdate, props, and 3 more. ==== tests/cases/conformance/jsx/file.tsx (3 errors) ==== @@ -32,8 +29,8 @@ tests/cases/conformance/jsx/file.tsx(28,6): error TS2322: Type '{ children: type // Error: no children specified let k = ; ~~~~ -!!! error TS2322: Type '{ a: number; b: string; }' is not assignable to type 'Prop'. -!!! error TS2322: Property 'children' is missing in type '{ a: number; b: string; }'. +!!! error TS2741: Property 'children' is missing in type '{ a: number; b: string; }' but required in type 'Prop'. +!!! related TS2728 tests/cases/conformance/jsx/file.tsx:6:5: 'children' is declared here. // Error: JSX.element is not the same as JSX.ElementClass let k1 = @@ -41,8 +38,7 @@ tests/cases/conformance/jsx/file.tsx(28,6): error TS2322: Type '{ children: type ~~~~ !!! error TS2322: Type '{ children: Element; a: number; b: string; }' is not assignable to type 'Prop'. !!! error TS2322: Types of property 'children' are incompatible. -!!! error TS2322: Type 'Element' is not assignable to type 'Button'. -!!! error TS2322: Property 'render' is missing in type 'Element'. +!!! error TS2322: Type 'Element' is missing the following properties from type 'Button': render, setState, forceUpdate, state, and 2 more.