Merge remote-tracking branch 'origin/master' into release-3.7

This commit is contained in:
Daniel Rosenwasser
2019-10-21 14:48:19 -07:00
530 changed files with 56484 additions and 42381 deletions
+6 -2
View File
@@ -15,8 +15,12 @@ Please help us by doing the following steps before logging an issue:
Please fill in the *entire* template below.
-->
<!-- Please try to reproduce the issue with `typescript@next`. It may have already been fixed. -->
**TypeScript Version:** 3.4.0-dev.201xxxxx
<!--
Please try to reproduce the issue with the latest published version. It may have already been fixed.
For npm: `typescript@next`
This is also the 'Nightly' version in the playground: http://www.typescriptlang.org/play/?ts=Nightly
-->
**TypeScript Version:** 3.7.x-dev.201xxxxx
<!-- Search terms you tried before logging this (so others can find this issue more easily) -->
**Search Terms:**
+3 -2
View File
@@ -61,9 +61,10 @@ internal/
**/.DS_Store
.settings
**/.vs
**/.vscode
**/.vscode/*
!**/.vscode/tasks.json
!**/.vscode/settings.json
!**/.vscode/settings.template.json
!**/.vscode/launch.template.json
!**/.vscode/extensions.json
!tests/cases/projects/projectOption/**/node_modules
!tests/cases/projects/NodeModulesSearch/**/*
+60
View File
@@ -0,0 +1,60 @@
/*
Copy this file into '.vscode/launch.json' or merge its
contents into your existing configurations.
If you want to remove the errors in comments for all JSON
files, add this to your settings in ~/.vscode/User/settings.json
"files.associations": {
"*.json": "jsonc"
},
*/
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"protocol": "inspector",
"request": "launch",
"name": "Mocha Tests (currently opened test)",
"runtimeArgs": ["--nolazy"],
"program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
"args": [
"-u",
"bdd",
"--no-timeouts",
"--colors",
"built/local/run.js",
"-f",
// You can change this to be the name of a specific test file (without the file extension)
// to consistently launch the same test
"${fileBasenameNoExtension}",
"--skip-percent",
"0"
],
"env": {
"NODE_ENV": "testing"
},
"sourceMaps": true,
"smartStep": true,
"preLaunchTask": "tests",
"console": "integratedTerminal",
"outFiles": [
"${workspaceRoot}/built/local/run.js"
]
},
{
// See: https://github.com/microsoft/TypeScript/wiki/Debugging-Language-Service-in-VS-Code
"type": "node",
"request": "attach",
"name": "Attach to VS Code TS Server via Port",
"processId": "${command:PickProcess}"
}
]
}
-12
View File
@@ -1,12 +0,0 @@
{
"eslint.validate": [
{
"language": "typescript",
"autoFix": true
}
],
"eslint.options": {
"rulePaths": ["./scripts/eslint/built/rules/"],
"ext": [".ts"]
}
}
+19
View File
@@ -0,0 +1,19 @@
// Rename this file 'settings.json' or merge its
// contents into your existing settings.
{
"eslint.validate": [
{
"language": "typescript",
"autoFix": true
}
],
"eslint.options": {
"rulePaths": ["./scripts/eslint/built/rules/"],
"ext": [".ts"]
},
// To use the last-known-good (LKG) compiler version:
// "typescript.tsdk": "lib"
// To use the locally built compiler, after 'npm run build':
// "typescript.tsdk": "built/local"
}
+2
View File
@@ -160,6 +160,8 @@ You can debug with VS Code or Node instead with `gulp runtests --inspect=true`:
gulp runtests --tests=2dArrays --inspect=true
```
You can also use the [provided VS Code launch configuration](./.vscode/launch.template.json) to launch a debug session for an open test file. Rename the file 'launch.json', open the test file of interest, and launch the debugger from the debug panel (or press F5).
## Adding a Test
To add a new test case, simply place a `.ts` file in `tests\cases\compiler` containing code that exemplifies the bugfix or change you are making.
+12 -2
View File
@@ -90,8 +90,18 @@ const localize = async () => {
}
};
const buildShims = () => buildProject("src/shims");
const cleanShims = () => cleanProject("src/shims");
cleanTasks.push(cleanShims);
const buildDebugTools = () => buildProject("src/debug");
const cleanDebugTools = () => cleanProject("src/debug");
cleanTasks.push(cleanDebugTools);
const buildShimsAndTools = parallel(buildShims, buildDebugTools);
// Pre-build steps when targeting the LKG compiler
const lkgPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics));
const lkgPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics, buildShimsAndTools));
const buildTsc = () => buildProject("src/tsc");
task("tsc", series(lkgPreBuild, buildTsc));
@@ -107,7 +117,7 @@ task("watch-tsc", series(lkgPreBuild, parallel(watchLib, watchDiagnostics, watch
task("watch-tsc").description = "Watch for changes and rebuild the command-line compiler only.";
// Pre-build steps when targeting the built/local compiler.
const localPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics, buildTsc));
const localPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics, buildShimsAndTools, buildTsc));
// Pre-build steps to use based on supplied options.
const preBuild = cmdLineOptions.lkg ? lkgPreBuild : localPreBuild;
+1 -1
View File
@@ -42,7 +42,7 @@ with any additional questions or comments.
## Documentation
* [Quick tutorial](https://www.typescriptlang.org/docs/tutorial.html)
* [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)
* [Programming handbook](https://www.typescriptlang.org/docs/handbook/basic-types.html)
* [Language specification](https://github.com/microsoft/TypeScript/blob/master/doc/spec.md)
* [Homepage](https://www.typescriptlang.org/)
+1 -1
View File
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Implementace funkce chybí nebo nenásleduje hned po deklaraci.",
"Function_implementation_name_must_be_0_2389": "Název implementace funkce musí být {0}.",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Funkce implicitně obsahuje návratový typ any, protože neobsahuje anotaci návratového typu a odkazuje se na ni přímo nebo nepřímo v jednom z jejích návratových výrazů.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Ve funkci chybí koncový návratový příkaz a návratový typ neobsahuje undefined.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Ve funkci chybí koncový příkaz return a návratový typ neobsahuje undefined.",
"Function_overload_must_be_static_2387": "Přetížení funkce musí být statické.",
"Function_overload_must_not_be_static_2388": "Přetížení funkce nesmí být statické.",
"Generate_get_and_set_accessors_95046": "Generovat přístupové objekty get a set",
+1 -1
View File
@@ -1032,7 +1032,7 @@
"await_expression_is_only_allowed_within_an_async_function_1308": "Der Ausdruck \"await\" ist nur in einer asynchronen Funktion zulässig.",
"await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "await-Ausdrücke dürfen nicht in einem Parameterinitialisierer verwendet werden.",
"baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "Die Option \"baseUrl\" ist auf \"{0}\" festgelegt. Dieser Wert wird verwendet, um den nicht relativen Modulnamen \"{1}\" aufzulösen.",
"can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "\"=\" kann nur in einer Objektliteraleigenschaft innerhalb eines Destrukturierungsauftrags verwendet werden.",
"can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "\"=\" kann nur in einer Objektliteraleigenschaft innerhalb eines Destrukturierungszuweisung verwendet werden.",
"case_or_default_expected_1130": "\"case\" oder \"default\" wurde erwartet.",
"class_expressions_are_not_currently_supported_9003": "class-Ausdrücke werden zurzeit nicht unterstützt.",
"const_declarations_can_only_be_declared_inside_a_block_1156": "const-Deklarationen können nur innerhalb eines Blocks deklariert werden.",
+2 -2
View File
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Falta la implementación de función o no sigue inmediatamente a la declaración.",
"Function_implementation_name_must_be_0_2389": "El nombre de la implementación de función debe ser '{0}'.",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "La función tiene el tipo de valor devuelto \"any\" implícitamente porque no tiene una anotación de tipo de valor devuelto y se hace referencia a ella directa o indirectamente en una de sus expresiones return.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Falta la instrucción return final en la función y el tipo de valor devuelto no incluye 'undefined'.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Falta la instrucción \"return\" final en la función y el tipo de valor devuelto no incluye 'undefined'.",
"Function_overload_must_be_static_2387": "La sobrecarga de función debe ser estática.",
"Function_overload_must_not_be_static_2388": "La sobrecarga de función no debe ser estática.",
"Generate_get_and_set_accessors_95046": "Generar los descriptores de acceso \"get\" y \"set\"",
@@ -453,7 +453,7 @@
"Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Los generadores solo están disponibles cuando el destino es ECMAScript 2015 o una versión posterior.",
"Generic_type_0_requires_1_type_argument_s_2314": "El tipo genérico '{0}' requiere los siguientes argumentos de tipo: {1}.",
"Generic_type_0_requires_between_1_and_2_type_arguments_2707": "El tipo genérico \"{0}\" requiere entre {1} y {2} argumentos de tipo.",
"Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "La creación de instancias de tipo genérico es excesivamente profunda y posiblemente infinita.",
"Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "La creación de una instancia de tipo genérico es excesivamente profunda y posiblemente infinita.",
"Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Los descriptores de acceso de captador y establecedor no se corresponden respecto a la visibilidad.",
"Global_module_exports_may_only_appear_at_top_level_1316": "Las exportaciones de módulos globales solo pueden aparecer en el nivel superior.",
"Global_module_exports_may_only_appear_in_declaration_files_1315": "Las exportaciones de módulos globales solo pueden aparecer en archivos de declaración.",
+3 -3
View File
@@ -142,7 +142,7 @@
"An_async_iterator_must_have_a_next_method_2519": "Un itérateur asynchrone doit comporter une méthode 'next()'.",
"An_element_access_expression_should_take_an_argument_1011": "Une expression d'accès à un élément doit accepter un argument.",
"An_enum_member_cannot_have_a_numeric_name_2452": "Un membre enum ne peut pas avoir un nom numérique.",
"An_export_assignment_can_only_be_used_in_a_module_1231": "Une attribution d'exportation peut uniquement être utilisée dans un module.",
"An_export_assignment_can_only_be_used_in_a_module_1231": "Une affectation d'exportation peut uniquement être utilisée dans un module.",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Impossible d'utiliser une assignation d'exportation dans un module comportant d'autres éléments exportés.",
"An_export_assignment_cannot_be_used_in_a_namespace_1063": "Une affectation d'exportation ne peut pas être utilisée dans un espace de noms.",
"An_export_assignment_cannot_have_modifiers_1120": "Une assignation d'exportation ne peut pas avoir de modificateurs.",
@@ -594,7 +594,7 @@
"No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Aucune entrée dans le fichier config '{0}'. Les chemins 'include' spécifiés étaient '{1}' et les chemins 'exclude' étaient '{2}'.",
"Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "La classe non abstraite '{0}' n'implémente pas le membre abstrait '{1}' hérité de la classe '{2}'.",
"Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "L'expression de classe non abstraite '{0}' n'implémente pas le membre abstrait hérité '{0}' de la classe '{1}'.",
"Not_all_code_paths_return_a_value_7030": "Les chemins de code ne retournent pas tous une valeur.",
"Not_all_code_paths_return_a_value_7030": "Les chemins du code ne retournent pas tous une valeur.",
"Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Impossible d'assigner le type d'index numérique '{0}' au type d'index de chaîne '{1}'.",
"Numeric_separators_are_not_allowed_here_6188": "Les séparateurs numériques ne sont pas autorisés ici.",
"Object_is_of_type_unknown_2571": "L'objet est de type 'unknown'.",
@@ -745,7 +745,7 @@
"Remove_unused_label_95053": "Supprimer l'étiquette inutilisée",
"Remove_variable_statement_90010": "Supprimer l'instruction de variable",
"Replace_import_with_0_95015": "Remplacez l'importation par '{0}'.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins de code de la fonction ne retournent pas tous une valeur.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins du code de la fonction ne retournent pas tous une valeur.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Signalez les erreurs pour les case avec fallthrough dans une instruction switch.",
"Report_errors_in_js_files_8019": "Signalez les erreurs dans les fichiers .js.",
"Report_errors_on_unused_locals_6134": "Signaler les erreurs sur les variables locales inutilisées.",
+15 -15
View File
@@ -130,7 +130,7 @@
"Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' フラグが指定されている場合、アンビエント const 列挙型は使用できません。",
"Ambient_module_declaration_cannot_specify_relative_module_name_2436": "アンビエント モジュール宣言では、相対モジュール名を指定できません。",
"Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "アンビエント モジュールを、他のモジュールまたは名前空間内の入れ子にすることはできません。",
"An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD モジュールに複数の名前を割り当てることはできません。",
"An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD モジュールに複数の名前を代入することはできません。",
"An_abstract_accessor_cannot_have_an_implementation_1318": "抽象アクセサーに実装を含めることはできません。",
"An_accessor_cannot_be_declared_in_an_ambient_context_1086": "環境コンテキストではアクセサーは宣言できません。",
"An_accessor_cannot_have_type_parameters_1094": "アクセサーに型パラメーターを指定することはできません。",
@@ -142,10 +142,10 @@
"An_async_iterator_must_have_a_next_method_2519": "非同期反復子には 'next()' メソッドが必要です。",
"An_element_access_expression_should_take_an_argument_1011": "要素アクセス式では、引数を取る必要があります。",
"An_enum_member_cannot_have_a_numeric_name_2452": "列挙型メンバーに数値名を含めることはできません。",
"An_export_assignment_can_only_be_used_in_a_module_1231": "エクスポートの割り当てはモジュールでのみ使用可能です。",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "エクスポートの割り当ては、エクスポートされた他の要素を含むモジュールでは使用できません。",
"An_export_assignment_cannot_be_used_in_a_namespace_1063": "エクスポートの割り当ては、名前空間では使用できません。",
"An_export_assignment_cannot_have_modifiers_1120": "エクスポートの割り当てに修飾子を指定することはできません。",
"An_export_assignment_can_only_be_used_in_a_module_1231": "エクスポートの代入はモジュールでのみ使用可能です。",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "エクスポートの代入は、エクスポートされた他の要素を含むモジュールでは使用できません。",
"An_export_assignment_cannot_be_used_in_a_namespace_1063": "エクスポートの代入は、名前空間では使用できません。",
"An_export_assignment_cannot_have_modifiers_1120": "エクスポートの代入に修飾子を指定することはできません。",
"An_export_declaration_can_only_be_used_in_a_module_1233": "エクスポート宣言はモジュールでのみ使用可能です。",
"An_export_declaration_cannot_have_modifiers_1193": "エクスポート宣言に修飾子を指定することはできません。",
"An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "拡張された Unicode エスケープ値は 0x0 と 0x10FFFF の間 (両端を含む) でなければなりません。",
@@ -389,8 +389,8 @@
"Experimental_Options_6177": "試験的なオプション",
"Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "デコレーターの実験的なサポートは将来のリリースで変更になる可能性がある機能です。'experimentalDecorators' オプションを設定してこの警告を削除します。",
"Explicitly_specified_module_resolution_kind_Colon_0_6087": "明示的に指定されたモジュール解決の種類 '{0}'。",
"Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript モジュールを対象にする場合は、エクスポート割り当てを使用できません。代わりに 'export default' または別のモジュール書式の使用をご検討ください。",
"Export_assignment_is_not_supported_when_module_flag_is_system_1218": "割り当てのエクスポートは、'--module' フラグが 'system' の場合にはサポートされません。",
"Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript モジュールを対象にする場合は、エクスポート代入を使用できません。代わりに 'export default' または別のモジュール書式の使用をご検討ください。",
"Export_assignment_is_not_supported_when_module_flag_is_system_1218": "代入のエクスポートは、'--module' フラグが 'system' の場合にはサポートされません。",
"Export_declaration_conflicts_with_exported_declaration_of_0_2484": "エクスポート宣言が、'{0}' のエクスポートされた宣言と競合しています。",
"Export_declarations_are_not_permitted_in_a_namespace_1194": "エクスポート宣言は名前空間でサポートされません。",
"Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "エクスポートされた外部パッケージの型指定のファイル '{0}' はモジュールではありません。パッケージ定義を更新する場合は、パッケージの作成者にお問い合わせください。",
@@ -399,7 +399,7 @@
"Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "エクスポートされた変数 '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。",
"Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "エクスポートされた変数 '{0}' がプライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。",
"Exported_variable_0_has_or_is_using_private_name_1_4025": "エクスポートされた変数 '{0}' がプライベート名 '{1}' を持っているか、使用しています。",
"Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "エクスポートとエクスポートの割り当てはモジュールの拡張では許可されていません。",
"Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "エクスポートとエクスポートの代入はモジュールの拡張では許可されていません。",
"Expression_expected_1109": "式が必要です。",
"Expression_or_comma_expected_1137": "式またはコンマが必要です。",
"Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "式は、コンパイラが基底クラスの参照をキャプチャするために使用する '_super' に解決されます。",
@@ -473,7 +473,7 @@
"Implement_interface_0_90006": "インターフェイス '{0}' を実装する",
"Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "エクスポートされたクラス '{0}' の Implements 句がプライベート名 '{1}' を持っているか、使用しています。",
"Import_0_from_module_1_90013": "モジュール \"{1}\" から '{0}' をインポートする",
"Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript モジュールを対象にする場合は、インポート割り当てを使用できません。代わりに 'import * as ns from \"mod\"'、'import {a} from \"mod\"'、'import d from \"mod\"' などのモジュール書式の使用をご検討ください。",
"Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript モジュールを対象にする場合は、インポート代入を使用できません。代わりに 'import * as ns from \"mod\"'、'import {a} from \"mod\"'、'import d from \"mod\"' などのモジュール書式の使用をご検討ください。",
"Import_declaration_0_is_using_private_name_1_4000": "インポート宣言 '{0}' がプライベート名 '{1}' を使用しています。",
"Import_declaration_conflicts_with_local_declaration_of_0_2440": "インポート宣言が、'{0}' のローカル宣言と競合しています。",
"Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "名前空間内のインポート宣言は、モジュールを参照できません。",
@@ -536,7 +536,7 @@
"JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 要素に同じ名前の複数の属性を指定することはできません。",
"JSX_expressions_must_have_one_parent_element_2657": "JSX 式には 1 つの親要素が必要です。",
"JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX フラグメントには対応する終了タグがありません。",
"JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "JSX フラグメントはインライン JSX ファクトリ プラグマの使用時にサポートされていません",
"JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "JSX フラグメントはインライン JSX ファクトリ pragma の使用時にサポートされていません",
"JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "--jsxFactory を使う場合、JSX フラグメントはサポートされません",
"JSX_spread_child_must_be_an_array_type_2609": "JSX スプレッドの子は、配列型でなければなりません。",
"Jump_target_cannot_cross_function_boundary_1107": "ジャンプ先は関数の境界を越えることはできません。",
@@ -714,7 +714,7 @@
"Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "エクスポートされたインターフェイスのプロパティ '{0}' が、プライベート名 '{1}' を持っているか、使用しています。",
"Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "型 '{1}' のプロパティ '{0}' を数値インデックス型 '{2}' に割り当てることはできません。",
"Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "型 '{1}' のプロパティ '{0}' を文字列インデックス型 '{2}' に割り当てることはできません。",
"Property_assignment_expected_1136": "プロパティの割り当てが必要です。",
"Property_assignment_expected_1136": "プロパティの代入が必要です。",
"Property_destructuring_pattern_expected_1180": "プロパティの非構造化パターンが必要です。",
"Property_or_signature_expected_1131": "プロパティまたはシグネチャが必要です。",
"Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "プロパティ値には、文字列リテラル、数値リテラル、'true'、'false'、'null'、オブジェクト リテラルまたは配列リテラルのみ使用できます。",
@@ -850,7 +850,7 @@
"The_character_set_of_the_input_files_6163": "入力ファイルの文字セット。",
"The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "含まれている関数またはモジュールの本体は、制御フロー解析には大きすぎます。",
"The_current_host_does_not_support_the_0_option_5001": "現在のホストは '{0}' オプションをサポートしていません。",
"The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "エクスポートの割り当ての式は、環境コンテキストの識別子または修飾名にする必要があります。",
"The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "エクスポートの代入の式は、環境コンテキストの識別子または修飾名にする必要があります。",
"The_files_list_in_config_file_0_is_empty_18002": "構成ファイル '{0}' の 'files' リストが空です。",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise では、'then' メソッドの最初のパラメーターはコールバックでなければなりません。",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "グローバル型 'JSX.{0}' には複数のプロパティが含まれていない可能性があります。",
@@ -882,7 +882,7 @@
"The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "instanceof' 式の右辺には、'any' 型、または 'Function' インターフェイス型に割り当てることができる型を指定してください。",
"The_specified_path_does_not_exist_Colon_0_5058": "指定されたパスがありません: '{0}'。",
"The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "代入式のターゲットは、変数またはプロパティ アクセスである必要があります。",
"The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "オブジェクトの残り部分の割り当ての対象は、変数またはプロパティ アクセスである必要があります。",
"The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "オブジェクトの残り部分の代入の対象は、変数またはプロパティ アクセスである必要があります。",
"The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "型 '{0}' の 'this' コンテキストを型 '{1}' のメソッドの 'this' に割り当てることはできません。",
"The_this_types_of_each_signature_are_incompatible_2685": "各シグネチャの 'this' 型に互換性がありません。",
"The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "型パラメーター '{0}' の型引数を使用法から推論することはできません。型引数を明示的に指定してください。",
@@ -1032,14 +1032,14 @@
"await_expression_is_only_allowed_within_an_async_function_1308": "'await' 式は、非同期関数内でのみ使用できます。",
"await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' 式は、パラメーター初期化子では使用できません。",
"baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' オプションは '{0}' に設定され、この値を使用して非相対モジュール名 '{1}' を解決します。",
"can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' は、非構造化割り当て内のオブジェクト リテラル プロパティでのみ使用できます。",
"can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' は、非構造化代入内のオブジェクト リテラル プロパティでのみ使用できます。",
"case_or_default_expected_1130": "'case' または 'default' が必要です。",
"class_expressions_are_not_currently_supported_9003": "'class' 式は現在サポートされていません。",
"const_declarations_can_only_be_declared_inside_a_block_1156": "'const' 宣言は、ブロック内でのみ宣言できます。",
"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": "厳格モードでは '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": "'列挙型宣言' を使用できるのは .ts ファイル内のみです。",
+1 -1
View File
@@ -1067,7 +1067,7 @@
"or_expected_1144": "'{' 또는 ';'이(가) 필요합니다.",
"package_json_does_not_have_a_0_field_6100": "'package.json'에는 '{0}' 필드가 없습니다.",
"package_json_has_0_field_1_that_references_2_6101": "'package.json'에 '{2}'을(를) 참조하는 '{0}' 필드 '{1}'이(가) 있습니다.",
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers'는 .ts 파일에서만 사용할 수 있습니다.",
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'매개 변수 한정자'는 .ts 파일에서만 사용할 수 있습니다.",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 옵션이 지정되었습니다. 모듈 이름 '{0}'과(와) 일치하는 패턴을 찾는 중입니다.",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 한정자는 속성 선언 또는 인덱스 시그니처에만 나타날 수 있습니다.",
"require_call_may_be_converted_to_an_import_80005": "'require' 호출이 가져오기로 변환될 수 있습니다.",
+2 -2
View File
@@ -9782,7 +9782,7 @@ interface ImageData {
declare var ImageData: {
prototype: ImageData;
new(width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height?: number): ImageData;
};
interface InnerHTML {
@@ -19103,7 +19103,7 @@ declare namespace WebAssembly {
var Instance: {
prototype: Instance;
new(module: Module, importObject?: any): Instance;
new(module: Module, importObject?: Imports): Instance;
};
interface LinkError {
+8 -8
View File
@@ -702,8 +702,8 @@ interface Math {
/** Returns a pseudorandom number between 0 and 1. */
random(): number;
/**
* Returns a supplied numeric expression rounded to the nearest number.
* @param x The value to be rounded to the nearest number.
* Returns a supplied numeric expression rounded to the nearest integer.
* @param x The value to be rounded to the nearest integer.
*/
round(x: number): number;
/**
@@ -893,12 +893,12 @@ interface DateConstructor {
/**
* Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date.
* @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year.
* @param month The month as an number between 0 and 11 (January to December).
* @param date The date as an number between 1 and 31.
* @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour.
* @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes.
* @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds.
* @param ms An number from 0 to 999 that specifies the milliseconds.
* @param month The month as a number between 0 and 11 (January to December).
* @param date The date as a number between 1 and 31.
* @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour.
* @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes.
* @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds.
* @param ms A number from 0 to 999 that specifies the milliseconds.
*/
UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number;
now(): number;
+2 -2
View File
@@ -2222,7 +2222,7 @@ interface ImageData {
declare var ImageData: {
prototype: ImageData;
new(width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height?: number): ImageData;
};
/** This Channel Messaging API interface allows us to create a new message channel and send data through it via its two MessagePort properties. */
@@ -5629,7 +5629,7 @@ declare namespace WebAssembly {
var Instance: {
prototype: Instance;
new(module: Module, importObject?: any): Instance;
new(module: Module, importObject?: Imports): Instance;
};
interface Memory {
+4 -4
View File
@@ -30,7 +30,7 @@
"A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Dekorator może dekorować jedynie implementację metody, a nie przeciążenie.",
"A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Klauzula „default” nie może występować więcej niż raz w instrukcji „switch”.",
"A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Eksport domyślny może być używany tylko w module w stylu języka ECMAScript.",
"A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Asercja określonego przydziału „!” nie jest dozwolona w tym kontekście.",
"A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Asercja określonego przypisania „!” nie jest dozwolona w tym kontekście.",
"A_destructuring_declaration_must_have_an_initializer_1182": "Deklaracja usuwająca strukturę musi mieć inicjator.",
"A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Wywołanie dynamicznego importowania w wersji ES5/ES3 wymaga konstruktora „Promise”. Upewnij się, że masz deklarację dla konstruktora „Promise”, lub uwzględnij wartość „ES2015” w opcji „--lib”.",
"A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Wywołanie dynamicznego importowania zwraca element „Promise”. Upewnij się, że masz deklarację elementu „Promise” lub uwzględnij wartość „ES2015” w opcji „--lib”.",
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Brak implementacji funkcji lub nie występuje ona bezpośrednio po deklaracji.",
"Function_implementation_name_must_be_0_2389": "Implementacja funkcji musi mieć nazwę „{0}”.",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Dla funkcji niejawnie określono zwracany typ „any”, ponieważ nie zawiera ona adnotacji zwracanego typu i jest przywoływana bezpośrednio lub pośrednio w jednym z jej zwracanych wyrażeń.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Funkcja nie zawiera końcowej instrukcji return, a zwracany typ nie obejmuje wartości „undefined”.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Funkcja nie zawiera końcowej instrukcji return, a zwracany typ nie obejmuje wartości „undefined”.",
"Function_overload_must_be_static_2387": "Przeciążenie funkcji musi być statyczne.",
"Function_overload_must_not_be_static_2388": "Przeciążenie funkcji nie może być statyczne.",
"Generate_get_and_set_accessors_95046": "Generuj metody dostępu „get” i „set”.",
@@ -594,7 +594,7 @@
"No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Nie można znaleźć danych wejściowych w pliku konfiguracji „{0}”. Określone ścieżki „include” to „{1}”, a „exclude” to „{2}”.",
"Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Klasa nieabstrakcyjna „{0}” nie implementuje odziedziczonej abstrakcyjnej składowej „{1}” z klasy „{2}”.",
"Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Wyrażenie klasy nieabstrakcyjnej nie implementuje odziedziczonej abstrakcyjnej składowej „{0}” z klasy „{1}”.",
"Not_all_code_paths_return_a_value_7030": "Nie wszystkie ścieżki kodu zwracają wartość.",
"Not_all_code_paths_return_a_value_7030": "Nie wszystkie ścieżki w kodzie zwracają wartość.",
"Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Nie można przypisać typu indeksu numerycznego „{0}” do typu indeksu ciągu „{1}”.",
"Numeric_separators_are_not_allowed_here_6188": "Separatory liczbowe nie są dozwolone w tym miejscu.",
"Object_is_of_type_unknown_2571": "Obiekt jest typu „nieznany”.",
@@ -745,7 +745,7 @@
"Remove_unused_label_95053": "Usuń nieużywaną etykietę",
"Remove_variable_statement_90010": "Usuń instrukcję zmiennej",
"Replace_import_with_0_95015": "Zamień import na element „{0}”.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki kodu zwracają wartość.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki w kodzie zwracają wartość.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Zgłoś błędy dla przepuszczających klauzul case w instrukcji switch.",
"Report_errors_in_js_files_8019": "Zgłaszaj błędy w plikach js.",
"Report_errors_on_unused_locals_6134": "Raportuj błędy dla nieużywanych elementów lokalnych.",
+9 -1
View File
@@ -652,9 +652,11 @@ declare namespace ts.server.protocol {
interface DefinitionResponse extends Response {
body?: FileSpanWithContext[];
}
interface DefinitionInfoAndBoundSpanReponse extends Response {
interface DefinitionInfoAndBoundSpanResponse extends Response {
body?: DefinitionInfoAndBoundSpan;
}
/** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */
type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse;
/**
* Definition response message. Gives text range for definition.
*/
@@ -2317,6 +2319,12 @@ declare namespace ts.server.protocol {
* For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`.
*/
readonly includeCompletionsWithInsertText?: boolean;
/**
* Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled,
* member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined
* values, with insertion text to replace preceding `.` tokens with `?.`.
*/
readonly includeAutomaticOptionalChainCompletions?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
readonly lazyConfiguredProjectsFromExternalProject?: boolean;
+1 -1
View File
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "A implementação da função está ausente ou não está imediatamente depois da declaração.",
"Function_implementation_name_must_be_0_2389": "O nome da implementação de função deve ser '{0}'.",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "A função tem o tipo de retorno 'any', de forma implícita, porque ela não tem uma anotação de tipo de retorno e é referenciada direta ou indiretamente em uma das suas expressões de retorno.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "A função não tem a instrução de retorno final e o tipo de retorno não inclui 'undefined'.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "A função não tem a instrução return final e o tipo de retorno não inclui 'undefined'.",
"Function_overload_must_be_static_2387": "A sobrecarga de função deve ser estática.",
"Function_overload_must_not_be_static_2388": "A sobrecarga de função não deve ser estática.",
"Generate_get_and_set_accessors_95046": "Gerar acessadores 'get' e 'set'",
+15 -15
View File
@@ -30,7 +30,7 @@
"A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Декоратор может только декорировать реализацию метода, а не перегрузку.",
"A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Предложение default не может повторяться в операторе switch.",
"A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Экспорт по умолчанию можно использовать только в модуле в стиле ECMAScript.",
"A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Утверждение определенного присваивания \"!\" запрещено в этом контексте.",
"A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Утверждение определенного назначения \"!\" запрещено в этом контексте.",
"A_destructuring_declaration_must_have_an_initializer_1182": "Объявление деструктурирования должно включать инициализатор.",
"A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Для вызова динамического импорта в ES5/ES3 требуется конструктор \"Promise\". Объявите конструктор \"Promise\" или включите \"ES2015\" в параметр \"--lib\".",
"A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Вызов динамического импорта возвращает конструктор \"Promise\". Объявите конструктор \"Promise\" или включите \"ES2015\" в параметр \"--lib\".",
@@ -103,8 +103,8 @@
"Add_all_missing_super_calls_95039": "Добавить все отсутствующие вызовы super",
"Add_async_modifier_to_containing_function_90029": "Добавьте модификатор async в содержащую функцию",
"Add_braces_to_arrow_function_95059": "Добавить скобки в стрелочную функцию",
"Add_definite_assignment_assertion_to_property_0_95020": "Добавить утверждение определенного присваивания к свойству \"{0}\"",
"Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Добавить утверждения определенного присваивания ко всем неинициализированным свойствам",
"Add_definite_assignment_assertion_to_property_0_95020": "Добавить утверждение определенного назначения к свойству \"{0}\"",
"Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Добавить утверждения определенного назначения ко всем неинициализированным свойствам",
"Add_index_signature_for_property_0_90017": "Добавьте сигнатуру индекса для свойства \"{0}\"",
"Add_initializer_to_property_0_95019": "Добавить инициализатор к свойству \"{0}\"",
"Add_initializers_to_all_uninitialized_properties_95027": "Добавить инициализаторы ко всем неинициализированным свойствам",
@@ -130,7 +130,7 @@
"Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Перечисление внешних констант не разрешено, если задан флаг \"--isolatedModules\".",
"Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Объявление окружающего модуля не может содержать относительное имя модуля.",
"Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Внешний модуль не может быть вложен в другие модули или пространства имен.",
"An_AMD_module_cannot_have_multiple_name_assignments_2458": "Модуль AMD не может иметь несколько присваиваний имен.",
"An_AMD_module_cannot_have_multiple_name_assignments_2458": "Модуль AMD не может иметь несколько назначений имен.",
"An_abstract_accessor_cannot_have_an_implementation_1318": "У абстрактного метода доступа не может быть реализации.",
"An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Метод доступа нельзя объявить в окружающем контексте.",
"An_accessor_cannot_have_type_parameters_1094": "Метод доступа не может иметь параметры типа.",
@@ -142,10 +142,10 @@
"An_async_iterator_must_have_a_next_method_2519": "В асинхронном итераторе должен быть метод next().",
"An_element_access_expression_should_take_an_argument_1011": "Выражение доступа к элементу должно принимать аргумент.",
"An_enum_member_cannot_have_a_numeric_name_2452": "Имя элемента перечисления не может быть числовым.",
"An_export_assignment_can_only_be_used_in_a_module_1231": "Присваивание экспорта может быть использовано только в модуле.",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Присваивание экспорта нельзя использовать в модуле с другими экспортированными элементами.",
"An_export_assignment_cannot_be_used_in_a_namespace_1063": "Присваивание экспорта нельзя использовать в пространстве имен.",
"An_export_assignment_cannot_have_modifiers_1120": "Присваивание экспорта не может иметь модификаторы.",
"An_export_assignment_can_only_be_used_in_a_module_1231": "Назначение экспорта может быть использовано только в модуле.",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Назначение экспорта нельзя использовать в модуле с другими экспортированными элементами.",
"An_export_assignment_cannot_be_used_in_a_namespace_1063": "Назначение экспорта нельзя использовать в пространстве имен.",
"An_export_assignment_cannot_have_modifiers_1120": "Назначение экспорта не может иметь модификаторы.",
"An_export_declaration_can_only_be_used_in_a_module_1233": "Объявление экспорта может быть использовано только в модуле.",
"An_export_declaration_cannot_have_modifiers_1193": "Объявление экспорта не может иметь модификаторы.",
"An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Расширенное escape-значение в Юникоде должно быть в пределах от 0x0 до 0x10FFFF включительно.",
@@ -390,7 +390,7 @@
"Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Экспериментальная поддержка для декораторов — это функция, которая будет изменена в будущем выпуске. Задайте параметр experimentalDecorators, чтобы удалить это предупреждение.",
"Explicitly_specified_module_resolution_kind_Colon_0_6087": "Явно указанный тип разрешения модуля: \"{0}\".",
"Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Назначение экспорта невозможно использовать при разработке для модулей ECMAScript. Попробуйте использовать \"export default\" или другой формат модуля.",
"Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Присваивание экспорта не поддерживается, если флаг \"--module\" имеет значение \"system\".",
"Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Назначение экспорта не поддерживается, если флаг \"--module\" имеет значение \"system\".",
"Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Объявление экспорта конфликтует с экспортированным объявлением \"{0}\".",
"Export_declarations_are_not_permitted_in_a_namespace_1194": "Объявления экспорта не разрешены в пространстве имен.",
"Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Файл экспортированных внешних типизаций пакета \"{0}\" не является модулем. Обратитесь к автору пакета для обновления определения пакета.",
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Реализация функции отсутствует либо не идет сразу после объявления.",
"Function_implementation_name_must_be_0_2389": "Имя реализации функции должно иметь значение \"{0}\".",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Функция неявно имеет тип возвращаемого значения any, так как у нее нет заметки с типом возвращаемого значения, а также на нее прямо или косвенно указывает ссылка в одном из ее выражений \"return\".",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "В функции отсутствует завершающий оператор возвращаемого значения, а тип возвращаемого значения не включает undefined.",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "В функции отсутствует завершающий оператор return, а тип возвращаемого значения не включает \"undefined\".",
"Function_overload_must_be_static_2387": "Перегрузка функции должна быть статической.",
"Function_overload_must_not_be_static_2388": "Перегрузка функции не должна быть статической.",
"Generate_get_and_set_accessors_95046": "Создать методы доступа get и set",
@@ -594,7 +594,7 @@
"No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Не удалось найти входные данные в файле конфигурации \"{0}\". Указанные пути \"include\": \"{1}\", пути \"exclude\": \"{2}\".",
"Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Класс \"{0}\", не являющийся абстрактным, не реализует наследуемый абстрактный элемент \"{1}\" класса \"{2}\".",
"Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Выражение неабстрактного класса не реализует унаследованный абстрактный элемент \"{0}\" класса \"{1}\".",
"Not_all_code_paths_return_a_value_7030": "Не все пути кода возвращают значение.",
"Not_all_code_paths_return_a_value_7030": "Не все пути к коду возвращают значение.",
"Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Тип числового индекса \"{0}\" нельзя назначить типу строкового индекса \"{1}\".",
"Numeric_separators_are_not_allowed_here_6188": "Числовые разделители здесь запрещены.",
"Object_is_of_type_unknown_2571": "Объект имеет тип \"Неизвестный\".",
@@ -714,7 +714,7 @@
"Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Свойство \"{0}\" экспортированного интерфейса имеет или использует закрытое имя \"{1}\".",
"Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "Свойство \"{0}\" типа \"{1}\" нельзя назначить типу числового индекса \"{2}\".",
"Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "Свойство \"{0}\" типа \"{1}\" нельзя назначить типу строкового индекса \"{2}\".",
"Property_assignment_expected_1136": "Ожидалось присваивание свойства.",
"Property_assignment_expected_1136": "Ожидалось назначение свойства.",
"Property_destructuring_pattern_expected_1180": "Ожидался шаблон деструктурирования свойства.",
"Property_or_signature_expected_1131": "Ожидалось свойство или сигнатура.",
"Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Значение свойства может быть только строковым или числовым литералом, True, False, Null, объектным литералом либо литералом массива.",
@@ -745,7 +745,7 @@
"Remove_unused_label_95053": "Удалить неиспользуемую метку",
"Remove_variable_statement_90010": "Удалить оператор с переменной",
"Replace_import_with_0_95015": "Замена импорта на \"{0}\".",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути кода в функции возвращают значение.",
"Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути к коду в функции возвращают значение.",
"Report_errors_for_fallthrough_cases_in_switch_statement_6076": "Сообщать об ошибках для случаев передачи управления в операторе switch.",
"Report_errors_in_js_files_8019": "Сообщать об ошибках в JS-файлах.",
"Report_errors_on_unused_locals_6134": "Сообщать об ошибках в неиспользованных локальных переменных.",
@@ -850,7 +850,7 @@
"The_character_set_of_the_input_files_6163": "Кодировка входных файлов.",
"The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Содержащая функция или текст модуля слишком велики для анализа потока управления.",
"The_current_host_does_not_support_the_0_option_5001": "Текущий узел не поддерживает параметр \"{0}\".",
"The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Выражение присваивания экспорта должно представлять собой идентификатор или полное имя в окружающем контексте.",
"The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Выражение назначения экспорта должно представлять собой идентификатор или полное имя в окружающем контексте.",
"The_files_list_in_config_file_0_is_empty_18002": "Список \"files\" в файле конфигурации \"{0}\" пуст.",
"The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Первым параметром метода then класса promise должен быть обратный вызов.",
"The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Глобальный тип \"JSX.{0}\" не может иметь больше одного свойства.",
@@ -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": "Невозможно вызвать оператор 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": "Объявления перечислений можно использовать только в TS-файле.",
+1 -1
View File
@@ -453,7 +453,7 @@
"Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Oluşturucular yalnızca ECMEAScript 2015 veya üstü hedeflenirken kullanılabilir.",
"Generic_type_0_requires_1_type_argument_s_2314": "'{0}' genel türü, {1} tür bağımsız değişkenini gerektiriyor.",
"Generic_type_0_requires_between_1_and_2_type_arguments_2707": "'{0}' genel türü {1} ile {2} arasında bağımsız değişken gerektirir.",
"Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Genel tür oluşturma işlemi, fazla ayrıntılı ve büyük olasılıkla sınırsız.",
"Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Genel tür örneği oluşturma işlemi, fazla ayrıntılı ve büyük olasılıkla sınırsız.",
"Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Alıcı ve ayarlayıcı erişimcileri görünürlükte anlaşamıyor.",
"Global_module_exports_may_only_appear_at_top_level_1316": "Genel modül dışarı aktarmaları yalnızca en üst düzeyde görünebilir.",
"Global_module_exports_may_only_appear_in_declaration_files_1315": "Genel modül dışarı aktarmaları yalnızca bildirim dosyalarında görünebilir.",
+1363 -1136
View File
File diff suppressed because it is too large Load Diff
+1543 -1260
View File
File diff suppressed because it is too large Load Diff
+23 -3
View File
@@ -13,6 +13,12 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
declare namespace ts {
interface Map<T> {
}
function createMapShim(): new <T>() => Map<T>;
}
//# sourceMappingURL=shims.d.ts.map
declare namespace ts {
const versionMajorMinor = "3.7";
/** The version of the TypeScript compiler release */
@@ -1964,6 +1970,8 @@ declare namespace ts {
DiagnosticsPresent_OutputsSkipped = 1,
DiagnosticsPresent_OutputsGenerated = 2,
InvalidProject_OutputsSkipped = 3,
ProjectReferenceCycle_OutputsSkipped = 4,
/** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
ProjectReferenceCycle_OutputsSkupped = 4
}
export interface EmitResult {
@@ -3169,6 +3177,7 @@ declare namespace ts {
readonly disableSuggestions?: boolean;
readonly quotePreference?: "auto" | "double" | "single";
readonly includeCompletionsForModuleExports?: boolean;
readonly includeAutomaticOptionalChainCompletions?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
@@ -4902,6 +4911,9 @@ declare namespace ts {
isClassOrInterface(): this is InterfaceType;
isClass(): this is InterfaceType;
}
interface TypeReference {
typeArguments?: readonly Type[];
}
interface Signature {
getDeclaration(): SignatureDeclaration;
getTypeParameters(): TypeParameter[] | undefined;
@@ -5068,7 +5080,7 @@ declare namespace ts {
getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined;
organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[];
getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[];
getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput;
getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput;
getProgram(): Program | undefined;
dispose(): void;
}
@@ -5191,7 +5203,7 @@ declare namespace ts {
}
interface FileTextChanges {
fileName: string;
textChanges: TextChange[];
textChanges: readonly TextChange[];
isNewFile?: boolean;
}
interface CodeAction {
@@ -6623,9 +6635,11 @@ declare namespace ts.server.protocol {
interface DefinitionResponse extends Response {
body?: FileSpanWithContext[];
}
interface DefinitionInfoAndBoundSpanReponse extends Response {
interface DefinitionInfoAndBoundSpanResponse extends Response {
body?: DefinitionInfoAndBoundSpan;
}
/** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */
type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse;
/**
* Definition response message. Gives text range for definition.
*/
@@ -8288,6 +8302,12 @@ declare namespace ts.server.protocol {
* For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`.
*/
readonly includeCompletionsWithInsertText?: boolean;
/**
* Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled,
* member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined
* values, with insertion text to replace preceding `.` tokens with `?.`.
*/
readonly includeAutomaticOptionalChainCompletions?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
readonly lazyConfiguredProjectsFromExternalProject?: boolean;
+1599 -1165
View File
File diff suppressed because it is too large Load Diff
+14 -2
View File
@@ -13,6 +13,12 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
declare namespace ts {
interface Map<T> {
}
function createMapShim(): new <T>() => Map<T>;
}
//# sourceMappingURL=shims.d.ts.map
declare namespace ts {
const versionMajorMinor = "3.7";
/** The version of the TypeScript compiler release */
@@ -1964,6 +1970,8 @@ declare namespace ts {
DiagnosticsPresent_OutputsSkipped = 1,
DiagnosticsPresent_OutputsGenerated = 2,
InvalidProject_OutputsSkipped = 3,
ProjectReferenceCycle_OutputsSkipped = 4,
/** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
ProjectReferenceCycle_OutputsSkupped = 4
}
export interface EmitResult {
@@ -3169,6 +3177,7 @@ declare namespace ts {
readonly disableSuggestions?: boolean;
readonly quotePreference?: "auto" | "double" | "single";
readonly includeCompletionsForModuleExports?: boolean;
readonly includeAutomaticOptionalChainCompletions?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
@@ -4902,6 +4911,9 @@ declare namespace ts {
isClassOrInterface(): this is InterfaceType;
isClass(): this is InterfaceType;
}
interface TypeReference {
typeArguments?: readonly Type[];
}
interface Signature {
getDeclaration(): SignatureDeclaration;
getTypeParameters(): TypeParameter[] | undefined;
@@ -5068,7 +5080,7 @@ declare namespace ts {
getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined;
organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[];
getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[];
getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput;
getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput;
getProgram(): Program | undefined;
dispose(): void;
}
@@ -5191,7 +5203,7 @@ declare namespace ts {
}
interface FileTextChanges {
fileName: string;
textChanges: TextChange[];
textChanges: readonly TextChange[];
isNewFile?: boolean;
}
interface CodeAction {
+1560 -1157
View File
File diff suppressed because it is too large Load Diff
+14 -2
View File
@@ -13,6 +13,12 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
declare namespace ts {
interface Map<T> {
}
function createMapShim(): new <T>() => Map<T>;
}
//# sourceMappingURL=shims.d.ts.map
declare namespace ts {
const versionMajorMinor = "3.7";
/** The version of the TypeScript compiler release */
@@ -1964,6 +1970,8 @@ declare namespace ts {
DiagnosticsPresent_OutputsSkipped = 1,
DiagnosticsPresent_OutputsGenerated = 2,
InvalidProject_OutputsSkipped = 3,
ProjectReferenceCycle_OutputsSkipped = 4,
/** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
ProjectReferenceCycle_OutputsSkupped = 4
}
export interface EmitResult {
@@ -3169,6 +3177,7 @@ declare namespace ts {
readonly disableSuggestions?: boolean;
readonly quotePreference?: "auto" | "double" | "single";
readonly includeCompletionsForModuleExports?: boolean;
readonly includeAutomaticOptionalChainCompletions?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
@@ -4902,6 +4911,9 @@ declare namespace ts {
isClassOrInterface(): this is InterfaceType;
isClass(): this is InterfaceType;
}
interface TypeReference {
typeArguments?: readonly Type[];
}
interface Signature {
getDeclaration(): SignatureDeclaration;
getTypeParameters(): TypeParameter[] | undefined;
@@ -5068,7 +5080,7 @@ declare namespace ts {
getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined;
organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[];
getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[];
getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput;
getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput;
getProgram(): Program | undefined;
dispose(): void;
}
@@ -5191,7 +5203,7 @@ declare namespace ts {
}
interface FileTextChanges {
fileName: string;
textChanges: TextChange[];
textChanges: readonly TextChange[];
isNewFile?: boolean;
}
interface CodeAction {
+1560 -1157
View File
File diff suppressed because it is too large Load Diff
+1360 -1182
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "函数实现缺失或未立即出现在声明之后。",
"Function_implementation_name_must_be_0_2389": "函数实现名称必须为“{0}”。",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "由于函数不具有返回类型批注并且在它的一个返回表达式中得到直接或间接引用,因此它隐式具有返回类型 \"any\"。",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函数缺少结束返回语句,返回类型不包括 \"undefined\"。",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函数缺少结束 return 语句,返回类型不包括 \"undefined\"。",
"Function_overload_must_be_static_2387": "函数重载必须为静态。",
"Function_overload_must_not_be_static_2388": "函数重载不能为静态。",
"Generate_get_and_set_accessors_95046": "生成 \"get\" 和 \"set\" 访问器",
@@ -536,7 +536,7 @@
"JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 元素不能具有多个名称相同的特性。",
"JSX_expressions_must_have_one_parent_element_2657": "JSX 表达式必须具有一个父元素。",
"JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX 片段没有相应的结束标记。",
"JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "使用内联 JSX 工厂杂注时,不支持 JSX 片段",
"JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "使用内联 JSX 工厂 pragma 时,不支持 JSX 片段",
"JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "使用 --jsxFactory 时不支持 JSX 片段",
"JSX_spread_child_must_be_an_array_type_2609": "JSX 扩展子属性必须为数组类型。",
"Jump_target_cannot_cross_function_boundary_1107": "跳转目标不能跨越函数边界。",
+32 -32
View File
@@ -1,12 +1,12 @@
{
"A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "'{0}' 修飾無法與匯入宣告並用。",
"A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "'{0}' 修飾無法與介面宣告並用。",
"A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "'{0}' 修飾無法與匯入宣告並用。",
"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_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' 修飾的類別宣告必須要有名稱。",
"A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "不具 'default' 修飾的類別宣告必須要有名稱。",
"A_class_may_only_extend_another_class_2311": "每個類別只可擴充另一個類別。",
"A_class_may_only_implement_another_class_or_interface_2422": "每個類別只可實作另一個類別或介面。",
"A_class_member_cannot_have_the_0_keyword_1248": "類別成員不能含有 '{0}' 關鍵字。",
@@ -25,8 +25,8 @@
"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_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": ".d.ts 檔案中的最上層宣告需要 'declare' 修飾。",
"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": ".d.ts 檔案中的最上層宣告需要 'declare' 修飾。",
"A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "一個裝飾項目只能裝飾一項方法實作,而不能多載。",
"A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "'default' 子句在 'switch' 陳述式中不得出現一次以上。",
"A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "預設匯出只能在 ECMAScript 樣式的模組中使用。",
@@ -93,15 +93,15 @@
"Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "無法透過 super 運算式存取類別 '{1}' 中的抽象方法 '{0}'。",
"Abstract_methods_can_only_appear_within_an_abstract_class_1244": "抽象方法只可出現在抽象類別中。",
"Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "無法從建構函式存取類別 '{1}' 中的抽象屬性 '{0}'。",
"Accessibility_modifier_already_seen_1028": "已有存取範圍修飾。",
"Accessibility_modifier_already_seen_1028": "已有存取範圍修飾。",
"Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "只有當目標為 ECMAScript 5 及更高版本時,才可使用存取子。",
"Accessors_must_both_be_abstract_or_non_abstract_2676": "存取子必須兩者均為抽象或非抽象。",
"Add_0_to_existing_import_declaration_from_1_90015": "從 \"{1}\" 將 '{0}' 新增至現有的匯入宣告",
"Add_0_to_unresolved_variable_90008": "對未解析的變數新增 '{0}.'",
"Add_all_missing_async_modifiers_95041": "新增缺少的所有 'async' 修飾",
"Add_all_missing_async_modifiers_95041": "新增缺少的所有 'async' 修飾",
"Add_all_missing_members_95022": "新增遺漏的所有成員",
"Add_all_missing_super_calls_95039": "新增缺少的所有 super 呼叫",
"Add_async_modifier_to_containing_function_90029": "將 async 修飾新增至包含的函式",
"Add_async_modifier_to_containing_function_90029": "將 async 修飾新增至包含的函式",
"Add_braces_to_arrow_function_95059": "將大括號新增至箭號函式",
"Add_definite_assignment_assertion_to_property_0_95020": "將明確指派判斷提示新增至屬性 '{0}'",
"Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "為所有未初始化的屬性新增明確的指派判斷提示",
@@ -119,7 +119,7 @@
"Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "新增 tsconfig.json 檔案有助於組織同時包含 TypeScript 及 JavaScript 檔案的專案。若要深入了解,請前往 https://aka.ms/tsconfig。",
"Additional_Checks_6176": "其他檢查",
"Advanced_Options_6178": "進階選項",
"All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' 的所有宣告都必須有相同修飾。",
"All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' 的所有宣告都必須有相同修飾。",
"All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' 的所有宣告都必須具有相同的類型參數。",
"All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有宣告必須連續。",
"All_destructured_elements_are_unused_6198": "不會使用所有未經結構化的項目。",
@@ -145,20 +145,20 @@
"An_export_assignment_can_only_be_used_in_a_module_1231": "匯出指派只可用於模組中。",
"An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "匯出指派不得用於具有其他匯出項目的模組中。",
"An_export_assignment_cannot_be_used_in_a_namespace_1063": "命名空間中不可使用匯出指派。",
"An_export_assignment_cannot_have_modifiers_1120": "匯出指派不得有修飾。",
"An_export_assignment_cannot_have_modifiers_1120": "匯出指派不得有修飾。",
"An_export_declaration_can_only_be_used_in_a_module_1233": "匯出宣告只可用於模組中。",
"An_export_declaration_cannot_have_modifiers_1193": "匯出宣告不得有修飾。",
"An_export_declaration_cannot_have_modifiers_1193": "匯出宣告不得有修飾。",
"An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "擴充的 Unicode 逸出值必須介於 0x0 與 0x10FFFF (不含) 之間。",
"An_implementation_cannot_be_declared_in_ambient_contexts_1183": "不得在環境內容中宣告實作。",
"An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "匯入宣告只可用於命名空間或模組中。",
"An_import_declaration_cannot_have_modifiers_1191": "匯入宣告不得有修飾。",
"An_import_declaration_cannot_have_modifiers_1191": "匯入宣告不得有修飾。",
"An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "匯入路徑的結尾不得為 '{0}' 副檔名。請考慮改為匯入 '{1}'。",
"An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "索引運算式引數必須是 'string'、'number'、'symbol' 或 'any' 類型。",
"An_index_signature_cannot_have_a_rest_parameter_1017": "索引簽章不得有剩餘參數。",
"An_index_signature_must_have_a_type_annotation_1021": "索引簽章必須有類型註釋。",
"An_index_signature_must_have_exactly_one_parameter_1096": "索引簽章只可有一個參數。",
"An_index_signature_parameter_cannot_have_a_question_mark_1019": "索引簽章參數不得有問號。",
"An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引簽章參數不得有存取範圍修飾。",
"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}'。",
@@ -183,7 +183,7 @@
"Array_element_destructuring_pattern_expected_1181": "必須是陣列項目解構模式。",
"Asterisk_Slash_expected_1010": "必須是 '*/'。",
"Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "全域範圍的增強指定只能在外部模組宣告或環境模組宣告直接巢狀。",
"Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "除非全域範圍的增強指定已顯示在環境內容中,否則應含有 'declare' 修飾。",
"Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "除非全域範圍的增強指定已顯示在環境內容中,否則應含有 'declare' 修飾。",
"Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "專案 '{0}' 中已啟用鍵入的自動探索。正在使用快取位置 '{2}' 執行模組 '{1}' 的額外解析傳遞。",
"Base_class_expressions_cannot_reference_class_type_parameters_2562": "基底類別運算式無法參考類別型別參數。",
"Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "基底建構函式傳回型別 '{0}' 不是類別或介面類型。",
@@ -441,7 +441,7 @@
"Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "遺漏函式實作,或函式實作未緊接在宣告之後。",
"Function_implementation_name_must_be_0_2389": "函式實作名稱必須是 '{0}'。",
"Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "函式因為沒有傳回型別註解,並在其中一個傳回運算式中直接或間接參考了自己,所以隱含了傳回型別 'any'。",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函式缺少結束傳回陳述式,且傳回類型不包括 'undefined'。",
"Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函式缺少結束 return 陳述式,且傳回類型不包括 'undefined'。",
"Function_overload_must_be_static_2387": "函式多載必須為靜態。",
"Function_overload_must_not_be_static_2388": "函式多載不可為靜態。",
"Generate_get_and_set_accessors_95046": "產生 'get' 與 'set' 存取子",
@@ -565,7 +565,7 @@
"Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "因為方法 '{0}' 已標記為抽象,所以不可具有實作。",
"Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "匯出介面的方法 '{0}' 具有或使用私用模組 '{2}' 的名稱 '{1}'。",
"Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "匯出介面的方法 '{0}' 具有或使用私用名稱 '{1}'。",
"Modifiers_cannot_appear_here_1184": "此處不得出現修飾。",
"Modifiers_cannot_appear_here_1184": "此處不得出現修飾。",
"Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "模組 '{0}' 未參考任何類型,但在此用為類型。",
"Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "模組 '{0}' 未參考任何值,但在此用為值。",
"Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "模組 {0} 已匯出名為 '{1}' 的成員。請考慮明確重新匯出項目以解決模稜兩可的情形。",
@@ -1009,26 +1009,26 @@
"_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' 在其本身的基底運算式中直接或間接受到參考。",
"_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' 在其本身的類型註釋中直接或間接受到參考。",
"_0_list_cannot_be_empty_1097": "'{0}' 清單不得為空白。",
"_0_modifier_already_seen_1030": "已有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_a_class_element_1031": "類別項目不得有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "建構函式宣告不得有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_a_data_property_1043": "資料屬性不得有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "模組或命名空間元素不能有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_a_parameter_1090": "參數不得有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_a_type_member_1070": "類型成員不能有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_an_index_signature_1071": "索引簽章不能有 '{0}' 修飾。",
"_0_modifier_cannot_be_used_here_1042": "無法在此處使用 '{0}' 修飾。",
"_0_modifier_cannot_be_used_in_an_ambient_context_1040": "無法在環境內容中使用 '{0}' 修飾。",
"_0_modifier_cannot_be_used_with_1_modifier_1243": "'{0}' 修飾無法與 '{1}' 修飾並用。",
"_0_modifier_cannot_be_used_with_a_class_declaration_1041": "'{0}' 修飾無法與類別宣告並用。",
"_0_modifier_must_precede_1_modifier_1029": "'{0}' 修飾必須在 '{1}' 修飾之前。",
"_0_modifier_already_seen_1030": "已有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_a_class_element_1031": "類別項目不得有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "建構函式宣告不得有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_a_data_property_1043": "資料屬性不得有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "模組或命名空間元素不能有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_a_parameter_1090": "參數不得有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_a_type_member_1070": "類型成員不能有 '{0}' 修飾。",
"_0_modifier_cannot_appear_on_an_index_signature_1071": "索引簽章不能有 '{0}' 修飾。",
"_0_modifier_cannot_be_used_here_1042": "無法在此處使用 '{0}' 修飾。",
"_0_modifier_cannot_be_used_in_an_ambient_context_1040": "無法在環境內容中使用 '{0}' 修飾。",
"_0_modifier_cannot_be_used_with_1_modifier_1243": "'{0}' 修飾無法與 '{1}' 修飾並用。",
"_0_modifier_cannot_be_used_with_a_class_declaration_1041": "'{0}' 修飾無法與類別宣告並用。",
"_0_modifier_must_precede_1_modifier_1029": "'{0}' 修飾必須在 '{1}' 修飾之前。",
"_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' 只參考類型,但在這裡用作命名空間。",
"_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' 只會參考類型,但此處將其用為值。",
"_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' 指的是全域的 UMD,但目前的檔案為模組。請考慮改為新增匯入。",
"_0_tag_already_specified_1223": "已指定 '{0}' 標記。",
"_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "'{0}' 標記不得獨立用作頂層 JSDoc 標記。",
"_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "缺少傳回型別註解的 '{0}' 隱含了 '{1}' 傳回型別。",
"abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "'abstract' 修飾只能出現在類別宣告、方法宣告或屬性宣告。",
"abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "'abstract' 修飾只能出現在類別宣告、方法宣告或屬性宣告。",
"await_expression_is_only_allowed_within_an_async_function_1308": "只有非同步函式才允許 'await' 運算式。",
"await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' 運算式不得用於參數初始設定式。",
"baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' 選項已設為 '{0}'。此值將用於解析非相對的模組名稱 '{1}'。",
@@ -1044,7 +1044,7 @@
"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": "「列舉宣告」只可用於 .ts 檔案中。",
"export_can_only_be_used_in_a_ts_file_8003": "'export=' 只可用於 .ts 檔案中。",
"export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "'export' 修飾無法套用至環境模組或模組增強指定,原因是這二者永遠會顯示。",
"export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "'export' 修飾無法套用至環境模組或模組增強指定,原因是這二者永遠會顯示。",
"extends_clause_already_seen_1172": "已經有 'extends' 子句。",
"extends_clause_must_precede_implements_clause_1173": "'extends' 子句必須在 'implements' 子句之前。",
"extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "匯出類別 '{0}' 的 'extends' 子句具有或使用私用名稱 '{1}'。",
@@ -1069,7 +1069,7 @@
"package_json_has_0_field_1_that_references_2_6101": "'package.json' 有參考 '{2}' 的 '{0}' 欄位 '{1}'。",
"parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' 只可用於 .ts 檔案中。",
"paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 選項已指定,將尋找符合模組名稱 '{0}' 的模式。",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾只能出現在屬性宣告或索引簽章。",
"readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾只能出現在屬性宣告或索引簽章。",
"require_call_may_be_converted_to_an_import_80005": "'require' 呼叫可能會轉換為匯入。",
"rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 選項已設定。該選項將用於解析相對的模組名稱 '{0}'。",
"super_can_only_be_referenced_in_a_derived_class_2335": "只有衍生類別中才可參考 'super'。",
+5 -5
View File
@@ -54,9 +54,9 @@
"@types/through2": "latest",
"@types/travis-fold": "latest",
"@types/xml2js": "^0.4.0",
"@typescript-eslint/eslint-plugin": "2.2.0",
"@typescript-eslint/experimental-utils": "2.2.0",
"@typescript-eslint/parser": "2.2.0",
"@typescript-eslint/eslint-plugin": "2.3.2",
"@typescript-eslint/experimental-utils": "2.3.2",
"@typescript-eslint/parser": "2.3.2",
"async": "latest",
"azure-devops-node-api": "^8.0.0",
"browser-resolve": "^1.11.2",
@@ -65,10 +65,10 @@
"chalk": "latest",
"convert-source-map": "latest",
"del": "5.1.0",
"eslint": "6.3.0",
"eslint": "6.5.1",
"eslint-formatter-autolinkable-stylish": "1.0.3",
"eslint-plugin-import": "2.18.2",
"eslint-plugin-jsdoc": "15.9.1",
"eslint-plugin-jsdoc": "15.9.9",
"eslint-plugin-no-null": "1.0.2",
"fancy-log": "latest",
"fs-extra": "^6.0.1",
+30 -18
View File
@@ -161,7 +161,12 @@ namespace ts {
IsObjectLiteralOrClassExpressionMethod = 1 << 7,
}
let flowNodeCreated: <T extends FlowNode>(node: T) => T = identity;
function initFlowNode<T extends FlowNode>(node: T) {
Debug.attachFlowNodeDebugInfo(node);
return node;
}
let flowNodeCreated: <T extends FlowNode>(node: T) => T = initFlowNode;
const binder = createBinder();
@@ -238,6 +243,10 @@ namespace ts {
Symbol = objectAllocator.getSymbolConstructor();
// Attach debugging information if necessary
Debug.attachFlowNodeDebugInfo(unreachableFlow);
Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
if (!file.locals) {
bind(file);
file.symbolCount = symbolCount;
@@ -626,7 +635,7 @@ namespace ts {
// A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
// similarly to break statements that exit to a label just past the statement body.
if (!isIIFE) {
currentFlow = { flags: FlowFlags.Start };
currentFlow = initFlowNode({ flags: FlowFlags.Start });
if (containerFlags & (ContainerFlags.IsFunctionExpression | ContainerFlags.IsObjectLiteralOrClassExpressionMethod)) {
currentFlow.node = <FunctionExpression | ArrowFunction | MethodDeclaration>node;
}
@@ -638,7 +647,7 @@ namespace ts {
currentContinueTarget = undefined;
activeLabels = undefined;
hasExplicitReturn = false;
flowNodeCreated = identity;
flowNodeCreated = initFlowNode;
bindChildren(node);
// Reset all reachability check related flags on node (for incremental scenarios)
node.flags &= ~NodeFlags.ReachabilityAndEmitFlags;
@@ -812,9 +821,6 @@ namespace ts {
case SyntaxKind.JSDocEnumTag:
bindJSDocTypeAlias(node as JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag);
break;
case SyntaxKind.JSDocClassTag:
bindJSDocClassTag(node as JSDocClassTag);
break;
// In source files and blocks, bind functions first to match hoisting that occurs at runtime
case SyntaxKind.SourceFile: {
bindEachFunctionsFirst((node as SourceFile).statements);
@@ -856,9 +862,8 @@ namespace ts {
function isNarrowableReference(expr: Expression): boolean {
return expr.kind === SyntaxKind.Identifier || expr.kind === SyntaxKind.ThisKeyword || expr.kind === SyntaxKind.SuperKeyword ||
(isPropertyAccessExpression(expr) || isNonNullExpression(expr) || isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
isElementAccessExpression(expr) &&
isStringOrNumericLiteralLike(expr.argumentExpression) &&
isNarrowableReference(expr.expression);
isElementAccessExpression(expr) && isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) ||
isOptionalChain(expr);
}
function hasNarrowableArgument(expr: CallExpression) {
@@ -920,11 +925,11 @@ namespace ts {
}
function createBranchLabel(): FlowLabel {
return { flags: FlowFlags.BranchLabel, antecedents: undefined };
return initFlowNode({ flags: FlowFlags.BranchLabel, antecedents: undefined });
}
function createLoopLabel(): FlowLabel {
return { flags: FlowFlags.LoopLabel, antecedents: undefined };
return initFlowNode({ flags: FlowFlags.LoopLabel, antecedents: undefined });
}
function setFlowNodeReferenced(flow: FlowNode) {
@@ -948,7 +953,7 @@ namespace ts {
}
if (expression.kind === SyntaxKind.TrueKeyword && flags & FlowFlags.FalseCondition ||
expression.kind === SyntaxKind.FalseKeyword && flags & FlowFlags.TrueCondition) {
if (!isOptionalChainRoot(expression.parent)) {
if (!isExpressionOfOptionalChainRoot(expression)) {
return unreachableFlow;
}
}
@@ -1194,7 +1199,7 @@ namespace ts {
// as possible antecedents of the start of the `catch` or `finally` blocks.
// Don't bother intercepting the call if there's no finally or catch block that needs the information
if (node.catchClause || node.finallyBlock) {
flowNodeCreated = node => (tryPriors.push(node), node);
flowNodeCreated = node => (tryPriors.push(node), initFlowNode(node));
}
bind(node.tryBlock);
flowNodeCreated = oldFlowNodeCreated;
@@ -1263,7 +1268,7 @@ namespace ts {
//
// extra edges that we inject allows to control this behavior
// if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped.
const preFinallyFlow: PreFinallyFlow = { flags: FlowFlags.PreFinally, antecedent: preFinallyPrior, lock: {} };
const preFinallyFlow: PreFinallyFlow = initFlowNode({ flags: FlowFlags.PreFinally, antecedent: preFinallyPrior, lock: {} });
addAntecedent(preFinallyLabel, preFinallyFlow);
currentFlow = finishFlowLabel(preFinallyLabel);
@@ -1333,7 +1338,7 @@ namespace ts {
bind(clause);
fallthroughFlow = currentFlow;
if (!(currentFlow.flags & FlowFlags.Unreachable) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
errorOnFirstToken(clause, Diagnostics.Fallthrough_case_in_switch);
clause.fallthroughFlowNode = currentFlow;
}
}
clauses.transformFlags = subtreeTransformFlags | TransformFlags.HasComputedFlags;
@@ -1984,7 +1989,7 @@ namespace ts {
const host = getJSDocHost(typeAlias);
container = findAncestor(host.parent, n => !!(getContainerFlags(n) & ContainerFlags.IsContainer)) || file;
blockScopeContainer = getEnclosingBlockScopeContainer(host) || file;
currentFlow = { flags: FlowFlags.Start };
currentFlow = initFlowNode({ flags: FlowFlags.Start });
parent = typeAlias;
bind(typeAlias.typeExpression);
const declName = getNameOfDeclaration(typeAlias);
@@ -2446,6 +2451,8 @@ namespace ts {
case SyntaxKind.JSDocTypeLiteral:
case SyntaxKind.MappedType:
return bindAnonymousTypeWorker(node as TypeLiteralNode | MappedTypeNode | JSDocTypeLiteral);
case SyntaxKind.JSDocClassTag:
return bindJSDocClassTag(node as JSDocClassTag);
case SyntaxKind.ObjectLiteralExpression:
return bindObjectLiteralExpression(<ObjectLiteralExpression>node);
case SyntaxKind.FunctionExpression:
@@ -2683,7 +2690,8 @@ 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.Assignment, SymbolFlags.None);
const symbol = declareSymbol(file.symbol.exports!, file.symbol, node, flags | SymbolFlags.Assignment, SymbolFlags.None);
setValueDeclaration(symbol, node);
}
function bindThisPropertyAssignment(node: BindablePropertyAssignmentExpression | PropertyAccessExpression | LiteralLikeElementAccessExpression) {
@@ -2781,6 +2789,10 @@ namespace ts {
function bindObjectDefinePrototypeProperty(node: BindableObjectDefinePropertyCall) {
const namespaceSymbol = lookupSymbolForPropertyAccess((node.arguments[0] as PropertyAccessExpression).expression as EntityNameExpression);
if (namespaceSymbol) {
// Ensure the namespace symbol becomes class-like
addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, SymbolFlags.Class);
}
bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
}
@@ -2862,7 +2874,7 @@ namespace ts {
}
});
}
if (containerIsClass && namespaceSymbol) {
if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, SymbolFlags.Class);
}
return namespaceSymbol;
+2 -35
View File
@@ -251,6 +251,7 @@ namespace ts {
state.seenAffectedFiles = createMap<true>();
}
state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit;
return state;
}
@@ -1118,7 +1119,7 @@ namespace ts {
const state: ReusableBuilderProgramState = {
fileInfos,
compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath),
compilerOptions: convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && arrayToMap(program.semanticDiagnosticsPerFile, value => toPath(isString(value) ? value : value[0]), value => isString(value) ? emptyArray : value[1]),
@@ -1156,40 +1157,6 @@ namespace ts {
}
}
function convertFromReusableCompilerOptions(options: CompilerOptions, toAbsolutePath: (path: string) => string) {
const result: CompilerOptions = {};
const optionsNameMap = getOptionNameMap().optionNameMap;
for (const name in options) {
if (hasProperty(options, name)) {
result[name] = convertFromReusableCompilerOptionValue(
optionsNameMap.get(name.toLowerCase()),
options[name] as CompilerOptionsValue,
toAbsolutePath
);
}
}
if (result.configFilePath) {
result.configFilePath = toAbsolutePath(result.configFilePath);
}
return result;
}
function convertFromReusableCompilerOptionValue(option: CommandLineOption | undefined, value: CompilerOptionsValue, toAbsolutePath: (path: string) => string) {
if (option) {
if (option.type === "list") {
const values = value as readonly (string | number)[];
if (option.element.isFilePath && values.length) {
return values.map(toAbsolutePath);
}
}
else if (option.isFilePath) {
return toAbsolutePath(value as string);
}
}
return value;
}
export function createRedirectedBuilderProgram(state: { program: Program | undefined; compilerOptions: CompilerOptions; }, configFileParsingDiagnostics: readonly Diagnostic[]): BuilderProgram {
return {
getState: notImplemented,
+396 -253
View File
File diff suppressed because it is too large Load Diff
+61 -123
View File
@@ -216,6 +216,15 @@ namespace ts {
isCommandLineOnly: true,
description: Diagnostics.Print_the_final_configuration_instead_of_building
},
{
name: "listFilesOnly",
type: "boolean",
category: Diagnostics.Command_line_Options,
affectsSemanticDiagnostics: true,
affectsEmit: true,
isCommandLineOnly: true,
description: Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
},
// Basic
{
@@ -1227,7 +1236,7 @@ namespace ts {
}
/*@internal*/
export function parseBuildCommand(args: string[]): ParsedBuildCommand {
export function parseBuildCommand(args: readonly string[]): ParsedBuildCommand {
let buildOptionNameMap: OptionNameMap | undefined;
const returnBuildOptionNameMap = () => (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(buildOpts)));
const { options, fileNames: projects, errors } = parseCommandLineWorker(returnBuildOptionNameMap, [
@@ -1258,125 +1267,12 @@ namespace ts {
return { buildOptions, projects, errors };
}
function getDiagnosticText(_message: DiagnosticMessage, ..._args: any[]): string {
/* @internal */
export function getDiagnosticText(_message: DiagnosticMessage, ..._args: any[]): string {
const diagnostic = createCompilerDiagnostic.apply(undefined, arguments);
return <string>diagnostic.messageText;
}
/* @internal */
export function printVersion() {
sys.write(getDiagnosticText(Diagnostics.Version_0, version) + sys.newLine);
}
/* @internal */
export function printHelp(optionsList: readonly CommandLineOption[], syntaxPrefix = "") {
const output: string[] = [];
// We want to align our "syntax" and "examples" commands to a certain margin.
const syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length;
const examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length;
let marginLength = Math.max(syntaxLength, examplesLength);
// Build up the syntactic skeleton.
let syntax = makePadding(marginLength - syntaxLength);
syntax += `tsc ${syntaxPrefix}[${getDiagnosticText(Diagnostics.options)}] [${getDiagnosticText(Diagnostics.file)}...]`;
output.push(getDiagnosticText(Diagnostics.Syntax_Colon_0, syntax));
output.push(sys.newLine + sys.newLine);
// Build up the list of examples.
const padding = makePadding(marginLength);
output.push(getDiagnosticText(Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + sys.newLine);
output.push(padding + "tsc --outFile file.js file.ts" + sys.newLine);
output.push(padding + "tsc @args.txt" + sys.newLine);
output.push(padding + "tsc --build tsconfig.json" + sys.newLine);
output.push(sys.newLine);
output.push(getDiagnosticText(Diagnostics.Options_Colon) + sys.newLine);
// We want our descriptions to align at the same column in our output,
// so we keep track of the longest option usage string.
marginLength = 0;
const usageColumn: string[] = []; // Things like "-d, --declaration" go in here.
const descriptionColumn: string[] = [];
const optionsDescriptionMap = createMap<string[]>(); // Map between option.description and list of option.type if it is a kind
for (const option of optionsList) {
// If an option lacks a description,
// it is not officially supported.
if (!option.description) {
continue;
}
let usageText = " ";
if (option.shortName) {
usageText += "-" + option.shortName;
usageText += getParamType(option);
usageText += ", ";
}
usageText += "--" + option.name;
usageText += getParamType(option);
usageColumn.push(usageText);
let description: string;
if (option.name === "lib") {
description = getDiagnosticText(option.description);
const element = (<CommandLineOptionOfListType>option).element;
const typeMap = <Map<number | string>>element.type;
optionsDescriptionMap.set(description, arrayFrom(typeMap.keys()).map(key => `'${key}'`));
}
else {
description = getDiagnosticText(option.description);
}
descriptionColumn.push(description);
// Set the new margin for the description column if necessary.
marginLength = Math.max(usageText.length, marginLength);
}
// Special case that can't fit in the loop.
const usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">";
usageColumn.push(usageText);
descriptionColumn.push(getDiagnosticText(Diagnostics.Insert_command_line_options_and_files_from_a_file));
marginLength = Math.max(usageText.length, marginLength);
// Print out each row, aligning all the descriptions on the same column.
for (let i = 0; i < usageColumn.length; i++) {
const usage = usageColumn[i];
const description = descriptionColumn[i];
const kindsList = optionsDescriptionMap.get(description);
output.push(usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine);
if (kindsList) {
output.push(makePadding(marginLength + 4));
for (const kind of kindsList) {
output.push(kind + " ");
}
output.push(sys.newLine);
}
}
for (const line of output) {
sys.write(line);
}
return;
function getParamType(option: CommandLineOption) {
if (option.paramType !== undefined) {
return " " + getDiagnosticText(option.paramType);
}
return "";
}
function makePadding(paddingLength: number): string {
return Array(paddingLength + 1).join(" ");
}
}
export type DiagnosticReporter = (diagnostic: Diagnostic) => void;
/**
* Reports config file diagnostics
@@ -1801,6 +1697,12 @@ namespace ts {
references: readonly ProjectReference[] | undefined;
}
/** @internal */
export interface ConvertToTSConfigHost {
getCurrentDirectory(): string;
useCaseSensitiveFileNames: boolean;
}
/**
* Generate an uncommented, complete tsconfig for use with "--showConfig"
* @param configParseResult options to be generated into tsconfig.json
@@ -1808,7 +1710,7 @@ namespace ts {
* @param host provides current directory and case sensitivity services
*/
/** @internal */
export function convertToTSConfig(configParseResult: ParsedCommandLine, configFileName: string, host: { getCurrentDirectory(): string, useCaseSensitiveFileNames: boolean }): TSConfig {
export function convertToTSConfig(configParseResult: ParsedCommandLine, configFileName: string, host: ConvertToTSConfigHost): TSConfig {
const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
const files = map(
filter(
@@ -1816,7 +1718,8 @@ namespace ts {
(!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? _ => true : matchesSpecs(
configFileName,
configParseResult.configFileSpecs.validatedIncludeSpecs,
configParseResult.configFileSpecs.validatedExcludeSpecs
configParseResult.configFileSpecs.validatedExcludeSpecs,
host,
)
),
f => getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName)
@@ -1854,11 +1757,11 @@ namespace ts {
return specs;
}
function matchesSpecs(path: string, includeSpecs: readonly string[] | undefined, excludeSpecs: readonly string[] | undefined): (path: string) => boolean {
function matchesSpecs(path: string, includeSpecs: readonly string[] | undefined, excludeSpecs: readonly string[] | undefined, host: ConvertToTSConfigHost): (path: string) => boolean {
if (!includeSpecs) return _ => true;
const patterns = getFileMatcherPatterns(path, excludeSpecs, includeSpecs, sys.useCaseSensitiveFileNames, sys.getCurrentDirectory());
const excludeRe = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, sys.useCaseSensitiveFileNames);
const includeRe = patterns.includeFilePattern && getRegexFromPattern(patterns.includeFilePattern, sys.useCaseSensitiveFileNames);
const patterns = getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
const excludeRe = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
const includeRe = patterns.includeFilePattern && getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
if (includeRe) {
if (excludeRe) {
return path => !(includeRe.test(path) && !excludeRe.test(path));
@@ -2041,6 +1944,41 @@ namespace ts {
}
}
/* @internal */
export function convertToOptionsWithAbsolutePaths(options: CompilerOptions, toAbsolutePath: (path: string) => string) {
const result: CompilerOptions = {};
const optionsNameMap = getOptionNameMap().optionNameMap;
for (const name in options) {
if (hasProperty(options, name)) {
result[name] = convertToOptionValueWithAbsolutePaths(
optionsNameMap.get(name.toLowerCase()),
options[name] as CompilerOptionsValue,
toAbsolutePath
);
}
}
if (result.configFilePath) {
result.configFilePath = toAbsolutePath(result.configFilePath);
}
return result;
}
function convertToOptionValueWithAbsolutePaths(option: CommandLineOption | undefined, value: CompilerOptionsValue, toAbsolutePath: (path: string) => string) {
if (option) {
if (option.type === "list") {
const values = value as readonly (string | number)[];
if (option.element.isFilePath && values.length) {
return values.map(toAbsolutePath);
}
}
else if (option.isFilePath) {
return toAbsolutePath(value as string);
}
}
return value;
}
/**
* Parse the contents of a config file (tsconfig.json).
* @param json The contents of the config file to parse
@@ -2604,7 +2542,7 @@ namespace ts {
function normalizeNonListOptionValue(option: CommandLineOption, basePath: string, value: any): CompilerOptionsValue {
if (option.isFilePath) {
value = normalizePath(combinePaths(basePath, value));
value = getNormalizedAbsolutePath(value, basePath);
if (value === "") {
value = ".";
}
+34 -227
View File
@@ -42,6 +42,12 @@ namespace ts {
clear(): void;
}
/* @internal */
export interface MapConstructor {
// eslint-disable-next-line @typescript-eslint/prefer-function-type
new <T>(): Map<T>;
}
/** ES6 Iterator type. */
export interface Iterator<T> {
next(): { value: T, done?: false } | { value: never, done: true };
@@ -66,28 +72,40 @@ namespace ts {
}
}
/* @internal */
namespace ts {
// Natives
// NOTE: This must be declared in a separate block from the one below so that we don't collide with the exported definition of `Map`.
declare const Map: (new <T>() => Map<T>) | undefined;
/**
* Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
*/
export function tryGetNativeMap(): MapConstructor | undefined {
// Internet Explorer's Map doesn't support iteration, so don't use it.
// eslint-disable-next-line no-in-operator
return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined;
}
}
/* @internal */
namespace ts {
export const emptyArray: never[] = [] as never[];
/** Create a MapLike with good performance. */
function createDictionaryObject<T>(): MapLike<T> {
const map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null
export const Map: MapConstructor = tryGetNativeMap() || (() => {
// NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
if (typeof createMapShim === "function") {
return createMapShim();
}
throw new Error("TypeScript requires an environment that provides a compatible native Map implementation.");
})();
// Using 'delete' on an object causes V8 to put the object in dictionary mode.
// This disables creation of hidden classes, which are expensive when an object is
// constantly changing shape.
map.__ = undefined;
delete map.__;
return map;
}
/** Create a new map. If a template object is provided, the map will copy entries from it. */
/** Create a new map. */
export function createMap<T>(): Map<T> {
return new MapCtr<T>();
return new Map<T>();
}
/** Create a new map from an array of entries. */
export function createMapFromEntries<T>(entries: [string, T][]): Map<T> {
const map = createMap<T>();
for (const [key, value] of entries) {
@@ -96,8 +114,9 @@ namespace ts {
return map;
}
/** Create a new map from a template object is provided, the map will copy entries from it. */
export function createMapFromTemplate<T>(template: MapLike<T>): Map<T> {
const map: Map<T> = new MapCtr<T>();
const map: Map<T> = new Map<T>();
// Copies keys/values from template. Note that for..in will not throw if
// template is undefined, and instead will just exit the loop.
@@ -110,204 +129,6 @@ namespace ts {
return map;
}
// The global Map object. This may not be available, so we must test for it.
declare const Map: (new <T>() => Map<T>) | undefined;
// Internet Explorer's Map doesn't support iteration, so don't use it.
// eslint-disable-next-line no-in-operator
export const MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap();
// Keep the class inside a function so it doesn't get compiled if it's not used.
export function shimMap(): new <T>() => Map<T> {
interface MapEntry<T> {
readonly key?: string;
value?: T;
// Linked list references for iterators.
nextEntry?: MapEntry<T>;
previousEntry?: MapEntry<T>;
/**
* Specifies if iterators should skip the next entry.
* This will be set when an entry is deleted.
* See https://github.com/Microsoft/TypeScript/pull/27292 for more information.
*/
skipNext?: boolean;
}
class MapIterator<T, U extends (string | T | [string, T])> {
private currentEntry?: MapEntry<T>;
private selector: (key: string, value: T) => U;
constructor(currentEntry: MapEntry<T>, selector: (key: string, value: T) => U) {
this.currentEntry = currentEntry;
this.selector = selector;
}
public next(): { value: U, done: false } | { value: never, done: true } {
// Navigate to the next entry.
while (this.currentEntry) {
const skipNext = !!this.currentEntry.skipNext;
this.currentEntry = this.currentEntry.nextEntry;
if (!skipNext) {
break;
}
}
if (this.currentEntry) {
return { value: this.selector(this.currentEntry.key!, this.currentEntry.value!), done: false };
}
else {
return { value: undefined as never, done: true };
}
}
}
return class <T> implements Map<T> {
private data = createDictionaryObject<MapEntry<T>>();
public size = 0;
// Linked list references for iterators.
// See https://github.com/Microsoft/TypeScript/pull/27292
// for more information.
/**
* The first entry in the linked list.
* Note that this is only a stub that serves as starting point
* for iterators and doesn't contain a key and a value.
*/
private readonly firstEntry: MapEntry<T>;
private lastEntry: MapEntry<T>;
constructor() {
// Create a first (stub) map entry that will not contain a key
// and value but serves as starting point for iterators.
this.firstEntry = {};
// When the map is empty, the last entry is the same as the
// first one.
this.lastEntry = this.firstEntry;
}
get(key: string): T | undefined {
const entry = this.data[key] as MapEntry<T> | undefined;
return entry && entry.value!;
}
set(key: string, value: T): this {
if (!this.has(key)) {
this.size++;
// Create a new entry that will be appended at the
// end of the linked list.
const newEntry: MapEntry<T> = {
key,
value
};
this.data[key] = newEntry;
// Adjust the references.
const previousLastEntry = this.lastEntry;
previousLastEntry.nextEntry = newEntry;
newEntry.previousEntry = previousLastEntry;
this.lastEntry = newEntry;
}
else {
this.data[key].value = value;
}
return this;
}
has(key: string): boolean {
// eslint-disable-next-line no-in-operator
return key in this.data;
}
delete(key: string): boolean {
if (this.has(key)) {
this.size--;
const entry = this.data[key];
delete this.data[key];
// Adjust the linked list references of the neighbor entries.
const previousEntry = entry.previousEntry!;
previousEntry.nextEntry = entry.nextEntry;
if (entry.nextEntry) {
entry.nextEntry.previousEntry = previousEntry;
}
// When the deleted entry was the last one, we need to
// adjust the lastEntry reference.
if (this.lastEntry === entry) {
this.lastEntry = previousEntry;
}
// Adjust the forward reference of the deleted entry
// in case an iterator still references it. This allows us
// to throw away the entry, but when an active iterator
// (which points to the current entry) continues, it will
// navigate to the entry that originally came before the
// current one and skip it.
entry.previousEntry = undefined;
entry.nextEntry = previousEntry;
entry.skipNext = true;
return true;
}
return false;
}
clear(): void {
this.data = createDictionaryObject<MapEntry<T>>();
this.size = 0;
// Reset the linked list. Note that we must adjust the forward
// references of the deleted entries to ensure iterators stuck
// in the middle of the list don't continue with deleted entries,
// but can continue with new entries added after the clear()
// operation.
const firstEntry = this.firstEntry;
let currentEntry = firstEntry.nextEntry;
while (currentEntry) {
const nextEntry = currentEntry.nextEntry;
currentEntry.previousEntry = undefined;
currentEntry.nextEntry = firstEntry;
currentEntry.skipNext = true;
currentEntry = nextEntry;
}
firstEntry.nextEntry = undefined;
this.lastEntry = firstEntry;
}
keys(): Iterator<string> {
return new MapIterator(this.firstEntry, key => key);
}
values(): Iterator<T> {
return new MapIterator(this.firstEntry, (_key, value) => value);
}
entries(): Iterator<[string, T]> {
return new MapIterator(this.firstEntry, (key, value) => [key, value] as [string, T]);
}
forEach(action: (value: T, key: string) => void): void {
const iterator = this.entries();
while (true) {
const iterResult = iterator.next();
if (iterResult.done) {
break;
}
const [key, value] = iterResult.value;
action(value, key);
}
}
};
}
export function length(array: readonly any[] | undefined): number {
return array ? array.length : 0;
}
@@ -2052,20 +1873,6 @@ namespace ts {
return str.indexOf(substring) !== -1;
}
export function fileExtensionIs(path: string, extension: string): boolean {
return path.length > extension.length && endsWith(path, extension);
}
export function fileExtensionIsOneOf(path: string, extensions: readonly string[]): boolean {
for (const extension of extensions) {
if (fileExtensionIs(path, extension)) {
return true;
}
}
return false;
}
/**
* Takes a string like "jquery-min.4.2.3" and returns "jquery"
*/
+49
View File
@@ -221,6 +221,40 @@ namespace ts {
let isDebugInfoEnabled = false;
interface ExtendedDebugModule {
init(_ts: typeof ts): void;
formatControlFlowGraph(flowNode: FlowNode): string;
}
let extendedDebugModule: ExtendedDebugModule | undefined;
function extendedDebug() {
enableDebugInfo();
if (!extendedDebugModule) {
throw new Error("Debugging helpers could not be loaded.");
}
return extendedDebugModule;
}
export function printControlFlowGraph(flowNode: FlowNode) {
return console.log(formatControlFlowGraph(flowNode));
}
export function formatControlFlowGraph(flowNode: FlowNode) {
return extendedDebug().formatControlFlowGraph(flowNode);
}
export function attachFlowNodeDebugInfo(flowNode: FlowNode) {
if (isDebugInfoEnabled) {
if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
Object.defineProperties(flowNode, {
__debugFlowFlags: { get(this: FlowNode) { return formatEnum(this.flags, (ts as any).FlowFlags, /*isFlags*/ true); } },
__debugToString: { value(this: FlowNode) { return formatControlFlowGraph(this); } }
});
}
}
}
/**
* Injects debug information into frequently used types.
*/
@@ -266,6 +300,21 @@ namespace ts {
}
}
// attempt to load extended debugging information
try {
if (sys && sys.require) {
const basePath = getDirectoryPath(resolvePath(sys.getExecutingFilePath()));
const result = sys.require(basePath, "./compiler-debug") as RequireResult<ExtendedDebugModule>;
if (!result.error) {
result.module.init(ts);
extendedDebugModule = result.module;
}
}
}
catch {
// do nothing
}
isDebugInfoEnabled = true;
}
+18 -6
View File
@@ -71,7 +71,7 @@
"category": "Error",
"code": 1022
},
"An index signature parameter type must be 'string' or 'number'.": {
"An index signature parameter type must be either 'string' or 'number'.": {
"category": "Error",
"code": 1023
},
@@ -903,7 +903,7 @@
"category": "Error",
"code": 1322
},
"Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'.": {
"Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'.": {
"category": "Error",
"code": 1323
},
@@ -1043,6 +1043,10 @@
"category": "Error",
"code": 1358
},
"Identifier expected. '{0}' is a reserved word that cannot be used here.": {
"category": "Error",
"code": 1359
},
"The types of '{0}' are incompatible between these types.": {
"category": "Error",
@@ -1557,10 +1561,6 @@
"category": "Error",
"code": 2423
},
"Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.": {
"category": "Error",
"code": 2424
},
"Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.": {
"category": "Error",
"code": 2425
@@ -2249,6 +2249,14 @@
"category": "Error",
"code": 2612
},
"Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?": {
"category": "Error",
"code": 2613
},
"Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?": {
"category": "Error",
"code": 2614
},
"Cannot augment module '{0}' with value exports because it resolves to a non-module entity.": {
"category": "Error",
@@ -4303,6 +4311,10 @@
"category": "Message",
"code": 6502
},
"Print names of files that are part of the compilation and then stop processing.": {
"category": "Message",
"code": 6503
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
+3 -1
View File
@@ -393,7 +393,9 @@ namespace ts {
declarationFilePath: string | undefined,
declarationMapPath: string | undefined,
relativeToBuildInfo: (path: string) => string) {
if (!sourceFileOrBundle || !declarationFilePath) {
if (!sourceFileOrBundle) return;
if (!declarationFilePath) {
if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) emitSkipped = true;
return;
}
const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
+15 -6
View File
@@ -1065,7 +1065,9 @@ namespace ts {
}
export function updatePropertyAccess(node: PropertyAccessExpression, expression: Expression, name: Identifier) {
Debug.assert(!(node.flags & NodeFlags.OptionalChain), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead.");
if (isOptionalChain(node)) {
return updatePropertyAccessChain(node, expression, node.questionDotToken, name);
}
// Because we are updating existed propertyAccess we want to inherit its emitFlags
// instead of using the default from createPropertyAccess
return node.expression !== expression
@@ -1103,7 +1105,9 @@ namespace ts {
}
export function updateElementAccess(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression) {
Debug.assert(!(node.flags & NodeFlags.OptionalChain), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead.");
if (isOptionalChain(node)) {
return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
}
return node.expression !== expression
|| node.argumentExpression !== argumentExpression
? updateNode(createElementAccess(expression, argumentExpression), node)
@@ -1137,7 +1141,9 @@ namespace ts {
}
export function updateCall(node: CallExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[]) {
Debug.assert(!(node.flags & NodeFlags.OptionalChain), "Cannot update a CallChain using updateCall. Use updateCallChain instead.");
if (isOptionalChain(node)) {
return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
}
return node.expression !== expression
|| node.typeArguments !== typeArguments
|| node.arguments !== argumentsArray
@@ -1805,7 +1811,7 @@ namespace ts {
const node = <ForOfStatement>createSynthesizedNode(SyntaxKind.ForOfStatement);
node.awaitModifier = awaitModifier;
node.initializer = initializer;
node.expression = expression;
node.expression = isCommaSequence(expression) ? createParen(expression) : expression;
node.statement = asEmbeddedStatement(statement);
return node;
}
@@ -2974,7 +2980,10 @@ namespace ts {
(texts || (texts = [])).push(prependNode);
break;
case BundleFileSectionKind.Internal:
if (stripInternal) break;
if (stripInternal) {
if (!texts) texts = [];
break;
}
// falls through
case BundleFileSectionKind.Text:
@@ -4730,7 +4739,7 @@ namespace ts {
const conditionalPrecedence = getOperatorPrecedence(SyntaxKind.ConditionalExpression, SyntaxKind.QuestionToken);
const emittedCondition = skipPartiallyEmittedExpressions(condition);
const conditionPrecedence = getExpressionPrecedence(emittedCondition);
if (compareValues(conditionPrecedence, conditionalPrecedence) === Comparison.LessThan) {
if (compareValues(conditionPrecedence, conditionalPrecedence) !== Comparison.GreaterThan) {
return createParen(condition);
}
return condition;
+5 -1
View File
@@ -317,9 +317,13 @@ namespace ts.moduleSpecifiers {
// If the module could be imported by a directory name, use that directory's name
const moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName);
const globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
// Get a path that's relative to node_modules or the importing file's path
// if node_modules folder is in this folder or any of its parent folders, no need to keep it.
if (!startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined;
const pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
if (!(startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
return undefined;
}
// If the module was found in @types, get the actual Node package name
const nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
+8 -1
View File
@@ -1401,7 +1401,14 @@ namespace ts {
// Only for end of file because the error gets reported incorrectly on embedded script tags.
const reportAtCurrentPosition = token() === SyntaxKind.EndOfFileToken;
return createMissingNode<Identifier>(SyntaxKind.Identifier, reportAtCurrentPosition, diagnosticMessage || Diagnostics.Identifier_expected);
const isReservedWord = scanner.isReservedWord();
const msgArg = scanner.getTokenText();
const defaultMessage = isReservedWord ?
Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
Diagnostics.Identifier_expected;
return createMissingNode<Identifier>(SyntaxKind.Identifier, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
}
function parseIdentifier(diagnosticMessage?: DiagnosticMessage): Identifier {
+855
View File
@@ -0,0 +1,855 @@
/* @internal */
namespace ts {
/**
* Internally, we represent paths as strings with '/' as the directory separator.
* When we make system calls (eg: LanguageServiceHost.getDirectory()),
* we expect the host to correctly handle paths in our specified format.
*/
export const directorySeparator = "/";
const altDirectorySeparator = "\\";
const urlSchemeSeparator = "://";
const backslashRegExp = /\\/g;
//// Path Tests
/**
* Determines whether a charCode corresponds to `/` or `\`.
*/
export function isAnyDirectorySeparator(charCode: number): boolean {
return charCode === CharacterCodes.slash || charCode === CharacterCodes.backslash;
}
/**
* Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
*/
export function isUrl(path: string) {
return getEncodedRootLength(path) < 0;
}
/**
* Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
* like `c:`, `c:\` or `c:/`).
*/
export function isRootedDiskPath(path: string) {
return getEncodedRootLength(path) > 0;
}
/**
* Determines whether a path consists only of a path root.
*/
export function isDiskPathRoot(path: string) {
const rootLength = getEncodedRootLength(path);
return rootLength > 0 && rootLength === path.length;
}
/**
* Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
*
* ```ts
* // POSIX
* pathIsAbsolute("/path/to/file.ext") === true
* // DOS
* pathIsAbsolute("c:/path/to/file.ext") === true
* // URL
* pathIsAbsolute("file:///path/to/file.ext") === true
* // Non-absolute
* pathIsAbsolute("path/to/file.ext") === false
* pathIsAbsolute("./path/to/file.ext") === false
* ```
*/
export function pathIsAbsolute(path: string): boolean {
return getEncodedRootLength(path) !== 0;
}
/**
* Determines whether a path starts with a relative path component (i.e. `.` or `..`).
*/
export function pathIsRelative(path: string): boolean {
return /^\.\.?($|[\\/])/.test(path);
}
export function hasExtension(fileName: string): boolean {
return stringContains(getBaseFileName(fileName), ".");
}
export function fileExtensionIs(path: string, extension: string): boolean {
return path.length > extension.length && endsWith(path, extension);
}
export function fileExtensionIsOneOf(path: string, extensions: readonly string[]): boolean {
for (const extension of extensions) {
if (fileExtensionIs(path, extension)) {
return true;
}
}
return false;
}
/**
* Determines whether a path has a trailing separator (`/` or `\\`).
*/
export function hasTrailingDirectorySeparator(path: string) {
return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
}
//// Path Parsing
function isVolumeCharacter(charCode: number) {
return (charCode >= CharacterCodes.a && charCode <= CharacterCodes.z) ||
(charCode >= CharacterCodes.A && charCode <= CharacterCodes.Z);
}
function getFileUrlVolumeSeparatorEnd(url: string, start: number) {
const ch0 = url.charCodeAt(start);
if (ch0 === CharacterCodes.colon) return start + 1;
if (ch0 === CharacterCodes.percent && url.charCodeAt(start + 1) === CharacterCodes._3) {
const ch2 = url.charCodeAt(start + 2);
if (ch2 === CharacterCodes.a || ch2 === CharacterCodes.A) return start + 3;
}
return -1;
}
/**
* Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
* If the root is part of a URL, the twos-complement of the root length is returned.
*/
function getEncodedRootLength(path: string): number {
if (!path) return 0;
const ch0 = path.charCodeAt(0);
// POSIX or UNC
if (ch0 === CharacterCodes.slash || ch0 === CharacterCodes.backslash) {
if (path.charCodeAt(1) !== ch0) return 1; // POSIX: "/" (or non-normalized "\")
const p1 = path.indexOf(ch0 === CharacterCodes.slash ? directorySeparator : altDirectorySeparator, 2);
if (p1 < 0) return path.length; // UNC: "//server" or "\\server"
return p1 + 1; // UNC: "//server/" or "\\server\"
}
// DOS
if (isVolumeCharacter(ch0) && path.charCodeAt(1) === CharacterCodes.colon) {
const ch2 = path.charCodeAt(2);
if (ch2 === CharacterCodes.slash || ch2 === CharacterCodes.backslash) return 3; // DOS: "c:/" or "c:\"
if (path.length === 2) return 2; // DOS: "c:" (but not "c:d")
}
// URL
const schemeEnd = path.indexOf(urlSchemeSeparator);
if (schemeEnd !== -1) {
const authorityStart = schemeEnd + urlSchemeSeparator.length;
const authorityEnd = path.indexOf(directorySeparator, authorityStart);
if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
// For local "file" URLs, include the leading DOS volume (if present).
// Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
// special case interpreted as "the machine from which the URL is being interpreted".
const scheme = path.slice(0, schemeEnd);
const authority = path.slice(authorityStart, authorityEnd);
if (scheme === "file" && (authority === "" || authority === "localhost") &&
isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
if (volumeSeparatorEnd !== -1) {
if (path.charCodeAt(volumeSeparatorEnd) === CharacterCodes.slash) {
// URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
return ~(volumeSeparatorEnd + 1);
}
if (volumeSeparatorEnd === path.length) {
// URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
// but not "file:///c:d" or "file:///c%3ad"
return ~volumeSeparatorEnd;
}
}
}
return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
}
return ~path.length; // URL: "file://server", "http://server"
}
// relative
return 0;
}
/**
* Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
*
* For example:
* ```ts
* getRootLength("a") === 0 // ""
* getRootLength("/") === 1 // "/"
* getRootLength("c:") === 2 // "c:"
* getRootLength("c:d") === 0 // ""
* getRootLength("c:/") === 3 // "c:/"
* getRootLength("c:\\") === 3 // "c:\\"
* getRootLength("//server") === 7 // "//server"
* getRootLength("//server/share") === 8 // "//server/"
* getRootLength("\\\\server") === 7 // "\\\\server"
* getRootLength("\\\\server\\share") === 8 // "\\\\server\\"
* getRootLength("file:///path") === 8 // "file:///"
* getRootLength("file:///c:") === 10 // "file:///c:"
* getRootLength("file:///c:d") === 8 // "file:///"
* getRootLength("file:///c:/path") === 11 // "file:///c:/"
* getRootLength("file://server") === 13 // "file://server"
* getRootLength("file://server/path") === 14 // "file://server/"
* getRootLength("http://server") === 13 // "http://server"
* getRootLength("http://server/path") === 14 // "http://server/"
* ```
*/
export function getRootLength(path: string) {
const rootLength = getEncodedRootLength(path);
return rootLength < 0 ? ~rootLength : rootLength;
}
/**
* Returns the path except for its basename. Semantics align with NodeJS's `path.dirname`
* except that we support URLs as well.
*
* ```ts
* // POSIX
* getDirectoryPath("/path/to/file.ext") === "/path/to"
* getDirectoryPath("/path/to/") === "/path"
* getDirectoryPath("/") === "/"
* // DOS
* getDirectoryPath("c:/path/to/file.ext") === "c:/path/to"
* getDirectoryPath("c:/path/to/") === "c:/path"
* getDirectoryPath("c:/") === "c:/"
* getDirectoryPath("c:") === "c:"
* // URL
* getDirectoryPath("http://typescriptlang.org/path/to/file.ext") === "http://typescriptlang.org/path/to"
* getDirectoryPath("http://typescriptlang.org/path/to") === "http://typescriptlang.org/path"
* getDirectoryPath("http://typescriptlang.org/") === "http://typescriptlang.org/"
* getDirectoryPath("http://typescriptlang.org") === "http://typescriptlang.org"
* ```
*/
export function getDirectoryPath(path: Path): Path;
/**
* Returns the path except for its basename. Semantics align with NodeJS's `path.dirname`
* except that we support URLs as well.
*
* ```ts
* // POSIX
* getDirectoryPath("/path/to/file.ext") === "/path/to"
* getDirectoryPath("/path/to/") === "/path"
* getDirectoryPath("/") === "/"
* // DOS
* getDirectoryPath("c:/path/to/file.ext") === "c:/path/to"
* getDirectoryPath("c:/path/to/") === "c:/path"
* getDirectoryPath("c:/") === "c:/"
* getDirectoryPath("c:") === "c:"
* // URL
* getDirectoryPath("http://typescriptlang.org/path/to/file.ext") === "http://typescriptlang.org/path/to"
* getDirectoryPath("http://typescriptlang.org/path/to") === "http://typescriptlang.org/path"
* getDirectoryPath("http://typescriptlang.org/") === "http://typescriptlang.org/"
* getDirectoryPath("http://typescriptlang.org") === "http://typescriptlang.org"
* getDirectoryPath("file://server/path/to/file.ext") === "file://server/path/to"
* getDirectoryPath("file://server/path/to") === "file://server/path"
* getDirectoryPath("file://server/") === "file://server/"
* getDirectoryPath("file://server") === "file://server"
* getDirectoryPath("file:///path/to/file.ext") === "file:///path/to"
* getDirectoryPath("file:///path/to") === "file:///path"
* getDirectoryPath("file:///") === "file:///"
* getDirectoryPath("file://") === "file://"
* ```
*/
export function getDirectoryPath(path: string): string;
export function getDirectoryPath(path: string): string {
path = normalizeSlashes(path);
// If the path provided is itself the root, then return it.
const rootLength = getRootLength(path);
if (rootLength === path.length) return path;
// return the leading portion of the path up to the last (non-terminal) directory separator
// but not including any trailing directory separator.
path = removeTrailingDirectorySeparator(path);
return path.slice(0, Math.max(rootLength, path.lastIndexOf(directorySeparator)));
}
/**
* Returns the path except for its containing directory name.
* Semantics align with NodeJS's `path.basename` except that we support URL's as well.
*
* ```ts
* // POSIX
* getBaseFileName("/path/to/file.ext") === "file.ext"
* getBaseFileName("/path/to/") === "to"
* getBaseFileName("/") === ""
* // DOS
* getBaseFileName("c:/path/to/file.ext") === "file.ext"
* getBaseFileName("c:/path/to/") === "to"
* getBaseFileName("c:/") === ""
* getBaseFileName("c:") === ""
* // URL
* getBaseFileName("http://typescriptlang.org/path/to/file.ext") === "file.ext"
* getBaseFileName("http://typescriptlang.org/path/to/") === "to"
* getBaseFileName("http://typescriptlang.org/") === ""
* getBaseFileName("http://typescriptlang.org") === ""
* getBaseFileName("file://server/path/to/file.ext") === "file.ext"
* getBaseFileName("file://server/path/to/") === "to"
* getBaseFileName("file://server/") === ""
* getBaseFileName("file://server") === ""
* getBaseFileName("file:///path/to/file.ext") === "file.ext"
* getBaseFileName("file:///path/to/") === "to"
* getBaseFileName("file:///") === ""
* getBaseFileName("file://") === ""
* ```
*/
export function getBaseFileName(path: string): string;
/**
* Gets the portion of a path following the last (non-terminal) separator (`/`).
* Semantics align with NodeJS's `path.basename` except that we support URL's as well.
* If the base name has any one of the provided extensions, it is removed.
*
* ```ts
* getBaseFileName("/path/to/file.ext", ".ext", true) === "file"
* getBaseFileName("/path/to/file.js", ".ext", true) === "file.js"
* getBaseFileName("/path/to/file.js", [".ext", ".js"], true) === "file"
* getBaseFileName("/path/to/file.ext", ".EXT", false) === "file.ext"
* ```
*/
export function getBaseFileName(path: string, extensions: string | readonly string[], ignoreCase: boolean): string;
export function getBaseFileName(path: string, extensions?: string | readonly string[], ignoreCase?: boolean) {
path = normalizeSlashes(path);
// if the path provided is itself the root, then it has not file name.
const rootLength = getRootLength(path);
if (rootLength === path.length) return "";
// return the trailing portion of the path starting after the last (non-terminal) directory
// separator but not including any trailing directory separator.
path = removeTrailingDirectorySeparator(path);
const name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(directorySeparator) + 1));
const extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
return extension ? name.slice(0, name.length - extension.length) : name;
}
function tryGetExtensionFromPath(path: string, extension: string, stringEqualityComparer: (a: string, b: string) => boolean) {
if (!startsWith(extension, ".")) extension = "." + extension;
if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === CharacterCodes.dot) {
const pathExtension = path.slice(path.length - extension.length);
if (stringEqualityComparer(pathExtension, extension)) {
return pathExtension;
}
}
}
function getAnyExtensionFromPathWorker(path: string, extensions: string | readonly string[], stringEqualityComparer: (a: string, b: string) => boolean) {
if (typeof extensions === "string") {
return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
}
for (const extension of extensions) {
const result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
if (result) return result;
}
return "";
}
/**
* Gets the file extension for a path.
*
* ```ts
* getAnyExtensionFromPath("/path/to/file.ext") === ".ext"
* getAnyExtensionFromPath("/path/to/file.ext/") === ".ext"
* getAnyExtensionFromPath("/path/to/file") === ""
* getAnyExtensionFromPath("/path/to.ext/file") === ""
* ```
*/
export function getAnyExtensionFromPath(path: string): string;
/**
* Gets the file extension for a path, provided it is one of the provided extensions.
*
* ```ts
* getAnyExtensionFromPath("/path/to/file.ext", ".ext", true) === ".ext"
* getAnyExtensionFromPath("/path/to/file.js", ".ext", true) === ""
* getAnyExtensionFromPath("/path/to/file.js", [".ext", ".js"], true) === ".js"
* getAnyExtensionFromPath("/path/to/file.ext", ".EXT", false) === ""
*/
export function getAnyExtensionFromPath(path: string, extensions: string | readonly string[], ignoreCase: boolean): string;
export function getAnyExtensionFromPath(path: string, extensions?: string | readonly string[], ignoreCase?: boolean): string {
// Retrieves any string from the final "." onwards from a base file name.
// Unlike extensionFromPath, which throws an exception on unrecognized extensions.
if (extensions) {
return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive);
}
const baseFileName = getBaseFileName(path);
const extensionIndex = baseFileName.lastIndexOf(".");
if (extensionIndex >= 0) {
return baseFileName.substring(extensionIndex);
}
return "";
}
function pathComponents(path: string, rootLength: number) {
const root = path.substring(0, rootLength);
const rest = path.substring(rootLength).split(directorySeparator);
if (rest.length && !lastOrUndefined(rest)) rest.pop();
return [root, ...rest];
}
/**
* Parse a path into an array containing a root component (at index 0) and zero or more path
* components (at indices > 0). The result is not normalized.
* If the path is relative, the root component is `""`.
* If the path is absolute, the root component includes the first path separator (`/`).
*
* ```ts
* // POSIX
* getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
* getPathComponents("/path/to/") === ["/", "path", "to"]
* getPathComponents("/") === ["/"]
* // DOS
* getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
* getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
* getPathComponents("c:/") === ["c:/"]
* getPathComponents("c:") === ["c:"]
* // URL
* getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
* getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
* getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
* getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
* getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
* getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
* getPathComponents("file://server/") === ["file://server/"]
* getPathComponents("file://server") === ["file://server"]
* getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
* getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
* getPathComponents("file:///") === ["file:///"]
* getPathComponents("file://") === ["file://"]
*/
export function getPathComponents(path: string, currentDirectory = "") {
path = combinePaths(currentDirectory, path);
return pathComponents(path, getRootLength(path));
}
//// Path Formatting
/**
* Formats a parsed path consisting of a root component (at index 0) and zero or more path
* segments (at indices > 0).
*
* ```ts
* getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
* ```
*/
export function getPathFromPathComponents(pathComponents: readonly string[]) {
if (pathComponents.length === 0) return "";
const root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
return root + pathComponents.slice(1).join(directorySeparator);
}
//// Path Normalization
/**
* Normalize path separators, converting `\` into `/`.
*/
export function normalizeSlashes(path: string): string {
return path.replace(backslashRegExp, directorySeparator);
}
/**
* Reduce an array of path components to a more simplified path by navigating any
* `"."` or `".."` entries in the path.
*/
export function reducePathComponents(components: readonly string[]) {
if (!some(components)) return [];
const reduced = [components[0]];
for (let i = 1; i < components.length; i++) {
const component = components[i];
if (!component) continue;
if (component === ".") continue;
if (component === "..") {
if (reduced.length > 1) {
if (reduced[reduced.length - 1] !== "..") {
reduced.pop();
continue;
}
}
else if (reduced[0]) continue;
}
reduced.push(component);
}
return reduced;
}
/**
* Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
*
* ```ts
* // Non-rooted
* combinePaths("path", "to", "file.ext") === "path/to/file.ext"
* combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
* // POSIX
* combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
* combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
* // DOS
* combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
* combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
* // URL
* combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
* combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
* ```
*/
export function combinePaths(path: string, ...paths: (string | undefined)[]): string {
if (path) path = normalizeSlashes(path);
for (let relativePath of paths) {
if (!relativePath) continue;
relativePath = normalizeSlashes(relativePath);
if (!path || getRootLength(relativePath) !== 0) {
path = relativePath;
}
else {
path = ensureTrailingDirectorySeparator(path) + relativePath;
}
}
return path;
}
/**
* Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
* `.` and `..` path components are resolved. Trailing directory separators are preserved.
*
* ```ts
* resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
* resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
* resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
* ```
*/
export function resolvePath(path: string, ...paths: (string | undefined)[]): string {
return normalizePath(some(paths) ? combinePaths(path, ...paths) : normalizeSlashes(path));
}
/**
* Parse a path into an array containing a root component (at index 0) and zero or more path
* components (at indices > 0). The result is normalized.
* If the path is relative, the root component is `""`.
* If the path is absolute, the root component includes the first path separator (`/`).
*
* ```ts
* getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
*/
export function getNormalizedPathComponents(path: string, currentDirectory: string | undefined) {
return reducePathComponents(getPathComponents(path, currentDirectory));
}
export function getNormalizedAbsolutePath(fileName: string, currentDirectory: string | undefined) {
return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
}
export function normalizePath(path: string): string {
path = normalizeSlashes(path);
const normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
}
function getPathWithoutRoot(pathComponents: readonly string[]) {
if (pathComponents.length === 0) return "";
return pathComponents.slice(1).join(directorySeparator);
}
export function getNormalizedAbsolutePathWithoutRoot(fileName: string, currentDirectory: string | undefined) {
return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
}
export function toPath(fileName: string, basePath: string | undefined, getCanonicalFileName: (path: string) => string): Path {
const nonCanonicalizedPath = isRootedDiskPath(fileName)
? normalizePath(fileName)
: getNormalizedAbsolutePath(fileName, basePath);
return <Path>getCanonicalFileName(nonCanonicalizedPath);
}
export function normalizePathAndParts(path: string): { path: string, parts: string[] } {
path = normalizeSlashes(path);
const [root, ...parts] = reducePathComponents(getPathComponents(path));
if (parts.length) {
const joinedParts = root + parts.join(directorySeparator);
return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts };
}
else {
return { path: root, parts };
}
}
//// Path Mutation
/**
* Removes a trailing directory separator from a path, if it does not already have one.
*
* ```ts
* removeTrailingDirectorySeparator("/path/to/file.ext") === "/path/to/file.ext"
* removeTrailingDirectorySeparator("/path/to/file.ext/") === "/path/to/file.ext"
* ```
*/
export function removeTrailingDirectorySeparator(path: Path): Path;
export function removeTrailingDirectorySeparator(path: string): string;
export function removeTrailingDirectorySeparator(path: string) {
if (hasTrailingDirectorySeparator(path)) {
return path.substr(0, path.length - 1);
}
return path;
}
/**
* Adds a trailing directory separator to a path, if it does not already have one.
*
* ```ts
* ensureTrailingDirectorySeparator("/path/to/file.ext") === "/path/to/file.ext/"
* ensureTrailingDirectorySeparator("/path/to/file.ext/") === "/path/to/file.ext/"
* ```
*/
export function ensureTrailingDirectorySeparator(path: Path): Path;
export function ensureTrailingDirectorySeparator(path: string): string;
export function ensureTrailingDirectorySeparator(path: string) {
if (!hasTrailingDirectorySeparator(path)) {
return path + directorySeparator;
}
return path;
}
/**
* Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
* with `./` or `../`) so as not to be confused with an unprefixed module name.
*
* ```ts
* ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
* ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
* ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
* ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
* ```
*/
export function ensurePathIsNonModuleName(path: string): string {
return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
}
/**
* Changes the extension of a path to the provided extension.
*
* ```ts
* changeAnyExtension("/path/to/file.ext", ".js") === "/path/to/file.js"
* ```
*/
export function changeAnyExtension(path: string, ext: string): string;
/**
* Changes the extension of a path to the provided extension if it has one of the provided extensions.
*
* ```ts
* changeAnyExtension("/path/to/file.ext", ".js", ".ext") === "/path/to/file.js"
* changeAnyExtension("/path/to/file.ext", ".js", ".ts") === "/path/to/file.ext"
* changeAnyExtension("/path/to/file.ext", ".js", [".ext", ".ts"]) === "/path/to/file.js"
* ```
*/
export function changeAnyExtension(path: string, ext: string, extensions: string | readonly string[], ignoreCase: boolean): string;
export function changeAnyExtension(path: string, ext: string, extensions?: string | readonly string[], ignoreCase?: boolean) {
const pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path;
}
//// Path Comparisons
// check path for these segments: '', '.'. '..'
const relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
function comparePathsWorker(a: string, b: string, componentComparer: (a: string, b: string) => Comparison) {
if (a === b) return Comparison.EqualTo;
if (a === undefined) return Comparison.LessThan;
if (b === undefined) return Comparison.GreaterThan;
// NOTE: Performance optimization - shortcut if the root segments differ as there would be no
// need to perform path reduction.
const aRoot = a.substring(0, getRootLength(a));
const bRoot = b.substring(0, getRootLength(b));
const result = compareStringsCaseInsensitive(aRoot, bRoot);
if (result !== Comparison.EqualTo) {
return result;
}
// NOTE: Performance optimization - shortcut if there are no relative path segments in
// the non-root portion of the path
const aRest = a.substring(aRoot.length);
const bRest = b.substring(bRoot.length);
if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
return componentComparer(aRest, bRest);
}
// The path contains a relative path segment. Normalize the paths and perform a slower component
// by component comparison.
const aComponents = reducePathComponents(getPathComponents(a));
const bComponents = reducePathComponents(getPathComponents(b));
const sharedLength = Math.min(aComponents.length, bComponents.length);
for (let i = 1; i < sharedLength; i++) {
const result = componentComparer(aComponents[i], bComponents[i]);
if (result !== Comparison.EqualTo) {
return result;
}
}
return compareValues(aComponents.length, bComponents.length);
}
/**
* Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
*/
export function comparePathsCaseSensitive(a: string, b: string) {
return comparePathsWorker(a, b, compareStringsCaseSensitive);
}
/**
* Performs a case-insensitive comparison of two paths.
*/
export function comparePathsCaseInsensitive(a: string, b: string) {
return comparePathsWorker(a, b, compareStringsCaseInsensitive);
}
/**
* Compare two paths using the provided case sensitivity.
*/
export function comparePaths(a: string, b: string, ignoreCase?: boolean): Comparison;
export function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison;
export function comparePaths(a: string, b: string, currentDirectory?: string | boolean, ignoreCase?: boolean) {
if (typeof currentDirectory === "string") {
a = combinePaths(currentDirectory, a);
b = combinePaths(currentDirectory, b);
}
else if (typeof currentDirectory === "boolean") {
ignoreCase = currentDirectory;
}
return comparePathsWorker(a, b, getStringComparer(ignoreCase));
}
/**
* Determines whether a `parent` path contains a `child` path using the provide case sensitivity.
*/
export function containsPath(parent: string, child: string, ignoreCase?: boolean): boolean;
export function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean;
export function containsPath(parent: string, child: string, currentDirectory?: string | boolean, ignoreCase?: boolean) {
if (typeof currentDirectory === "string") {
parent = combinePaths(currentDirectory, parent);
child = combinePaths(currentDirectory, child);
}
else if (typeof currentDirectory === "boolean") {
ignoreCase = currentDirectory;
}
if (parent === undefined || child === undefined) return false;
if (parent === child) return true;
const parentComponents = reducePathComponents(getPathComponents(parent));
const childComponents = reducePathComponents(getPathComponents(child));
if (childComponents.length < parentComponents.length) {
return false;
}
const componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
for (let i = 0; i < parentComponents.length; i++) {
const equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer;
if (!equalityComparer(parentComponents[i], childComponents[i])) {
return false;
}
}
return true;
}
/**
* Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
* Comparison is case-sensitive between the canonical paths.
*
* @deprecated Use `containsPath` if possible.
*/
export function startsWithDirectory(fileName: string, directoryName: string, getCanonicalFileName: GetCanonicalFileName): boolean {
const canonicalFileName = getCanonicalFileName(fileName);
const canonicalDirectoryName = getCanonicalFileName(directoryName);
return startsWith(canonicalFileName, canonicalDirectoryName + "/") || startsWith(canonicalFileName, canonicalDirectoryName + "\\");
}
//// Relative Paths
export function getPathComponentsRelativeTo(from: string, to: string, stringEqualityComparer: (a: string, b: string) => boolean, getCanonicalFileName: GetCanonicalFileName) {
const fromComponents = reducePathComponents(getPathComponents(from));
const toComponents = reducePathComponents(getPathComponents(to));
let start: number;
for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
const fromComponent = getCanonicalFileName(fromComponents[start]);
const toComponent = getCanonicalFileName(toComponents[start]);
const comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer;
if (!comparer(fromComponent, toComponent)) break;
}
if (start === 0) {
return toComponents;
}
const components = toComponents.slice(start);
const relative: string[] = [];
for (; start < fromComponents.length; start++) {
relative.push("..");
}
return ["", ...relative, ...components];
}
/**
* Gets a relative path that can be used to traverse between `from` and `to`.
*/
export function getRelativePathFromDirectory(from: string, to: string, ignoreCase: boolean): string;
/**
* Gets a relative path that can be used to traverse between `from` and `to`.
*/
export function getRelativePathFromDirectory(fromDirectory: string, to: string, getCanonicalFileName: GetCanonicalFileName): string; // eslint-disable-line @typescript-eslint/unified-signatures
export function getRelativePathFromDirectory(fromDirectory: string, to: string, getCanonicalFileNameOrIgnoreCase: GetCanonicalFileName | boolean) {
Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
const getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity;
const ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
const pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName);
return getPathFromPathComponents(pathComponents);
}
export function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string {
return !isRootedDiskPath(absoluteOrRelativePath)
? absoluteOrRelativePath
: getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
}
export function getRelativePathFromFile(from: string, to: string, getCanonicalFileName: GetCanonicalFileName) {
return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
}
export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: GetCanonicalFileName, isAbsolutePathAnUrl: boolean) {
const pathComponents = getPathComponentsRelativeTo(
resolvePath(currentDirectory, directoryPathOrUrl),
resolvePath(currentDirectory, relativeOrAbsolutePath),
equateStringsCaseSensitive,
getCanonicalFileName
);
const firstComponent = pathComponents[0];
if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
const prefix = firstComponent.charAt(0) === directorySeparator ? "file://" : "file:///";
pathComponents[0] = prefix + firstComponent;
}
return getPathFromPathComponents(pathComponents);
}
//// Path Traversal
/**
* Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result.
*/
export function forEachAncestorDirectory<T>(directory: Path, callback: (directory: Path) => T | undefined): T | undefined;
export function forEachAncestorDirectory<T>(directory: string, callback: (directory: string) => T | undefined): T | undefined;
export function forEachAncestorDirectory<T>(directory: Path, callback: (directory: Path) => T | undefined): T | undefined {
while (true) {
const result = callback(directory);
if (result !== undefined) {
return result;
}
const parentPath = getDirectoryPath(directory);
if (parentPath === directory) {
return undefined;
}
directory = parentPath;
}
}
}
-2
View File
@@ -38,6 +38,4 @@ namespace ts {
/** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
export const perfLogger: PerfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
const args = typeof process === "undefined" ? [] : process.argv;
perfLogger.logInfoEvent(`Starting TypeScript v${versionMajorMinor} with command line: ${JSON.stringify(args)}`);
}
+4 -5
View File
@@ -545,6 +545,9 @@ namespace ts {
return resolutions;
}
/* @internal */
export const inferredTypesContainingFile = "__inferred type names__.ts";
interface DiagnosticCache<T extends Diagnostic> {
perFile?: Map<T[]>;
allDiagnostics?: Diagnostic[];
@@ -875,7 +878,7 @@ namespace ts {
if (typeReferences.length) {
// This containingFilename needs to match with the one used in managed-side
const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
const containingFilename = combinePaths(containingDirectory, "__inferred type names__.ts");
const containingFilename = combinePaths(containingDirectory, inferredTypesContainingFile);
const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
for (let i = 0; i < typeReferences.length; i++) {
processTypeReferenceDirective(typeReferences[i], resolutions[i]);
@@ -2926,10 +2929,6 @@ namespace ts {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
}
if (options.noEmit && isIncrementalCompilation(options)) {
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite");
}
verifyProjectReferences();
// List of collected files is complete; validate exhautiveness if this is a project with a file list
+5
View File
@@ -669,6 +669,11 @@ namespace ts {
// Mark the file as needing re-evaluation of module resolution instead of using it blindly.
resolution.isInvalidated = true;
(filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = createMap<true>())).set(containingFilePath, true);
// When its a file with inferred types resolution, invalidate type reference directive resolution
if (containingFilePath.endsWith(inferredTypesContainingFile)) {
resolutionHost.onChangedAutomaticTypeDirectiveNames();
}
}
});
});
+11
View File
@@ -682,6 +682,7 @@ namespace ts {
/*@internal*/ bufferFrom?(input: string, encoding?: string): Buffer;
// For testing
/*@internal*/ now?(): Date;
/*@internal*/ require?(baseDir: string, moduleName: string): RequireResult;
}
export interface FileWatcher {
@@ -876,6 +877,15 @@ namespace ts {
bufferFrom,
base64decode: input => bufferFrom(input, "base64").toString("utf8"),
base64encode: input => bufferFrom(input).toString("base64"),
require: (baseDir, moduleName) => {
try {
const modulePath = resolveJSModule(moduleName, baseDir, nodeSystem);
return { module: require(modulePath), modulePath, error: undefined };
}
catch (error) {
return { module: undefined, modulePath: undefined, error };
}
}
};
return nodeSystem;
@@ -1022,6 +1032,7 @@ namespace ts {
return watchDirectoryUsingFsWatch;
}
// defer watchDirectoryRecursively as it depends on `ts.createMap()` which may not be usable yet.
const watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ?
createWatchDirectoryUsing(fsWatchFile) :
tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ?
+2 -2
View File
@@ -132,7 +132,7 @@ namespace ts {
// Create a temporary variable to store a computed property name (if necessary).
// If it's not inlineable, then we emit an expression after the class which assigns
// the property name to the temporary variable.
const expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer);
const expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields);
if (expr && !isSimpleInlineableExpression(expr)) {
(pendingExpressions || (pendingExpressions = [])).push(expr);
}
@@ -145,7 +145,7 @@ namespace ts {
}
const savedPendingExpressions = pendingExpressions;
pendingExpressions = undefined!;
pendingExpressions = undefined;
const extendsClauseElement = getEffectiveBaseTypeNode(node);
const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword);
@@ -285,6 +285,7 @@ namespace ts {
let combinedStatements: NodeArray<Statement>;
if (isSourceFileJS(currentSourceFile)) {
combinedStatements = createNodeArray(transformDeclarationsForJS(node));
refs.forEach(referenceVisitor);
emittedImports = filter(combinedStatements, isAnyImportSyntax);
}
else {
+9 -15
View File
@@ -1788,31 +1788,25 @@ namespace ts {
let reportQueue = true;
let successfulProjects = 0;
let errorProjects = 0;
while (true) {
const invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
if (!invalidatedProject) break;
reportQueue = false;
invalidatedProject.done(cancellationToken);
if (state.diagnostics.has(invalidatedProject.projectPath)) {
errorProjects++;
}
else {
successfulProjects++;
}
if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++;
}
disableCache(state);
reportErrorSummary(state, buildOrder);
startWatching(state, buildOrder);
return isCircularBuildOrder(buildOrder) ?
ExitStatus.ProjectReferenceCycle_OutputsSkupped :
errorProjects ?
successfulProjects ?
ExitStatus.DiagnosticsPresent_OutputsGenerated :
ExitStatus.DiagnosticsPresent_OutputsSkipped :
ExitStatus.Success;
return isCircularBuildOrder(buildOrder)
? ExitStatus.ProjectReferenceCycle_OutputsSkipped
: !buildOrder.some(p => state.diagnostics.has(toResolvedConfigFilePath(state, p)))
? ExitStatus.Success
: successfulProjects
? ExitStatus.DiagnosticsPresent_OutputsGenerated
: ExitStatus.DiagnosticsPresent_OutputsSkipped;
}
function clean(state: SolutionBuilderState, project?: string, onlyReferences?: boolean) {
@@ -1821,7 +1815,7 @@ namespace ts {
if (isCircularBuildOrder(buildOrder)) {
reportErrors(state, buildOrder.circularDiagnostics);
return ExitStatus.ProjectReferenceCycle_OutputsSkupped;
return ExitStatus.ProjectReferenceCycle_OutputsSkipped;
}
const { options, host } = state;
+4 -1
View File
@@ -4,7 +4,9 @@
"outFile": "../../built/local/compiler.js"
},
"references": [],
"references": [
{ "path": "../shims" },
],
"files": [
"core.ts",
@@ -15,6 +17,7 @@
"types.ts",
"sys.ts",
"path.ts",
"diagnosticInformationMap.generated.ts",
"scanner.ts",
"utilities.ts",
+4 -1
View File
@@ -4,5 +4,8 @@
"outFile": "../../built/local/compiler.release.js",
"removeComments": true,
"preserveConstEnums": false
}
},
"references": [
{ "path": "../shims" }
]
}
+43 -8
View File
@@ -2250,12 +2250,14 @@ namespace ts {
parent: CaseBlock;
expression: Expression;
statements: NodeArray<Statement>;
/* @internal */ fallthroughFlowNode?: FlowNode;
}
export interface DefaultClause extends Node {
kind: SyntaxKind.DefaultClause;
parent: CaseBlock;
statements: NodeArray<Statement>;
/* @internal */ fallthroughFlowNode?: FlowNode;
}
export type CaseOrDefaultClause = CaseClause | DefaultClause;
@@ -2681,6 +2683,7 @@ namespace ts {
isArrayType?: boolean;
}
// NOTE: Ensure this is up-to-date with src/debug/debug.ts
export const enum FlowFlags {
Unreachable = 1 << 0, // Unreachable code
Start = 1 << 1, // Start of flow graph
@@ -3258,6 +3261,9 @@ namespace ts {
InvalidProject_OutputsSkipped = 3,
// When build is skipped because project references form cycle
ProjectReferenceCycle_OutputsSkipped = 4,
/** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
ProjectReferenceCycle_OutputsSkupped = 4,
}
@@ -3365,8 +3371,10 @@ namespace ts {
getFullyQualifiedName(symbol: Symbol): string;
getAugmentedPropertiesOfType(type: Type): Symbol[];
getRootSymbols(symbol: Symbol): readonly Symbol[];
getContextualType(node: Expression): Type | undefined;
/* @internal */ getContextualType(node: Expression, contextFlags?: ContextFlags): Type | undefined; // eslint-disable-line @typescript-eslint/unified-signatures
/* @internal */ getContextualTypeForObjectLiteralElement(element: ObjectLiteralElementLike): Type | undefined;
/* @internal */ getContextualTypeForArgumentAtIndex(call: CallLikeExpression, argIndex: number): Type | undefined;
/* @internal */ getContextualTypeForJsxAttribute(attribute: JsxAttribute | JsxSpreadAttribute): Type | undefined;
@@ -3443,8 +3451,7 @@ namespace ts {
resolvedReturnType: Type,
typePredicate: TypePredicate | undefined,
minArgumentCount: number,
hasRestParameter: boolean,
hasLiteralTypes: boolean,
flags: SignatureFlags
): Signature;
/* @internal */ createSymbol(flags: SymbolFlags, name: __String): TransientSymbol;
/* @internal */ createIndexInfo(type: Type, isReadonly: boolean, declaration?: SignatureDeclaration): IndexInfo;
@@ -3526,6 +3533,14 @@ namespace ts {
Subtype
}
/* @internal */
export const enum ContextFlags {
None = 0,
Signature = 1 << 0, // Obtaining contextual signature
NoConstraints = 1 << 1, // Don't obtain type variable constraints
Completion = 1 << 2, // Obtaining constraint type for completion
}
// NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
export const enum NodeBuilderFlags {
None = 0,
@@ -4655,7 +4670,22 @@ namespace ts {
Construct,
}
/* @internal */
export const enum SignatureFlags {
None = 0,
HasRestParameter = 1 << 0, // Indicates last parameter is rest parameter
HasLiteralTypes = 1 << 1, // Indicates signature is specialized
IsOptionalCall = 1 << 2, // Indicates signature comes from a CallChain
// We do not propagate `IsOptionalCall` to instantiated signatures, as that would result in us
// attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
// instantiating the return type.
PropagatingFlags = HasRestParameter | HasLiteralTypes,
}
export interface Signature {
/* @internal */ flags: SignatureFlags;
/* @internal */ checker?: TypeChecker;
declaration?: SignatureDeclaration | JSDocSignature; // Originating declaration
typeParameters?: readonly TypeParameter[]; // Type parameters (undefined if non-generic)
parameters: readonly Symbol[]; // Parameters
@@ -4672,10 +4702,6 @@ namespace ts {
/* @internal */
minArgumentCount: number; // Number of non-optional parameters
/* @internal */
hasRestParameter: boolean; // True if last parameter is rest parameter
/* @internal */
hasLiteralTypes: boolean; // True if specialized
/* @internal */
target?: Signature; // Instantiation target
/* @internal */
mapper?: TypeMapper; // Instantiation mapper
@@ -4686,11 +4712,11 @@ namespace ts {
/* @internal */
canonicalSignatureCache?: Signature; // Canonical version of signature (deferred)
/* @internal */
optionalCallSignatureCache?: Signature; // Optional chained call version of signature (deferred)
/* @internal */
isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison
/* @internal */
instantiations?: Map<Signature>; // Generic signature instantiation cache
/* @internal */
isOptionalCall?: boolean;
}
export const enum IndexKind {
@@ -4935,6 +4961,7 @@ namespace ts {
lib?: string[];
/*@internal*/listEmittedFiles?: boolean;
/*@internal*/listFiles?: boolean;
/*@internal*/listFilesOnly?: boolean;
locale?: string;
mapRoot?: string;
maxNodeModuleJsDepth?: number;
@@ -5123,6 +5150,11 @@ namespace ts {
/* @internal */ spec: ConfigFileSpecs;
}
/* @internal */
export type RequireResult<T = {}> =
| { module: T, modulePath?: string, error: undefined }
| { module: undefined, modulePath?: undefined, error: { stack?: string, message?: string } };
export interface CreateProgramOptions {
rootNames: readonly string[];
options: CompilerOptions;
@@ -6149,6 +6181,8 @@ namespace ts {
readFile?(path: string): string | undefined;
/* @internal */
getProbableSymlinks?(files: readonly SourceFile[]): ReadonlyMap<string>;
/* @internal */
getGlobalTypingsCacheLocation?(): string | undefined;
}
// Note: this used to be deprecated in our public API, but is still used internally
@@ -6418,6 +6452,7 @@ namespace ts {
readonly disableSuggestions?: boolean;
readonly quotePreference?: "auto" | "double" | "single";
readonly includeCompletionsForModuleExports?: boolean;
readonly includeAutomaticOptionalChainCompletions?: boolean;
readonly includeCompletionsWithInsertText?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
+54 -646
View File
@@ -36,7 +36,7 @@ namespace ts {
/** Create a new escaped identifier map. */
export function createUnderscoreEscapedMap<T>(): UnderscoreEscapedMap<T> {
return new MapCtr<T>() as UnderscoreEscapedMap<T>;
return new Map<T>() as UnderscoreEscapedMap<T>;
}
export function hasEntries(map: ReadonlyUnderscoreEscapedMap<any> | undefined): map is ReadonlyUnderscoreEscapedMap<any> {
@@ -94,13 +94,6 @@ namespace ts {
};
}
export function toPath(fileName: string, basePath: string | undefined, getCanonicalFileName: (path: string) => string): Path {
const nonCanonicalizedPath = isRootedDiskPath(fileName)
? normalizePath(fileName)
: getNormalizedAbsolutePath(fileName, basePath);
return <Path>getCanonicalFileName(nonCanonicalizedPath);
}
export function changesAffectModuleResolution(oldOptions: CompilerOptions, newOptions: CompilerOptions): boolean {
return oldOptions.configFilePath !== newOptions.configFilePath ||
optionsHaveModuleResolutionChanges(oldOptions, newOptions);
@@ -968,6 +961,11 @@ namespace ts {
break;
case SyntaxKind.ArrowFunction:
return getErrorSpanForArrowFunction(sourceFile, <ArrowFunction>node);
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
const start = skipTrivia(sourceFile.text, (<CaseOrDefaultClause>node).pos);
const end = (<CaseOrDefaultClause>node).statements.length > 0 ? (<CaseOrDefaultClause>node).statements[0].pos : (<CaseOrDefaultClause>node).end;
return createTextSpanFromBounds(start, end);
}
if (errorNode === undefined) {
@@ -1821,9 +1819,9 @@ namespace ts {
* exactly one argument (of the form 'require("name")').
* This function does not test if the node is in a JavaScript file or not.
*/
export function isRequireCall(callExpression: Node, checkArgumentIsStringLiteralLike: true): callExpression is RequireOrImportCall & { expression: Identifier, arguments: [StringLiteralLike] };
export function isRequireCall(callExpression: Node, checkArgumentIsStringLiteralLike: boolean): callExpression is CallExpression;
export function isRequireCall(callExpression: Node, checkArgumentIsStringLiteralLike: boolean): callExpression is CallExpression {
export function isRequireCall(callExpression: Node, requireStringLiteralLikeArgument: true): callExpression is RequireOrImportCall & { expression: Identifier, arguments: [StringLiteralLike] };
export function isRequireCall(callExpression: Node, requireStringLiteralLikeArgument: boolean): callExpression is CallExpression;
export function isRequireCall(callExpression: Node, requireStringLiteralLikeArgument: boolean): callExpression is CallExpression {
if (callExpression.kind !== SyntaxKind.CallExpression) {
return false;
}
@@ -1837,7 +1835,7 @@ namespace ts {
return false;
}
const arg = args[0];
return !checkArgumentIsStringLiteralLike || isStringLiteralLike(arg);
return !requireStringLiteralLikeArgument || isStringLiteralLike(arg);
}
export function isSingleOrDoubleQuote(charCode: number) {
@@ -2060,7 +2058,7 @@ namespace ts {
idText(expr.expression.expression) === "Object" &&
idText(expr.expression.name) === "defineProperty" &&
isStringOrNumericLiteralLike(expr.arguments[1]) &&
isBindableStaticNameExpression(expr.arguments[0]);
isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
}
export function isBindableStaticElementAccessExpression(node: Node, excludeThisKeyword?: boolean): node is BindableStaticElementAccessExpression {
@@ -2174,9 +2172,11 @@ namespace ts {
nextToLast = nextToLast.expression as Exclude<BindableStaticNameExpression, Identifier>;
}
const id = nextToLast.expression;
if (id.escapedText === "exports" ||
id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") {
// exports.name = expr OR module.exports.name = expr
if ((id.escapedText === "exports" ||
id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
// ExportsProperty does not support binding with computed names
isBindableStaticAccessExpression(lhs)) {
// exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
return AssignmentDeclarationKind.ExportsProperty;
}
// F.G...x = expr
@@ -4179,6 +4179,23 @@ namespace ts {
return node.kind === SyntaxKind.Identifier || isPropertyAccessEntityNameExpression(node);
}
export function getFirstIdentifier(node: EntityNameOrEntityNameExpression): Identifier {
switch (node.kind) {
case SyntaxKind.Identifier:
return node;
case SyntaxKind.QualifiedName:
do {
node = node.left;
} while (node.kind !== SyntaxKind.Identifier);
return node;
case SyntaxKind.PropertyAccessExpression:
do {
node = node.expression;
} while (node.kind !== SyntaxKind.Identifier);
return node;
}
}
export function isDottedName(node: Expression): boolean {
return node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.ThisKeyword ||
node.kind === SyntaxKind.PropertyAccessExpression && isDottedName((<PropertyAccessExpression>node).expression) ||
@@ -4733,25 +4750,6 @@ namespace ts {
});
}
/** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */
export function forEachAncestorDirectory<T>(directory: Path, callback: (directory: Path) => T | undefined): T | undefined;
export function forEachAncestorDirectory<T>(directory: string, callback: (directory: string) => T | undefined): T | undefined;
export function forEachAncestorDirectory<T>(directory: Path, callback: (directory: Path) => T | undefined): T | undefined {
while (true) {
const result = callback(directory);
if (result !== undefined) {
return result;
}
const parentPath = getDirectoryPath(directory);
if (parentPath === directory) {
return undefined;
}
directory = parentPath;
}
}
// Return true if the given type is the constructor type for an abstract class
export function isAbstractConstructorType(type: Type): boolean {
return !!(getObjectFlags(type) & ObjectFlags.Anonymous) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
@@ -5906,9 +5904,19 @@ namespace ts {
}
export function isOptionalChain(node: Node): node is PropertyAccessChain | ElementAccessChain | CallChain {
return isPropertyAccessChain(node)
|| isElementAccessChain(node)
|| isCallChain(node);
const kind = node.kind;
return !!(node.flags & NodeFlags.OptionalChain) &&
(kind === SyntaxKind.PropertyAccessExpression
|| kind === SyntaxKind.ElementAccessExpression
|| kind === SyntaxKind.CallExpression);
}
/**
* Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
*/
/* @internal */
export function isExpressionOfOptionalChainRoot(node: Node): node is Expression & { parent: OptionalChainRoot } {
return isOptionalChainRoot(node.parent) && node.parent.expression === node;
}
export function isNewExpression(node: Node): node is NewExpression {
@@ -7310,7 +7318,7 @@ namespace ts {
getSourceFileConstructor(): new (kind: SyntaxKind.SourceFile, pos?: number, end?: number) => SourceFile;
getSymbolConstructor(): new (flags: SymbolFlags, name: __String) => Symbol;
getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type;
getSignatureConstructor(): new (checker: TypeChecker) => Signature;
getSignatureConstructor(): new (checker: TypeChecker, flags: SignatureFlags) => Signature;
getSourceMapSourceConstructor(): new (fileName: string, text: string, skipTrivia?: (pos: number) => number) => SourceMapSource;
}
@@ -7331,7 +7339,12 @@ namespace ts {
}
}
function Signature() {}
function Signature(this: Signature, checker: TypeChecker, flags: SignatureFlags) {
this.flags = flags;
if (Debug.isDebugging) {
this.checker = checker;
}
}
function Node(this: Node, kind: SyntaxKind, pos: number, end: number) {
this.pos = pos;
@@ -7635,294 +7648,6 @@ namespace ts {
return true;
}
/**
* Internally, we represent paths as strings with '/' as the directory separator.
* When we make system calls (eg: LanguageServiceHost.getDirectory()),
* we expect the host to correctly handle paths in our specified format.
*/
export const directorySeparator = "/";
const altDirectorySeparator = "\\";
const urlSchemeSeparator = "://";
const backslashRegExp = /\\/g;
/**
* Normalize path separators.
*/
export function normalizeSlashes(path: string): string {
return path.replace(backslashRegExp, directorySeparator);
}
function isVolumeCharacter(charCode: number) {
return (charCode >= CharacterCodes.a && charCode <= CharacterCodes.z) ||
(charCode >= CharacterCodes.A && charCode <= CharacterCodes.Z);
}
function getFileUrlVolumeSeparatorEnd(url: string, start: number) {
const ch0 = url.charCodeAt(start);
if (ch0 === CharacterCodes.colon) return start + 1;
if (ch0 === CharacterCodes.percent && url.charCodeAt(start + 1) === CharacterCodes._3) {
const ch2 = url.charCodeAt(start + 2);
if (ch2 === CharacterCodes.a || ch2 === CharacterCodes.A) return start + 3;
}
return -1;
}
/**
* Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
* If the root is part of a URL, the twos-complement of the root length is returned.
*/
function getEncodedRootLength(path: string): number {
if (!path) return 0;
const ch0 = path.charCodeAt(0);
// POSIX or UNC
if (ch0 === CharacterCodes.slash || ch0 === CharacterCodes.backslash) {
if (path.charCodeAt(1) !== ch0) return 1; // POSIX: "/" (or non-normalized "\")
const p1 = path.indexOf(ch0 === CharacterCodes.slash ? directorySeparator : altDirectorySeparator, 2);
if (p1 < 0) return path.length; // UNC: "//server" or "\\server"
return p1 + 1; // UNC: "//server/" or "\\server\"
}
// DOS
if (isVolumeCharacter(ch0) && path.charCodeAt(1) === CharacterCodes.colon) {
const ch2 = path.charCodeAt(2);
if (ch2 === CharacterCodes.slash || ch2 === CharacterCodes.backslash) return 3; // DOS: "c:/" or "c:\"
if (path.length === 2) return 2; // DOS: "c:" (but not "c:d")
}
// URL
const schemeEnd = path.indexOf(urlSchemeSeparator);
if (schemeEnd !== -1) {
const authorityStart = schemeEnd + urlSchemeSeparator.length;
const authorityEnd = path.indexOf(directorySeparator, authorityStart);
if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
// For local "file" URLs, include the leading DOS volume (if present).
// Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
// special case interpreted as "the machine from which the URL is being interpreted".
const scheme = path.slice(0, schemeEnd);
const authority = path.slice(authorityStart, authorityEnd);
if (scheme === "file" && (authority === "" || authority === "localhost") &&
isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
if (volumeSeparatorEnd !== -1) {
if (path.charCodeAt(volumeSeparatorEnd) === CharacterCodes.slash) {
// URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
return ~(volumeSeparatorEnd + 1);
}
if (volumeSeparatorEnd === path.length) {
// URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
// but not "file:///c:d" or "file:///c%3ad"
return ~volumeSeparatorEnd;
}
}
}
return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
}
return ~path.length; // URL: "file://server", "http://server"
}
// relative
return 0;
}
/**
* Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
*
* For example:
* ```ts
* getRootLength("a") === 0 // ""
* getRootLength("/") === 1 // "/"
* getRootLength("c:") === 2 // "c:"
* getRootLength("c:d") === 0 // ""
* getRootLength("c:/") === 3 // "c:/"
* getRootLength("c:\\") === 3 // "c:\\"
* getRootLength("//server") === 7 // "//server"
* getRootLength("//server/share") === 8 // "//server/"
* getRootLength("\\\\server") === 7 // "\\\\server"
* getRootLength("\\\\server\\share") === 8 // "\\\\server\\"
* getRootLength("file:///path") === 8 // "file:///"
* getRootLength("file:///c:") === 10 // "file:///c:"
* getRootLength("file:///c:d") === 8 // "file:///"
* getRootLength("file:///c:/path") === 11 // "file:///c:/"
* getRootLength("file://server") === 13 // "file://server"
* getRootLength("file://server/path") === 14 // "file://server/"
* getRootLength("http://server") === 13 // "http://server"
* getRootLength("http://server/path") === 14 // "http://server/"
* ```
*/
export function getRootLength(path: string) {
const rootLength = getEncodedRootLength(path);
return rootLength < 0 ? ~rootLength : rootLength;
}
// TODO(rbuckton): replace references with `resolvePath`
export function normalizePath(path: string): string {
return resolvePath(path);
}
export function normalizePathAndParts(path: string): { path: string, parts: string[] } {
path = normalizeSlashes(path);
const [root, ...parts] = reducePathComponents(getPathComponents(path));
if (parts.length) {
const joinedParts = root + parts.join(directorySeparator);
return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts };
}
else {
return { path: root, parts };
}
}
/**
* Returns the path except for its basename. Semantics align with NodeJS's `path.dirname`
* except that we support URLs as well.
*
* ```ts
* getDirectoryPath("/path/to/file.ext") === "/path/to"
* getDirectoryPath("/path/to/") === "/path"
* getDirectoryPath("/") === "/"
* ```
*/
export function getDirectoryPath(path: Path): Path;
/**
* Returns the path except for its basename. Semantics align with NodeJS's `path.dirname`
* except that we support URLs as well.
*
* ```ts
* getDirectoryPath("/path/to/file.ext") === "/path/to"
* getDirectoryPath("/path/to/") === "/path"
* getDirectoryPath("/") === "/"
* ```
*/
export function getDirectoryPath(path: string): string;
export function getDirectoryPath(path: string): string {
path = normalizeSlashes(path);
// If the path provided is itself the root, then return it.
const rootLength = getRootLength(path);
if (rootLength === path.length) return path;
// return the leading portion of the path up to the last (non-terminal) directory separator
// but not including any trailing directory separator.
path = removeTrailingDirectorySeparator(path);
return path.slice(0, Math.max(rootLength, path.lastIndexOf(directorySeparator)));
}
export function startsWithDirectory(fileName: string, directoryName: string, getCanonicalFileName: GetCanonicalFileName): boolean {
const canonicalFileName = getCanonicalFileName(fileName);
const canonicalDirectoryName = getCanonicalFileName(directoryName);
return startsWith(canonicalFileName, canonicalDirectoryName + "/") || startsWith(canonicalFileName, canonicalDirectoryName + "\\");
}
export function isUrl(path: string) {
return getEncodedRootLength(path) < 0;
}
export function pathIsRelative(path: string): boolean {
return /^\.\.?($|[\\/])/.test(path);
}
/**
* Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path
* like `c:`, `c:\` or `c:/`).
*/
export function isRootedDiskPath(path: string) {
return getEncodedRootLength(path) > 0;
}
/**
* Determines whether a path consists only of a path root.
*/
export function isDiskPathRoot(path: string) {
const rootLength = getEncodedRootLength(path);
return rootLength > 0 && rootLength === path.length;
}
export function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string {
return !isRootedDiskPath(absoluteOrRelativePath)
? absoluteOrRelativePath
: getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
}
function pathComponents(path: string, rootLength: number) {
const root = path.substring(0, rootLength);
const rest = path.substring(rootLength).split(directorySeparator);
if (rest.length && !lastOrUndefined(rest)) rest.pop();
return [root, ...rest];
}
/**
* Parse a path into an array containing a root component (at index 0) and zero or more path
* components (at indices > 0). The result is not normalized.
* If the path is relative, the root component is `""`.
* If the path is absolute, the root component includes the first path separator (`/`).
*/
export function getPathComponents(path: string, currentDirectory = "") {
path = combinePaths(currentDirectory, path);
const rootLength = getRootLength(path);
return pathComponents(path, rootLength);
}
/**
* Reduce an array of path components to a more simplified path by navigating any
* `"."` or `".."` entries in the path.
*/
export function reducePathComponents(components: readonly string[]) {
if (!some(components)) return [];
const reduced = [components[0]];
for (let i = 1; i < components.length; i++) {
const component = components[i];
if (!component) continue;
if (component === ".") continue;
if (component === "..") {
if (reduced.length > 1) {
if (reduced[reduced.length - 1] !== "..") {
reduced.pop();
continue;
}
}
else if (reduced[0]) continue;
}
reduced.push(component);
}
return reduced;
}
/**
* Parse a path into an array containing a root component (at index 0) and zero or more path
* components (at indices > 0). The result is normalized.
* If the path is relative, the root component is `""`.
* If the path is absolute, the root component includes the first path separator (`/`).
*/
export function getNormalizedPathComponents(path: string, currentDirectory: string | undefined) {
return reducePathComponents(getPathComponents(path, currentDirectory));
}
export function getNormalizedAbsolutePath(fileName: string, currentDirectory: string | undefined) {
return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
}
/**
* Formats a parsed path consisting of a root component (at index 0) and zero or more path
* segments (at indices > 0).
*/
export function getPathFromPathComponents(pathComponents: readonly string[]) {
if (pathComponents.length === 0) return "";
const root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
return root + pathComponents.slice(1).join(directorySeparator);
}
export function getNormalizedAbsolutePathWithoutRoot(fileName: string, currentDirectory: string | undefined) {
return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
}
function getPathWithoutRoot(pathComponents: readonly string[]) {
if (pathComponents.length === 0) return "";
return pathComponents.slice(1).join(directorySeparator);
}
export function discoverProbableSymlinks(files: readonly SourceFile[], getCanonicalFileName: GetCanonicalFileName, cwd: string): ReadonlyMap<string> {
const result = createMap<string>();
const symlinks = flatten<readonly [string, string]>(mapDefined(files, sf =>
@@ -7956,278 +7681,8 @@ namespace ts {
/* @internal */
namespace ts {
export function getPathComponentsRelativeTo(from: string, to: string, stringEqualityComparer: (a: string, b: string) => boolean, getCanonicalFileName: GetCanonicalFileName) {
const fromComponents = reducePathComponents(getPathComponents(from));
const toComponents = reducePathComponents(getPathComponents(to));
let start: number;
for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
const fromComponent = getCanonicalFileName(fromComponents[start]);
const toComponent = getCanonicalFileName(toComponents[start]);
const comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer;
if (!comparer(fromComponent, toComponent)) break;
}
if (start === 0) {
return toComponents;
}
const components = toComponents.slice(start);
const relative: string[] = [];
for (; start < fromComponents.length; start++) {
relative.push("..");
}
return ["", ...relative, ...components];
}
export function getRelativePathFromFile(from: string, to: string, getCanonicalFileName: GetCanonicalFileName) {
return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
}
/**
* Gets a relative path that can be used to traverse between `from` and `to`.
*/
export function getRelativePathFromDirectory(from: string, to: string, ignoreCase: boolean): string;
/**
* Gets a relative path that can be used to traverse between `from` and `to`.
*/
export function getRelativePathFromDirectory(fromDirectory: string, to: string, getCanonicalFileName: GetCanonicalFileName): string; // eslint-disable-line @typescript-eslint/unified-signatures
export function getRelativePathFromDirectory(fromDirectory: string, to: string, getCanonicalFileNameOrIgnoreCase: GetCanonicalFileName | boolean) {
Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
const getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity;
const ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
const pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName);
return getPathFromPathComponents(pathComponents);
}
export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: GetCanonicalFileName, isAbsolutePathAnUrl: boolean) {
const pathComponents = getPathComponentsRelativeTo(
resolvePath(currentDirectory, directoryPathOrUrl),
resolvePath(currentDirectory, relativeOrAbsolutePath),
equateStringsCaseSensitive,
getCanonicalFileName
);
const firstComponent = pathComponents[0];
if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
const prefix = firstComponent.charAt(0) === directorySeparator ? "file://" : "file:///";
pathComponents[0] = prefix + firstComponent;
}
return getPathFromPathComponents(pathComponents);
}
/**
* Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
* with `./` or `../`) so as not to be confused with an unprefixed module name.
*/
export function ensurePathIsNonModuleName(path: string): string {
return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path;
}
/**
* Returns the path except for its containing directory name.
* Semantics align with NodeJS's `path.basename` except that we support URL's as well.
*
* ```ts
* getBaseFileName("/path/to/file.ext") === "file.ext"
* getBaseFileName("/path/to/") === "to"
* getBaseFileName("/") === ""
* ```
*/
export function getBaseFileName(path: string): string;
/**
* Gets the portion of a path following the last (non-terminal) separator (`/`).
* Semantics align with NodeJS's `path.basename` except that we support URL's as well.
* If the base name has any one of the provided extensions, it is removed.
*
* ```ts
* getBaseFileName("/path/to/file.ext", ".ext", true) === "file"
* getBaseFileName("/path/to/file.js", ".ext", true) === "file.js"
* ```
*/
export function getBaseFileName(path: string, extensions: string | readonly string[], ignoreCase: boolean): string;
export function getBaseFileName(path: string, extensions?: string | readonly string[], ignoreCase?: boolean) {
path = normalizeSlashes(path);
// if the path provided is itself the root, then it has not file name.
const rootLength = getRootLength(path);
if (rootLength === path.length) return "";
// return the trailing portion of the path starting after the last (non-terminal) directory
// separator but not including any trailing directory separator.
path = removeTrailingDirectorySeparator(path);
const name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(directorySeparator) + 1));
const extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
return extension ? name.slice(0, name.length - extension.length) : name;
}
/**
* Combines paths. If a path is absolute, it replaces any previous path.
*/
export function combinePaths(path: string, ...paths: (string | undefined)[]): string {
if (path) path = normalizeSlashes(path);
for (let relativePath of paths) {
if (!relativePath) continue;
relativePath = normalizeSlashes(relativePath);
if (!path || getRootLength(relativePath) !== 0) {
path = relativePath;
}
else {
path = ensureTrailingDirectorySeparator(path) + relativePath;
}
}
return path;
}
/**
* Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
* `.` and `..` path components are resolved.
*/
export function resolvePath(path: string, ...paths: (string | undefined)[]): string {
const combined = some(paths) ? combinePaths(path, ...paths) : normalizeSlashes(path);
const normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined)));
return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized;
}
/**
* Determines whether a path has a trailing separator (`/` or `\\`).
*/
export function hasTrailingDirectorySeparator(path: string) {
if (path.length === 0) return false;
const ch = path.charCodeAt(path.length - 1);
return ch === CharacterCodes.slash || ch === CharacterCodes.backslash;
}
/**
* Removes a trailing directory separator from a path.
* @param path The path.
*/
export function removeTrailingDirectorySeparator(path: Path): Path;
export function removeTrailingDirectorySeparator(path: string): string;
export function removeTrailingDirectorySeparator(path: string) {
if (hasTrailingDirectorySeparator(path)) {
return path.substr(0, path.length - 1);
}
return path;
}
/**
* Adds a trailing directory separator to a path, if it does not already have one.
* @param path The path.
*/
export function ensureTrailingDirectorySeparator(path: Path): Path;
export function ensureTrailingDirectorySeparator(path: string): string;
export function ensureTrailingDirectorySeparator(path: string) {
if (!hasTrailingDirectorySeparator(path)) {
return path + directorySeparator;
}
return path;
}
// check path for these segments: '', '.'. '..'
const relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
function comparePathsWorker(a: string, b: string, componentComparer: (a: string, b: string) => Comparison) {
if (a === b) return Comparison.EqualTo;
if (a === undefined) return Comparison.LessThan;
if (b === undefined) return Comparison.GreaterThan;
// NOTE: Performance optimization - shortcut if the root segments differ as there would be no
// need to perform path reduction.
const aRoot = a.substring(0, getRootLength(a));
const bRoot = b.substring(0, getRootLength(b));
const result = compareStringsCaseInsensitive(aRoot, bRoot);
if (result !== Comparison.EqualTo) {
return result;
}
// NOTE: Performance optimization - shortcut if there are no relative path segments in
// the non-root portion of the path
const aRest = a.substring(aRoot.length);
const bRest = b.substring(bRoot.length);
if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
return componentComparer(aRest, bRest);
}
// The path contains a relative path segment. Normalize the paths and perform a slower component
// by component comparison.
const aComponents = reducePathComponents(getPathComponents(a));
const bComponents = reducePathComponents(getPathComponents(b));
const sharedLength = Math.min(aComponents.length, bComponents.length);
for (let i = 1; i < sharedLength; i++) {
const result = componentComparer(aComponents[i], bComponents[i]);
if (result !== Comparison.EqualTo) {
return result;
}
}
return compareValues(aComponents.length, bComponents.length);
}
/**
* Performs a case-sensitive comparison of two paths.
*/
export function comparePathsCaseSensitive(a: string, b: string) {
return comparePathsWorker(a, b, compareStringsCaseSensitive);
}
/**
* Performs a case-insensitive comparison of two paths.
*/
export function comparePathsCaseInsensitive(a: string, b: string) {
return comparePathsWorker(a, b, compareStringsCaseInsensitive);
}
export function comparePaths(a: string, b: string, ignoreCase?: boolean): Comparison;
export function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison;
export function comparePaths(a: string, b: string, currentDirectory?: string | boolean, ignoreCase?: boolean) {
if (typeof currentDirectory === "string") {
a = combinePaths(currentDirectory, a);
b = combinePaths(currentDirectory, b);
}
else if (typeof currentDirectory === "boolean") {
ignoreCase = currentDirectory;
}
return comparePathsWorker(a, b, getStringComparer(ignoreCase));
}
export function containsPath(parent: string, child: string, ignoreCase?: boolean): boolean;
export function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean;
export function containsPath(parent: string, child: string, currentDirectory?: string | boolean, ignoreCase?: boolean) {
if (typeof currentDirectory === "string") {
parent = combinePaths(currentDirectory, parent);
child = combinePaths(currentDirectory, child);
}
else if (typeof currentDirectory === "boolean") {
ignoreCase = currentDirectory;
}
if (parent === undefined || child === undefined) return false;
if (parent === child) return true;
const parentComponents = reducePathComponents(getPathComponents(parent));
const childComponents = reducePathComponents(getPathComponents(child));
if (childComponents.length < parentComponents.length) {
return false;
}
const componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive;
for (let i = 0; i < parentComponents.length; i++) {
const equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer;
if (!equalityComparer(parentComponents[i], childComponents[i])) {
return false;
}
}
return true;
}
function isDirectorySeparator(charCode: number): boolean {
return charCode === CharacterCodes.slash || charCode === CharacterCodes.backslash;
}
function stripLeadingDirectorySeparator(s: string): string | undefined {
return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
return isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
}
export function tryRemoveDirectoryPrefix(path: string, dirPath: string, getCanonicalFileName: GetCanonicalFileName): string | undefined {
@@ -8250,10 +7705,6 @@ namespace ts {
const wildcardCharCodes = [CharacterCodes.asterisk, CharacterCodes.question];
export function hasExtension(fileName: string): boolean {
return stringContains(getBaseFileName(fileName), ".");
}
export const commonPackageFolders: readonly string[] = ["node_modules", "bower_components", "jspm_packages"];
const implicitExcludePathRegexPattern = `(?!(${commonPackageFolders.join("|")})(/|$))`;
@@ -8718,13 +8169,6 @@ namespace ts {
return <T>changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
}
export function changeAnyExtension(path: string, ext: string): string;
export function changeAnyExtension(path: string, ext: string, extensions: string | readonly string[], ignoreCase: boolean): string;
export function changeAnyExtension(path: string, ext: string, extensions?: string | readonly string[], ignoreCase?: boolean) {
const pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path;
}
export function tryParsePattern(pattern: string): Pattern | undefined {
// This should be verified outside of here and a proper error thrown.
Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
@@ -8767,42 +8211,6 @@ namespace ts {
return find<Extension>(extensionsToRemove, e => fileExtensionIs(path, e));
}
function getAnyExtensionFromPathWorker(path: string, extensions: string | readonly string[], stringEqualityComparer: (a: string, b: string) => boolean) {
if (typeof extensions === "string") extensions = [extensions];
for (let extension of extensions) {
if (!startsWith(extension, ".")) extension = "." + extension;
if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") {
const pathExtension = path.slice(path.length - extension.length);
if (stringEqualityComparer(pathExtension, extension)) {
return pathExtension;
}
}
}
return "";
}
/**
* Gets the file extension for a path.
*/
export function getAnyExtensionFromPath(path: string): string;
/**
* Gets the file extension for a path, provided it is one of the provided extensions.
*/
export function getAnyExtensionFromPath(path: string, extensions: string | readonly string[], ignoreCase: boolean): string;
export function getAnyExtensionFromPath(path: string, extensions?: string | readonly string[], ignoreCase?: boolean): string {
// Retrieves any string from the final "." onwards from a base file name.
// Unlike extensionFromPath, which throws an exception on unrecognized extensions.
if (extensions) {
return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive);
}
const baseFileName = getBaseFileName(path);
const extensionIndex = baseFileName.lastIndexOf(".");
if (extensionIndex >= 0) {
return baseFileName.substring(extensionIndex);
}
return "";
}
export function isCheckJsEnabledForFile(sourceFile: SourceFile, compilerOptions: CompilerOptions) {
return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
}
+13 -6
View File
@@ -91,7 +91,7 @@ namespace ts {
/** Parses config file using System interface */
export function parseConfigFileWithSystem(configFileName: string, optionsToExtend: CompilerOptions, system: System, reportDiagnostic: DiagnosticReporter) {
const host: ParseConfigFileHost = <any>system;
host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(sys, reportDiagnostic, diagnostic);
host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic);
const result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host);
host.onUnRecoverableConfigFileDiagnostic = undefined!; // TODO: GH#18217
return result;
@@ -129,7 +129,7 @@ namespace ts {
}
export function listFiles(program: ProgramToEmitFilesAndReportErrors, writeFileName: (s: string) => void) {
if (program.getCompilerOptions().listFiles) {
if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) {
forEach(program.getSourceFiles(), file => {
writeFileName(file.fileName);
});
@@ -149,6 +149,8 @@ namespace ts {
emitOnlyDtsFiles?: boolean,
customTransformers?: CustomTransformers
) {
const isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
// First get and report any syntactic errors.
const diagnostics = program.getConfigFileParsingDiagnostics().slice();
const configFileParsingDiagnosticsLength = diagnostics.length;
@@ -158,15 +160,20 @@ namespace ts {
// semantic errors.
if (diagnostics.length === configFileParsingDiagnosticsLength) {
addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
if (diagnostics.length === configFileParsingDiagnosticsLength) {
addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
if (!isListFilesOnly) {
addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
if (diagnostics.length === configFileParsingDiagnosticsLength) {
addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
}
}
}
// Emit and report any errors we ran into.
const emitResult = program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
const emitResult = isListFilesOnly
? { emitSkipped: true, diagnostics: emptyArray }
: program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
const { emittedFiles, diagnostics: emitDiagnostics } = emitResult;
addRange(diagnostics, emitDiagnostics);
+499
View File
@@ -0,0 +1,499 @@
/// <reference lib="es2019" />
/* @internal */
namespace Debug {
interface Node {
kind: number;
}
type FunctionExpression = Node;
type ArrowFunction = Node;
type MethodDeclaration = Node;
type Expression = Node;
type SourceFile = Node;
interface SwitchStatement extends Node {
caseBlock: CaseBlock;
}
interface CaseBlock extends Node {
clauses: (CaseClause | DefaultClause)[];
}
interface CaseClause extends Node {
_caseclauseBrand: any;
expression: Expression;
}
interface DefaultClause extends Node {
_defaultClauseBrand: any;
}
interface TypeScriptModule {
readonly SyntaxKind: {
readonly CaseClause: number;
readonly DefaultClause: number;
};
readonly FlowFlags: {
readonly Unreachable: number,
readonly Start: number,
readonly BranchLabel: number,
readonly LoopLabel: number,
readonly Assignment: number,
readonly TrueCondition: number,
readonly FalseCondition: number,
readonly SwitchClause: number,
readonly ArrayMutation: number,
readonly Call: number,
readonly Referenced: number,
readonly Shared: number,
readonly PreFinally: number,
readonly AfterFinally: number,
readonly Label: number,
readonly Condition: number,
};
getSourceFileOfNode(node: Node): SourceFile;
getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node, includeTrivia?: boolean): string;
isDefaultClause(node: Node): node is DefaultClause;
}
type FlowNode =
| AfterFinallyFlow
| PreFinallyFlow
| FlowStart
| FlowLabel
| FlowAssignment
| FlowCall
| FlowCondition
| FlowSwitchClause
| FlowArrayMutation
;
interface FlowNodeBase {
flags: FlowFlags;
id?: number;
}
interface AfterFinallyFlow extends FlowNodeBase {
antecedent: FlowNode;
}
interface PreFinallyFlow extends FlowNodeBase {
antecedent: FlowNode;
}
interface FlowStart extends FlowNodeBase {
node?: FunctionExpression | ArrowFunction | MethodDeclaration;
}
interface FlowLabel extends FlowNodeBase {
antecedents: FlowNode[] | undefined;
}
interface FlowAssignment extends FlowNodeBase {
node: Expression;
antecedent: FlowNode;
}
interface FlowCall extends FlowNodeBase {
node: Expression;
antecedent: FlowNode;
}
interface FlowCondition extends FlowNodeBase {
node: Expression;
antecedent: FlowNode;
}
interface FlowSwitchClause extends FlowNodeBase {
switchStatement: SwitchStatement;
clauseStart: number;
clauseEnd: number;
antecedent: FlowNode;
}
interface FlowArrayMutation extends FlowNodeBase {
node: Expression;
antecedent: FlowNode;
}
type FlowFlags = number;
let FlowFlags: TypeScriptModule["FlowFlags"];
let getSourceFileOfNode: TypeScriptModule["getSourceFileOfNode"];
let getSourceTextOfNodeFromSourceFile: TypeScriptModule["getSourceTextOfNodeFromSourceFile"];
let isDefaultClause: TypeScriptModule["isDefaultClause"];
export function init(ts: TypeScriptModule) {
FlowFlags = ts.FlowFlags;
getSourceFileOfNode = ts.getSourceFileOfNode;
getSourceTextOfNodeFromSourceFile = ts.getSourceTextOfNodeFromSourceFile;
isDefaultClause = ts.isDefaultClause;
}
let nextDebugFlowId = -1;
function getDebugFlowNodeId(f: FlowNode) {
if (!f.id) {
f.id = nextDebugFlowId;
nextDebugFlowId--;
}
return f.id;
}
export function formatControlFlowGraph(flowNode: FlowNode) {
const enum BoxCharacter {
lr = "─",
ud = "│",
dr = "╭",
dl = "╮",
ul = "╯",
ur = "╰",
udr = "├",
udl = "┤",
dlr = "┬",
ulr = "┴",
udlr = "╫",
}
const enum Connection {
Up = 1 << 0,
Down = 1 << 1,
Left = 1 << 2,
Right = 1 << 3,
UpDown = Up | Down,
LeftRight = Left | Right,
UpLeft = Up | Left,
UpRight = Up | Right,
DownLeft = Down | Left,
DownRight = Down | Right,
UpDownLeft = UpDown | Left,
UpDownRight = UpDown | Right,
UpLeftRight = Up | LeftRight,
DownLeftRight = Down | LeftRight,
UpDownLeftRight = UpDown | LeftRight,
NoChildren = 1 << 4,
}
interface FlowGraphNode {
id: number;
flowNode: FlowNode;
edges: FlowGraphEdge[];
text: string;
lane: number;
endLane: number;
level: number;
}
interface FlowGraphEdge {
source: FlowGraphNode;
target: FlowGraphNode;
}
const hasAntecedentFlags =
FlowFlags.Assignment |
FlowFlags.Condition |
FlowFlags.SwitchClause |
FlowFlags.ArrayMutation |
FlowFlags.Call |
FlowFlags.PreFinally |
FlowFlags.AfterFinally;
const hasNodeFlags =
FlowFlags.Start |
FlowFlags.Assignment |
FlowFlags.Call |
FlowFlags.Condition |
FlowFlags.ArrayMutation;
const links: Record<number, FlowGraphNode> = Object.create(/*o*/ null); // eslint-disable-line no-null/no-null
const nodes: FlowGraphNode[] = [];
const edges: FlowGraphEdge[] = [];
const root = buildGraphNode(flowNode);
for (const node of nodes) {
computeLevel(node);
}
const height = computeHeight(root);
const columnWidths = computeColumnWidths(height);
computeLanes(root, 0);
return renderGraph();
function isFlowSwitchClause(f: FlowNode): f is FlowSwitchClause {
return !!(f.flags & FlowFlags.SwitchClause);
}
function hasAntecedents(f: FlowNode): f is FlowLabel & { antecedents: FlowNode[] } {
return !!(f.flags & FlowFlags.Label) && !!(f as FlowLabel).antecedents;
}
function hasAntecedent(f: FlowNode): f is Extract<FlowNode, { antecedent: FlowNode }> {
return !!(f.flags & hasAntecedentFlags);
}
function hasNode(f: FlowNode): f is Extract<FlowNode, { node?: Node }> {
return !!(f.flags & hasNodeFlags);
}
function getChildren(node: FlowGraphNode) {
const children: FlowGraphNode[] = [];
for (const edge of node.edges) {
if (edge.source === node) {
children.push(edge.target);
}
}
return children;
}
function getParents(node: FlowGraphNode) {
const parents: FlowGraphNode[] = [];
for (const edge of node.edges) {
if (edge.target === node) {
parents.push(edge.source);
}
}
return parents;
}
function buildGraphNode(flowNode: FlowNode) {
const id = getDebugFlowNodeId(flowNode);
let graphNode = links[id];
if (!graphNode) {
links[id] = graphNode = { id, flowNode, edges: [], text: renderFlowNode(flowNode), lane: -1, endLane: -1, level: -1 };
nodes.push(graphNode);
if (!(flowNode.flags & FlowFlags.PreFinally)) {
if (hasAntecedents(flowNode)) {
for (const antecedent of flowNode.antecedents) {
buildGraphEdge(graphNode, antecedent);
}
}
else if (hasAntecedent(flowNode)) {
buildGraphEdge(graphNode, flowNode.antecedent);
}
}
}
return graphNode;
}
function buildGraphEdge(source: FlowGraphNode, antecedent: FlowNode) {
const target = buildGraphNode(antecedent);
const edge: FlowGraphEdge = { source, target };
edges.push(edge);
source.edges.push(edge);
target.edges.push(edge);
}
function computeLevel(node: FlowGraphNode): number {
if (node.level !== -1) {
return node.level;
}
let level = 0;
for (const parent of getParents(node)) {
level = Math.max(level, computeLevel(parent) + 1);
}
return node.level = level;
}
function computeHeight(node: FlowGraphNode): number {
let height = 0;
for (const child of getChildren(node)) {
height = Math.max(height, computeHeight(child));
}
return height + 1;
}
function computeColumnWidths(height: number) {
const columns: number[] = fill(Array(height), 0);
for (const node of nodes) {
columns[node.level] = Math.max(columns[node.level], node.text.length);
}
return columns;
}
function computeLanes(node: FlowGraphNode, lane: number) {
if (node.lane === -1) {
node.lane = lane;
node.endLane = lane;
const children = getChildren(node);
for (let i = 0; i < children.length; i++) {
if (i > 0) lane++;
const child = children[i];
computeLanes(child, lane);
if (child.endLane > node.endLane) {
lane = child.endLane;
}
}
node.endLane = lane;
}
}
function getHeader(flags: FlowFlags) {
if (flags & FlowFlags.Start) return "Start";
if (flags & FlowFlags.BranchLabel) return "Branch";
if (flags & FlowFlags.LoopLabel) return "Loop";
if (flags & FlowFlags.Assignment) return "Assignment";
if (flags & FlowFlags.TrueCondition) return "True";
if (flags & FlowFlags.FalseCondition) return "False";
if (flags & FlowFlags.SwitchClause) return "SwitchClause";
if (flags & FlowFlags.ArrayMutation) return "ArrayMutation";
if (flags & FlowFlags.Call) return "Call";
if (flags & FlowFlags.PreFinally) return "PreFinally";
if (flags & FlowFlags.AfterFinally) return "AfterFinally";
if (flags & FlowFlags.Unreachable) return "Unreachable";
throw new Error();
}
function getNodeText(node: Node) {
const sourceFile = getSourceFileOfNode(node);
return getSourceTextOfNodeFromSourceFile(sourceFile, node, /*includeTrivia*/ false);
}
function renderFlowNode(flowNode: FlowNode) {
let text = getHeader(flowNode.flags);
if (hasNode(flowNode)) {
if (flowNode.node) {
text += ` (${getNodeText(flowNode.node)})`;
}
}
else if (isFlowSwitchClause(flowNode)) {
const clauses: string[] = [];
for (let i = flowNode.clauseStart; i < flowNode.clauseEnd; i++) {
const clause = flowNode.switchStatement.caseBlock.clauses[i];
if (isDefaultClause(clause)) {
clauses.push("default");
}
else {
clauses.push(getNodeText(clause.expression));
}
}
text += ` (${clauses.join(", ")})`;
}
return text;
}
function renderGraph() {
const columnCount = columnWidths.length;
const laneCount = nodes.reduce((x, n) => Math.max(x, n.lane), 0) + 1;
const lanes: string[] = fill(Array(laneCount), "");
const grid: (FlowGraphNode | undefined)[][] = columnWidths.map(() => Array(laneCount));
const connectors: Connection[][] = columnWidths.map(() => fill(Array(laneCount), 0));
// build connectors
for (const node of nodes) {
grid[node.level][node.lane] = node;
const children = getChildren(node);
for (let i = 0; i < children.length; i++) {
const child = children[i];
let connector: Connection = Connection.Right;
if (child.lane === node.lane) connector |= Connection.Left;
if (i > 0) connector |= Connection.Up;
if (i < children.length - 1) connector |= Connection.Down;
connectors[node.level][child.lane] |= connector;
}
if (children.length === 0) {
connectors[node.level][node.lane] |= Connection.NoChildren;
}
const parents = getParents(node);
for (let i = 0; i < parents.length; i++) {
const parent = parents[i];
let connector: Connection = Connection.Left;
if (i > 0) connector |= Connection.Up;
if (i < parents.length - 1) connector |= Connection.Down;
connectors[node.level - 1][parent.lane] |= connector;
}
}
// fill in missing connectors
for (let column = 0; column < columnCount; column++) {
for (let lane = 0; lane < laneCount; lane++) {
const left = column > 0 ? connectors[column - 1][lane] : 0;
const above = lane > 0 ? connectors[column][lane - 1] : 0;
let connector = connectors[column][lane];
if (!connector) {
if (left & Connection.Right) connector |= Connection.LeftRight;
if (above & Connection.Down) connector |= Connection.UpDown;
connectors[column][lane] = connector;
}
}
}
for (let column = 0; column < columnCount; column++) {
for (let lane = 0; lane < lanes.length; lane++) {
const connector = connectors[column][lane];
const fill = connector & Connection.Left ? BoxCharacter.lr : " ";
const node = grid[column][lane];
if (!node) {
if (column < columnCount - 1) {
writeLane(lane, repeat(fill, columnWidths[column] + 1));
}
}
else {
writeLane(lane, node.text);
if (column < columnCount - 1) {
writeLane(lane, " ");
writeLane(lane, repeat(fill, columnWidths[column] - node.text.length));
}
}
writeLane(lane, getBoxCharacter(connector));
writeLane(lane, connector & Connection.Right && column < columnCount - 1 && !grid[column + 1][lane] ? BoxCharacter.lr : " ");
}
}
return `\n${lanes.join("\n")}\n`;
function writeLane(lane: number, text: string) {
lanes[lane] += text;
}
}
function getBoxCharacter(connector: Connection) {
switch (connector) {
case Connection.UpDown: return BoxCharacter.ud;
case Connection.LeftRight: return BoxCharacter.lr;
case Connection.UpLeft: return BoxCharacter.ul;
case Connection.UpRight: return BoxCharacter.ur;
case Connection.DownLeft: return BoxCharacter.dl;
case Connection.DownRight: return BoxCharacter.dr;
case Connection.UpDownLeft: return BoxCharacter.udl;
case Connection.UpDownRight: return BoxCharacter.udr;
case Connection.UpLeftRight: return BoxCharacter.ulr;
case Connection.DownLeftRight: return BoxCharacter.dlr;
case Connection.UpDownLeftRight: return BoxCharacter.udlr;
}
return " ";
}
function fill<T>(array: T[], value: T) {
if (array.fill) {
array.fill(value);
}
else {
for (let i = 0; i < array.length; i++) {
array[i] = value;
}
}
return array;
}
function repeat(ch: string, length: number) {
if (ch.repeat) {
return length > 0 ? ch.repeat(length) : "";
}
let s = "";
while (s.length < length) {
s += ch;
}
return s;
}
}
// Export as a module. NOTE: Can't use module exports as this is built using --outFile
declare const module: { exports: {} };
if (typeof module !== "undefined" && module.exports) {
module.exports = Debug;
}
}
+13
View File
@@ -0,0 +1,13 @@
{
"extends": "../tsconfig-library-base",
"compilerOptions": {
"target": "es2019",
"lib": ["es2019"],
"outFile": "../../built/local/compiler-debug.js",
"declaration": false,
"sourceMap": true
},
"files": [
"debug.ts"
]
}
+1 -1
View File
@@ -290,7 +290,7 @@ namespace ts.server {
const args: protocol.FileLocationRequestArgs = this.createFileLocationRequestArgs(fileName, position);
const request = this.processRequest<protocol.DefinitionRequest>(CommandNames.DefinitionAndBoundSpan, args);
const response = this.processResponse<protocol.DefinitionInfoAndBoundSpanReponse>(request);
const response = this.processResponse<protocol.DefinitionInfoAndBoundSpanResponse>(request);
const body = Debug.assertDefined(response.body); // TODO: GH#18217
return {
+6 -2
View File
@@ -524,7 +524,7 @@ ${indentText}${text}`;
export const version = "FakeTSVersion";
export function patchSolutionBuilderHost(host: ts.SolutionBuilderHost<ts.BuilderProgram>, sys: System) {
export function patchHostForBuildInfoReadWrite(host: ts.CompilerHost | ts.SolutionBuilderHost<ts.BuilderProgram>) {
const originalReadFile = host.readFile;
host.readFile = (path, encoding) => {
const value = originalReadFile.call(host, path, encoding);
@@ -537,7 +537,7 @@ ${indentText}${text}`;
if (host.writeFile) {
const originalWriteFile = host.writeFile;
host.writeFile = (fileName, content, writeByteOrderMark) => {
host.writeFile = (fileName: string, content: string, writeByteOrderMark: boolean) => {
if (!ts.isBuildInfoFile(fileName)) return originalWriteFile.call(host, fileName, content, writeByteOrderMark);
const buildInfo = ts.getBuildInfo(content);
sanitizeBuildInfoProgram(buildInfo);
@@ -545,6 +545,10 @@ ${indentText}${text}`;
originalWriteFile.call(host, fileName, ts.getBuildInfoText(buildInfo), writeByteOrderMark);
};
}
}
export function patchSolutionBuilderHost(host: ts.SolutionBuilderHost<ts.BuilderProgram>, sys: System) {
patchHostForBuildInfoReadWrite(host);
ts.Debug.assert(host.now === undefined);
host.now = () => new Date(sys.vfs.time());
+7 -1
View File
@@ -775,7 +775,9 @@ namespace FourSlash {
private verifyCompletionsWorker(options: FourSlashInterface.VerifyCompletionsOptions): void {
const actualCompletions = this.getCompletionListAtCaret({ ...options.preferences, triggerCharacter: options.triggerCharacter })!;
if (!actualCompletions) {
if (ts.hasProperty(options, "exact") && options.exact === undefined) return;
if (ts.hasProperty(options, "exact") && (options.exact === undefined || ts.isArray(options.exact) && !options.exact.length)) {
return;
}
this.raiseError(`No completions at position '${this.currentCaretPosition}'.`);
}
@@ -4894,12 +4896,14 @@ namespace FourSlashInterface {
"declare",
"keyof",
"module",
"namespace",
"never",
"readonly",
"number",
"object",
"string",
"symbol",
"type",
"unique",
"unknown",
"bigint",
@@ -5091,12 +5095,14 @@ namespace FourSlashInterface {
"declare",
"keyof",
"module",
"namespace",
"never",
"readonly",
"number",
"object",
"string",
"symbol",
"type",
"unique",
"unknown",
"bigint",
+5 -1
View File
@@ -220,6 +220,10 @@ namespace Harness.LanguageService {
return !!this.typesRegistry && this.typesRegistry.has(name);
}
getGlobalTypingsCacheLocation() {
return "/Library/Caches/typescript";
}
installPackage = ts.notImplemented;
getCompilationSettings() { return this.settings; }
@@ -796,7 +800,7 @@ namespace Harness.LanguageService {
return mockHash(s);
}
require(_initialDir: string, _moduleName: string): ts.server.RequireResult {
require(_initialDir: string, _moduleName: string): ts.RequireResult {
switch (_moduleName) {
// Adds to the Quick Info a fixed string and a string from the config file
// and replaces the first display part
+1 -1
View File
@@ -341,7 +341,7 @@ interface Array<T> { length: number; [n: number]: T; }`
private readonly currentDirectory: string;
private readonly customWatchFile: HostWatchFile | undefined;
private readonly customRecursiveWatchDirectory: HostWatchDirectory | undefined;
public require: ((initialPath: string, moduleName: string) => server.RequireResult) | undefined;
public require: ((initialPath: string, moduleName: string) => RequireResult) | undefined;
constructor(
public withSafeList: boolean,
+2 -2
View File
@@ -9762,7 +9762,7 @@ interface ImageData {
declare var ImageData: {
prototype: ImageData;
new(width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height?: number): ImageData;
};
interface InnerHTML {
@@ -19083,7 +19083,7 @@ declare namespace WebAssembly {
var Instance: {
prototype: Instance;
new(module: Module, importObject?: any): Instance;
new(module: Module, importObject?: Imports): Instance;
};
interface LinkError {
+8 -8
View File
@@ -682,8 +682,8 @@ interface Math {
/** Returns a pseudorandom number between 0 and 1. */
random(): number;
/**
* Returns a supplied numeric expression rounded to the nearest number.
* @param x The value to be rounded to the nearest number.
* Returns a supplied numeric expression rounded to the nearest integer.
* @param x The value to be rounded to the nearest integer.
*/
round(x: number): number;
/**
@@ -873,12 +873,12 @@ interface DateConstructor {
/**
* Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date.
* @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year.
* @param month The month as an number between 0 and 11 (January to December).
* @param date The date as an number between 1 and 31.
* @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour.
* @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes.
* @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds.
* @param ms An number from 0 to 999 that specifies the milliseconds.
* @param month The month as a number between 0 and 11 (January to December).
* @param date The date as a number between 1 and 31.
* @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour.
* @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes.
* @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds.
* @param ms A number from 0 to 999 that specifies the milliseconds.
*/
UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number;
now(): number;
+2 -2
View File
@@ -2202,7 +2202,7 @@ interface ImageData {
declare var ImageData: {
prototype: ImageData;
new(width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height: number): ImageData;
new(array: Uint8ClampedArray, width: number, height?: number): ImageData;
};
/** This Channel Messaging API interface allows us to create a new message channel and send data through it via its two MessagePort properties. */
@@ -5609,7 +5609,7 @@ declare namespace WebAssembly {
var Instance: {
prototype: Instance;
new(module: Module, importObject?: any): Instance;
new(module: Module, importObject?: Imports): Instance;
};
interface Memory {
@@ -4087,7 +4087,7 @@
<Str Cat="Text">
<Val><![CDATA[Function lacks ending return statement and return type does not include 'undefined'.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[函数缺少结束返回语句,返回类型不包括 "undefined"。]]></Val>
<Val><![CDATA[函数缺少结束 return 语句,返回类型不包括 "undefined"。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -4987,7 +4987,7 @@
<Str Cat="Text">
<Val><![CDATA[JSX fragment is not supported when using an inline JSX factory pragma]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[使用内联 JSX 工厂杂注时,不支持 JSX 片段]]></Val>
<Val><![CDATA[使用内联 JSX 工厂 pragma 时,不支持 JSX 片段]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -25,7 +25,7 @@
<Str Cat="Text">
<Val><![CDATA[A '{0}' modifier cannot be used with an import declaration.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['{0}' 修飾無法與匯入宣告並用。]]></Val>
<Val><![CDATA['{0}' 修飾無法與匯入宣告並用。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -34,7 +34,7 @@
<Str Cat="Text">
<Val><![CDATA[A '{0}' modifier cannot be used with an interface declaration.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['{0}' 修飾無法與介面宣告並用。]]></Val>
<Val><![CDATA['{0}' 修飾無法與介面宣告並用。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -88,7 +88,7 @@
<Str Cat="Text">
<Val><![CDATA[A class declaration without the 'default' modifier must have a name.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[不具 'default' 修飾的類別宣告必須要有名稱。]]></Val>
<Val><![CDATA[不具 'default' 修飾的類別宣告必須要有名稱。]]></Val>
</Tgt>
<Prev Cat="Text">
<Val><![CDATA[A class declaration without the 'default' modifier must have a name]]></Val>
@@ -265,7 +265,7 @@
<Str Cat="Text">
<Val><![CDATA[A 'declare' modifier cannot be used in an already ambient context.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[不得在現有環境內容中使用 'declare' 修飾。]]></Val>
<Val><![CDATA[不得在現有環境內容中使用 'declare' 修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -274,7 +274,7 @@
<Str Cat="Text">
<Val><![CDATA[A 'declare' modifier is required for a top level declaration in a .d.ts file.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[.d.ts 檔案中的最上層宣告需要 'declare' 修飾。]]></Val>
<Val><![CDATA[.d.ts 檔案中的最上層宣告需要 'declare' 修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -886,7 +886,7 @@
<Str Cat="Text">
<Val><![CDATA[Accessibility modifier already seen.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[已有存取範圍修飾。]]></Val>
<Val><![CDATA[已有存取範圍修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -934,7 +934,7 @@
<Str Cat="Text">
<Val><![CDATA[Add all missing 'async' modifiers]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[新增缺少的所有 'async' 修飾]]></Val>
<Val><![CDATA[新增缺少的所有 'async' 修飾]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -961,7 +961,7 @@
<Str Cat="Text">
<Val><![CDATA[Add async modifier to containing function]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[將 async 修飾新增至包含的函式]]></Val>
<Val><![CDATA[將 async 修飾新增至包含的函式]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1129,7 +1129,7 @@
<Str Cat="Text">
<Val><![CDATA[All declarations of '{0}' must have identical modifiers.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['{0}' 的所有宣告都必須有相同修飾。]]></Val>
<Val><![CDATA['{0}' 的所有宣告都必須有相同修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1363,7 +1363,7 @@
<Str Cat="Text">
<Val><![CDATA[An export assignment cannot have modifiers.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[匯出指派不得有修飾。]]></Val>
<Val><![CDATA[匯出指派不得有修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1381,7 +1381,7 @@
<Str Cat="Text">
<Val><![CDATA[An export declaration cannot have modifiers.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[匯出宣告不得有修飾。]]></Val>
<Val><![CDATA[匯出宣告不得有修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1417,7 +1417,7 @@
<Str Cat="Text">
<Val><![CDATA[An import declaration cannot have modifiers.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[匯入宣告不得有修飾。]]></Val>
<Val><![CDATA[匯入宣告不得有修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1480,7 +1480,7 @@
<Str Cat="Text">
<Val><![CDATA[An index signature parameter cannot have an accessibility modifier.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[索引簽章參數不得有存取範圍修飾。]]></Val>
<Val><![CDATA[索引簽章參數不得有存取範圍修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1708,7 +1708,7 @@
<Str Cat="Text">
<Val><![CDATA[Augmentations for the global scope should have 'declare' modifier unless they appear in already ambient context.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[除非全域範圍的增強指定已顯示在環境內容中,否則應含有 'declare' 修飾。]]></Val>
<Val><![CDATA[除非全域範圍的增強指定已顯示在環境內容中,否則應含有 'declare' 修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -4087,7 +4087,7 @@
<Str Cat="Text">
<Val><![CDATA[Function lacks ending return statement and return type does not include 'undefined'.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[函式缺少結束傳回陳述式,且傳回類型不包括 'undefined'。]]></Val>
<Val><![CDATA[函式缺少結束 return 陳述式,且傳回類型不包括 'undefined'。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -5260,7 +5260,7 @@
<Str Cat="Text">
<Val><![CDATA[Modifiers cannot appear here.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[此處不得出現修飾。]]></Val>
<Val><![CDATA[此處不得出現修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9325,7 +9325,7 @@
<Str Cat="Text">
<Val><![CDATA['{0}' modifier already seen.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[已有 '{0}' 修飾。]]></Val>
<Val><![CDATA[已有 '{0}' 修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9334,7 +9334,7 @@
<Str Cat="Text">
<Val><![CDATA['{0}' modifier cannot appear on a class element.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[類別項目不得有 '{0}' 修飾。]]></Val>
<Val><![CDATA[類別項目不得有 '{0}' 修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9343,7 +9343,7 @@
<Str Cat="Text">
<Val><![CDATA['{0}' modifier cannot appear on a constructor declaration.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[建構函式宣告不得有 '{0}' 修飾。]]></Val>
<Val><![CDATA[建構函式宣告不得有 '{0}' 修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9352,7 +9352,7 @@
<Str Cat="Text">
<Val><![CDATA['{0}' modifier cannot appear on a data property.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[資料屬性不得有 '{0}' 修飾。]]></Val>
<Val><![CDATA[資料屬性不得有 '{0}' 修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9361,7 +9361,7 @@
<Str Cat="Text">
<Val><![CDATA['{0}' modifier cannot appear on a module or namespace element.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[模組或命名空間元素不能有 '{0}' 修飾。]]></Val>
<Val><![CDATA[模組或命名空間元素不能有 '{0}' 修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9370,7 +9370,7 @@
<Str Cat="Text">
<Val><![CDATA['{0}' modifier cannot appear on a parameter.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[參數不得有 '{0}' 修飾。]]></Val>
<Val><![CDATA[參數不得有 '{0}' 修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9379,7 +9379,7 @@
<Str Cat="Text">
<Val><![CDATA['{0}' modifier cannot appear on a type member.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[類型成員不能有 '{0}' 修飾。]]></Val>
<Val><![CDATA[類型成員不能有 '{0}' 修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9388,7 +9388,7 @@
<Str Cat="Text">
<Val><![CDATA['{0}' modifier cannot appear on an index signature.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[索引簽章不能有 '{0}' 修飾。]]></Val>
<Val><![CDATA[索引簽章不能有 '{0}' 修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9397,7 +9397,7 @@
<Str Cat="Text">
<Val><![CDATA['{0}' modifier cannot be used here.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[無法在此處使用 '{0}' 修飾。]]></Val>
<Val><![CDATA[無法在此處使用 '{0}' 修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9406,7 +9406,7 @@
<Str Cat="Text">
<Val><![CDATA['{0}' modifier cannot be used in an ambient context.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[無法在環境內容中使用 '{0}' 修飾。]]></Val>
<Val><![CDATA[無法在環境內容中使用 '{0}' 修飾。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9415,7 +9415,7 @@
<Str Cat="Text">
<Val><![CDATA['{0}' modifier cannot be used with '{1}' modifier.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['{0}' 修飾無法與 '{1}' 修飾並用。]]></Val>
<Val><![CDATA['{0}' 修飾無法與 '{1}' 修飾並用。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9424,7 +9424,7 @@
<Str Cat="Text">
<Val><![CDATA['{0}' modifier cannot be used with a class declaration.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['{0}' 修飾無法與類別宣告並用。]]></Val>
<Val><![CDATA['{0}' 修飾無法與類別宣告並用。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9433,7 +9433,7 @@
<Str Cat="Text">
<Val><![CDATA['{0}' modifier must precede '{1}' modifier.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['{0}' 修飾必須在 '{1}' 修飾之前。]]></Val>
<Val><![CDATA['{0}' 修飾必須在 '{1}' 修飾之前。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9496,7 +9496,7 @@
<Str Cat="Text">
<Val><![CDATA['abstract' modifier can only appear on a class, method, or property declaration.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['abstract' 修飾只能出現在類別宣告、方法宣告或屬性宣告。]]></Val>
<Val><![CDATA['abstract' 修飾只能出現在類別宣告、方法宣告或屬性宣告。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9649,7 +9649,7 @@
<Str Cat="Text">
<Val><![CDATA['export' modifier cannot be applied to ambient modules and module augmentations since they are always visible.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['export' 修飾無法套用至環境模組或模組增強指定,原因是這二者永遠會顯示。]]></Val>
<Val><![CDATA['export' 修飾無法套用至環境模組或模組增強指定,原因是這二者永遠會顯示。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9874,7 +9874,7 @@
<Str Cat="Text">
<Val><![CDATA['readonly' modifier can only appear on a property declaration or index signature.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['readonly' 修飾只能出現在屬性宣告或索引簽章。]]></Val>
<Val><![CDATA['readonly' 修飾只能出現在屬性宣告或索引簽章。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<LCX SchemaVersion="6.0" Name="f:\ddSetup\sources\typescript\localization\compiler2.resx" PsrId="306" FileType="1" SrcCul="en-US" TgtCul="cs-CZ" xmlns="http://schemas.microsoft.com/locstudio/2006/6/lcx">
<Props>
<Str Name="CustomName1" Val="Custom 1" />
@@ -4096,7 +4096,7 @@
<Str Cat="Text">
<Val><![CDATA[Function lacks ending return statement and return type does not include 'undefined'.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Ve funkci chybí koncový návratový příkaz a návratový typ neobsahuje undefined.]]></Val>
<Val><![CDATA[Ve funkci chybí koncový příkaz return a návratový typ neobsahuje undefined.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<LCX SchemaVersion="6.0" Name="f:\ddSetup\sources\typescript\localization\compiler2.resx" PsrId="306" FileType="1" SrcCul="en-US" TgtCul="fr-FR" xmlns="http://schemas.microsoft.com/locstudio/2006/6/lcx">
<Props>
<Str Name="CustomName1" Val="Custom 1" />
@@ -1348,7 +1348,7 @@
<Str Cat="Text">
<Val><![CDATA[An export assignment can only be used in a module.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Une attribution d'exportation peut uniquement être utilisée dans un module.]]></Val>
<Val><![CDATA[Une affectation d'exportation peut uniquement être utilisée dans un module.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -5539,7 +5539,7 @@
<Str Cat="Text">
<Val><![CDATA[Not all code paths return a value.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Les chemins de code ne retournent pas tous une valeur.]]></Val>
<Val><![CDATA[Les chemins du code ne retournent pas tous une valeur.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -6916,7 +6916,7 @@
<Str Cat="Text">
<Val><![CDATA[Report error when not all code paths in function return a value.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Signalez une erreur quand les chemins de code de la fonction ne retournent pas tous une valeur.]]></Val>
<Val><![CDATA[Signalez une erreur quand les chemins du code de la fonction ne retournent pas tous une valeur.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1228,7 +1228,7 @@
<Str Cat="Text">
<Val><![CDATA[An AMD module cannot have multiple name assignments.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[AMD モジュールに複数の名前を割り当てることはできません。]]></Val>
<Val><![CDATA[AMD モジュールに複数の名前を代入することはできません。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1336,7 +1336,7 @@
<Str Cat="Text">
<Val><![CDATA[An export assignment can only be used in a module.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[エクスポートの割り当てはモジュールでのみ使用可能です。]]></Val>
<Val><![CDATA[エクスポートの代入はモジュールでのみ使用可能です。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1345,7 +1345,7 @@
<Str Cat="Text">
<Val><![CDATA[An export assignment cannot be used in a module with other exported elements.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[エクスポートの割り当ては、エクスポートされた他の要素を含むモジュールでは使用できません。]]></Val>
<Val><![CDATA[エクスポートの代入は、エクスポートされた他の要素を含むモジュールでは使用できません。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1354,7 +1354,7 @@
<Str Cat="Text">
<Val><![CDATA[An export assignment cannot be used in a namespace.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[エクスポートの割り当ては、名前空間では使用できません。]]></Val>
<Val><![CDATA[エクスポートの代入は、名前空間では使用できません。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1363,7 +1363,7 @@
<Str Cat="Text">
<Val><![CDATA[An export assignment cannot have modifiers.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[エクスポートの割り当てに修飾子を指定することはできません。]]></Val>
<Val><![CDATA[エクスポートの代入に修飾子を指定することはできません。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -3610,7 +3610,7 @@
<Str Cat="Text">
<Val><![CDATA[Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[ECMAScript モジュールを対象にする場合は、エクスポート割り当てを使用できません。代わりに 'export default' または別のモジュール書式の使用をご検討ください。]]></Val>
<Val><![CDATA[ECMAScript モジュールを対象にする場合は、エクスポート代入を使用できません。代わりに 'export default' または別のモジュール書式の使用をご検討ください。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -3619,7 +3619,7 @@
<Str Cat="Text">
<Val><![CDATA[Export assignment is not supported when '--module' flag is 'system'.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[割り当てのエクスポートは、'--module' フラグが 'system' の場合にはサポートされません。]]></Val>
<Val><![CDATA[代入のエクスポートは、'--module' フラグが 'system' の場合にはサポートされません。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -3703,7 +3703,7 @@
<Str Cat="Text">
<Val><![CDATA[Exports and export assignments are not permitted in module augmentations.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[エクスポートとエクスポートの割り当てはモジュールの拡張では許可されていません。]]></Val>
<Val><![CDATA[エクスポートとエクスポートの代入はモジュールの拡張では許可されていません。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -4390,7 +4390,7 @@
<Str Cat="Text">
<Val><![CDATA[Import assignment cannot be used when targeting ECMAScript modules. Consider using 'import * as ns from "mod"', 'import {a} from "mod"', 'import d from "mod"', or another module format instead.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[ECMAScript モジュールを対象にする場合は、インポート割り当てを使用できません。代わりに 'import * as ns from "mod"'、'import {a} from "mod"'、'import d from "mod"' などのモジュール書式の使用をご検討ください。]]></Val>
<Val><![CDATA[ECMAScript モジュールを対象にする場合は、インポート代入を使用できません。代わりに 'import * as ns from "mod"'、'import {a} from "mod"'、'import d from "mod"' などのモジュール書式の使用をご検討ください。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -4987,7 +4987,7 @@
<Str Cat="Text">
<Val><![CDATA[JSX fragment is not supported when using an inline JSX factory pragma]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[JSX フラグメントはインライン JSX ファクトリ プラグマの使用時にサポートされていません]]></Val>
<Val><![CDATA[JSX フラグメントはインライン JSX ファクトリ pragma の使用時にサポートされていません]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -6622,7 +6622,7 @@
<Str Cat="Text">
<Val><![CDATA[Property assignment expected.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[プロパティの割り当てが必要です。]]></Val>
<Val><![CDATA[プロパティの代入が必要です。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -7870,7 +7870,7 @@
<Str Cat="Text">
<Val><![CDATA[The expression of an export assignment must be an identifier or qualified name in an ambient context.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[エクスポートの割り当ての式は、環境コンテキストの識別子または修飾名にする必要があります。]]></Val>
<Val><![CDATA[エクスポートの代入の式は、環境コンテキストの識別子または修飾名にする必要があります。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -8170,7 +8170,7 @@
<Str Cat="Text">
<Val><![CDATA[The target of an object rest assignment must be a variable or a property access.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[オブジェクトの残り部分の割り当ての対象は、変数またはプロパティ アクセスである必要があります。]]></Val>
<Val><![CDATA[オブジェクトの残り部分の代入の対象は、変数またはプロパティ アクセスである必要があります。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9535,7 +9535,7 @@
<Str Cat="Text">
<Val><![CDATA['=' can only be used in an object literal property inside a destructuring assignment.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['=' は、非構造化割り当て内のオブジェクト リテラル プロパティでのみ使用できます。]]></Val>
<Val><![CDATA['=' は、非構造化代入内のオブジェクト リテラル プロパティでのみ使用できます。]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9601,7 +9601,7 @@
<Str Cat="Text">
<Val><![CDATA['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.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['const' 列挙型は、プロパティまたはインデックスのアクセス式、インポート宣言またはエクスポートの割り当ての右辺、型のクエリにのみ使用できます。]]></Val>
<Val><![CDATA['const' 列挙型は、プロパティまたはインデックスのアクセス式、インポート宣言またはエクスポートの代入の右辺、型のクエリにのみ使用できます。]]></Val>
</Tgt>
<Prev Cat="Text">
<Val><![CDATA['const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment.]]></Val>
@@ -9856,7 +9856,7 @@
<Str Cat="Text">
<Val><![CDATA['parameter modifiers' can only be used in a .ts file.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA['parameter modifiers'는 .ts 파일에서만 사용할 수 있습니다.]]></Val>
<Val><![CDATA['매개 변수 한정자'는 .ts 파일에서만 사용할 수 있습니다.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -303,7 +303,7 @@
<Str Cat="Text">
<Val><![CDATA[A definite assignment assertion '!' is not permitted in this context.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Asercja określonego przydziału „!” nie jest dozwolona w tym kontekście.]]></Val>
<Val><![CDATA[Asercja określonego przypisania „!” nie jest dozwolona w tym kontekście.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -4077,7 +4077,7 @@
<Str Cat="Text">
<Val><![CDATA[Function lacks ending return statement and return type does not include 'undefined'.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Funkcja nie zawiera końcowej instrukcji return, a zwracany typ nie obejmuje wartości „undefined”.]]></Val>
<Val><![CDATA[Funkcja nie zawiera końcowej instrukcji return, a zwracany typ nie obejmuje wartości „undefined”.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -5517,7 +5517,7 @@
<Str Cat="Text">
<Val><![CDATA[Not all code paths return a value.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Nie wszystkie ścieżki kodu zwracają wartość.]]></Val>
<Val><![CDATA[Nie wszystkie ścieżki w kodzie zwracają wartość.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -6891,7 +6891,7 @@
<Str Cat="Text">
<Val><![CDATA[Report error when not all code paths in function return a value.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Zgłoś błąd, gdy nie wszystkie ścieżki kodu zwracają wartość.]]></Val>
<Val><![CDATA[Zgłoś błąd, gdy nie wszystkie ścieżki w kodzie zwracają wartość.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
File diff suppressed because it is too large Load Diff
@@ -309,7 +309,7 @@
<Str Cat="Text">
<Val><![CDATA[A definite assignment assertion '!' is not permitted in this context.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Утверждение определенного присваивания "!" запрещено в этом контексте.]]></Val>
<Val><![CDATA[Утверждение определенного назначения "!" запрещено в этом контексте.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -978,7 +978,7 @@
<Str Cat="Text">
<Val><![CDATA[Add definite assignment assertion to property '{0}']]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Добавить утверждение определенного присваивания к свойству "{0}"]]></Val>
<Val><![CDATA[Добавить утверждение определенного назначения к свойству "{0}"]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -987,7 +987,7 @@
<Str Cat="Text">
<Val><![CDATA[Add definite assignment assertions to all uninitialized properties]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Добавить утверждения определенного присваивания ко всем неинициализированным свойствам]]></Val>
<Val><![CDATA[Добавить утверждения определенного назначения ко всем неинициализированным свойствам]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1227,7 +1227,7 @@
<Str Cat="Text">
<Val><![CDATA[An AMD module cannot have multiple name assignments.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Модуль AMD не может иметь несколько присваиваний имен.]]></Val>
<Val><![CDATA[Модуль AMD не может иметь несколько назначений имен.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1335,7 +1335,7 @@
<Str Cat="Text">
<Val><![CDATA[An export assignment can only be used in a module.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Присваивание экспорта может быть использовано только в модуле.]]></Val>
<Val><![CDATA[Назначение экспорта может быть использовано только в модуле.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1344,7 +1344,7 @@
<Str Cat="Text">
<Val><![CDATA[An export assignment cannot be used in a module with other exported elements.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Присваивание экспорта нельзя использовать в модуле с другими экспортированными элементами.]]></Val>
<Val><![CDATA[Назначение экспорта нельзя использовать в модуле с другими экспортированными элементами.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1353,7 +1353,7 @@
<Str Cat="Text">
<Val><![CDATA[An export assignment cannot be used in a namespace.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Присваивание экспорта нельзя использовать в пространстве имен.]]></Val>
<Val><![CDATA[Назначение экспорта нельзя использовать в пространстве имен.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -1362,7 +1362,7 @@
<Str Cat="Text">
<Val><![CDATA[An export assignment cannot have modifiers.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Присваивание экспорта не может иметь модификаторы.]]></Val>
<Val><![CDATA[Назначение экспорта не может иметь модификаторы.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -3618,7 +3618,7 @@
<Str Cat="Text">
<Val><![CDATA[Export assignment is not supported when '--module' flag is 'system'.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Присваивание экспорта не поддерживается, если флаг "--module" имеет значение "system".]]></Val>
<Val><![CDATA[Назначение экспорта не поддерживается, если флаг "--module" имеет значение "system".]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -4086,7 +4086,7 @@
<Str Cat="Text">
<Val><![CDATA[Function lacks ending return statement and return type does not include 'undefined'.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[В функции отсутствует завершающий оператор возвращаемого значения, а тип возвращаемого значения не включает undefined.]]></Val>
<Val><![CDATA[В функции отсутствует завершающий оператор return, а тип возвращаемого значения не включает "undefined".]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -5526,7 +5526,7 @@
<Str Cat="Text">
<Val><![CDATA[Not all code paths return a value.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Не все пути кода возвращают значение.]]></Val>
<Val><![CDATA[Не все пути к коду возвращают значение.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -6621,7 +6621,7 @@
<Str Cat="Text">
<Val><![CDATA[Property assignment expected.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Ожидалось присваивание свойства.]]></Val>
<Val><![CDATA[Ожидалось назначение свойства.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -6903,7 +6903,7 @@
<Str Cat="Text">
<Val><![CDATA[Report error when not all code paths in function return a value.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Сообщать об ошибке, если не все пути кода в функции возвращают значение.]]></Val>
<Val><![CDATA[Сообщать об ошибке, если не все пути к коду в функции возвращают значение.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -7869,7 +7869,7 @@
<Str Cat="Text">
<Val><![CDATA[The expression of an export assignment must be an identifier or qualified name in an ambient context.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Выражение присваивания экспорта должно представлять собой идентификатор или полное имя в окружающем контексте.]]></Val>
<Val><![CDATA[Выражение назначения экспорта должно представлять собой идентификатор или полное имя в окружающем контексте.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
@@ -9600,7 +9600,7 @@
<Str Cat="Text">
<Val><![CDATA['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.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Перечисления const можно использовать только в выражениях доступа к свойству или индексу, а также в правой части объявления импорта, присваивания экспорта или запроса типа.]]></Val>
<Val><![CDATA[Перечисления const можно использовать только в выражениях доступа к свойству или индексу, а также в правой части объявления импорта, назначения экспорта или запроса типа.]]></Val>
</Tgt>
<Prev Cat="Text">
<Val><![CDATA['const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment.]]></Val>
@@ -4188,7 +4188,7 @@
<Str Cat="Text">
<Val><![CDATA[Generic type instantiation is excessively deep and possibly infinite.]]></Val>
<Tgt Cat="Text" Stat="Loc" Orig="New">
<Val><![CDATA[Genel tür oluşturma işlemi, fazla ayrıntılı ve büyük olasılıkla sınırsız.]]></Val>
<Val><![CDATA[Genel tür örneği oluşturma işlemi, fazla ayrıntılı ve büyük olasılıkla sınırsız.]]></Val>
</Tgt>
</Str>
<Disp Icon="Str" />
+8
View File
@@ -1533,6 +1533,14 @@ namespace ts.server {
return undefined;
}
/*@internal*/
findDefaultConfiguredProject(info: ScriptInfo) {
if (!info.isScriptOpen()) return undefined;
const configFileName = this.getConfigFileNameForFile(info);
return configFileName &&
this.findConfiguredProjectByProjectName(configFileName);
}
/**
* This function tries to search for a tsconfig.json for the given file.
* This is different from the method the compiler uses because
+5
View File
@@ -307,6 +307,11 @@ namespace ts.server {
return this.typingsCache.installPackage({ ...options, projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) });
}
/*@internal*/
getGlobalTypingsCacheLocation() {
return this.getGlobalCache();
}
private get typingsCache(): TypingsCache {
return this.projectService.typingsCache;
}
+10 -1
View File
@@ -918,10 +918,13 @@ namespace ts.server.protocol {
body?: FileSpanWithContext[];
}
export interface DefinitionInfoAndBoundSpanReponse extends Response {
export interface DefinitionInfoAndBoundSpanResponse extends Response {
body?: DefinitionInfoAndBoundSpan;
}
/** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */
export type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse;
/**
* Definition response message. Gives text range for definition.
*/
@@ -3004,6 +3007,12 @@ namespace ts.server.protocol {
* For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`.
*/
readonly includeCompletionsWithInsertText?: boolean;
/**
* Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled,
* member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined
* values, with insertion text to replace preceding `.` tokens with `?.`.
*/
readonly includeAutomaticOptionalChainCompletions?: boolean;
readonly importModuleSpecifierPreference?: "relative" | "non-relative";
readonly allowTextChangesInNewFiles?: boolean;
readonly lazyConfiguredProjectsFromExternalProject?: boolean;
+25 -6
View File
@@ -491,21 +491,40 @@ namespace ts.server {
case 1:
return this.containingProjects[0];
default:
// if this file belongs to multiple projects, the first configured project should be
// the default project; if no configured projects, the first external project should
// be the default project; otherwise the first inferred project should be the default.
// If this file belongs to multiple projects, below is the order in which default project is used
// - for open script info, its default configured project during opening is default if info is part of it
// - first configured project of which script info is not a source of project reference redirect
// - first configured project
// - first external project
// - first inferred project
let firstExternalProject;
let firstConfiguredProject;
for (const project of this.containingProjects) {
let firstNonSourceOfProjectReferenceRedirect;
let defaultConfiguredProject: ConfiguredProject | false | undefined;
for (let index = 0; index < this.containingProjects.length; index++) {
const project = this.containingProjects[index];
if (project.projectKind === ProjectKind.Configured) {
if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) return project;
if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) {
// If we havent found default configuredProject and
// its not the last one, find it and use that one if there
if (defaultConfiguredProject === undefined &&
index !== this.containingProjects.length - 1) {
defaultConfiguredProject = project.projectService.findDefaultConfiguredProject(this) || false;
}
if (defaultConfiguredProject === project) return project;
if (!firstNonSourceOfProjectReferenceRedirect) firstNonSourceOfProjectReferenceRedirect = project;
}
if (!firstConfiguredProject) firstConfiguredProject = project;
}
else if (project.projectKind === ProjectKind.External && !firstExternalProject) {
firstExternalProject = project;
}
}
return firstConfiguredProject || firstExternalProject || this.containingProjects[0];
return defaultConfiguredProject ||
firstNonSourceOfProjectReferenceRedirect ||
firstConfiguredProject ||
firstExternalProject ||
this.containingProjects[0];
}
}
+4 -3
View File
@@ -499,8 +499,10 @@ namespace ts {
return { spans, endOfLineState: EndOfLineState.None };
function pushClassification(start: number, end: number, type: ClassificationType): void {
const length = end - start;
Debug.assert(length > 0, `Classification had non-positive length of ${length}`);
spans.push(start);
spans.push(end - start);
spans.push(length);
spans.push(type);
}
}
@@ -985,8 +987,7 @@ namespace ts {
return ClassificationType.bigintLiteral;
}
else if (tokenKind === SyntaxKind.StringLiteral) {
// TODO: GH#18217
return token!.parent.kind === SyntaxKind.JsxAttribute ? ClassificationType.jsxAttributeStringLiteralValue : ClassificationType.stringLiteral;
return token && token.parent.kind === SyntaxKind.JsxAttribute ? ClassificationType.jsxAttributeStringLiteralValue : ClassificationType.stringLiteral;
}
else if (tokenKind === SyntaxKind.RegularExpressionLiteral) {
// TODO: we should get another classification type for these literals.
+3 -3
View File
@@ -233,14 +233,14 @@ namespace ts.codefix {
let someSigHasRestParameter = false;
for (const sig of signatures) {
minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount);
if (sig.hasRestParameter) {
if (signatureHasRestParameter(sig)) {
someSigHasRestParameter = true;
}
if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) {
if (sig.parameters.length >= maxArgsSignature.parameters.length && (!signatureHasRestParameter(sig) || signatureHasRestParameter(maxArgsSignature))) {
maxArgsSignature = sig;
}
}
const maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0);
const maxNonRestArgs = maxArgsSignature.parameters.length - (signatureHasRestParameter(maxArgsSignature) ? 1 : 0);
const maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(symbol => symbol.name);
const parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false);
+11 -3
View File
@@ -631,6 +631,7 @@ namespace ts.codefix {
let filteredCount = 0;
const packageJson = filterByPackageJson && createAutoImportFilter(from, program, host);
const allSourceFiles = program.getSourceFiles();
const globalTypingsCache = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
forEachExternalModule(program.getTypeChecker(), allSourceFiles, (module, sourceFile) => {
if (sourceFile === undefined) {
if (!packageJson || packageJson.allowsImportingAmbientModule(module, allSourceFiles)) {
@@ -640,7 +641,10 @@ namespace ts.codefix {
filteredCount++;
}
}
else if (sourceFile && sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) {
else if (sourceFile &&
sourceFile !== from &&
isImportablePath(from.fileName, sourceFile.fileName, hostGetCanonicalFileName(host), globalTypingsCache)
) {
if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile, allSourceFiles)) {
cb(module);
}
@@ -669,10 +673,13 @@ namespace ts.codefix {
* Don't include something from a `node_modules` that isn't actually reachable by a global import.
* A relative import to node_modules is usually a bad idea.
*/
function isImportablePath(fromPath: string, toPath: string): boolean {
function isImportablePath(fromPath: string, toPath: string, getCanonicalFileName: GetCanonicalFileName, globalCachePath?: string): boolean {
// If it's in a `node_modules` but is not reachable from here via a global import, don't bother.
const toNodeModules = forEachAncestorDirectory(toPath, ancestor => getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined);
return toNodeModules === undefined || startsWith(fromPath, getDirectoryPath(toNodeModules));
const toNodeModulesParent = toNodeModules && getDirectoryPath(getCanonicalFileName(toNodeModules));
return toNodeModulesParent === undefined
|| startsWith(getCanonicalFileName(fromPath), toNodeModulesParent)
|| (!!globalCachePath && startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent));
}
export function moduleSymbolToValidIdentifier(moduleSymbol: Symbol, target: ScriptTarget): string {
@@ -718,6 +725,7 @@ namespace ts.codefix {
readFile: maybeBind(host, host.readFile),
useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames),
getProbableSymlinks: maybeBind(host, host.getProbableSymlinks) || program.getProbableSymlinks,
getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation),
};
let usesNodeCoreModules: boolean | undefined;
+78 -20
View File
@@ -49,21 +49,21 @@ namespace ts.codefix {
registerCodeFix({
errorCodes,
getCodeActions(context) {
const { sourceFile, program, span: { start }, errorCode, cancellationToken, host } = context;
const { sourceFile, program, span: { start }, errorCode, cancellationToken, host, formatContext, preferences } = 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, /*markSeen*/ returnTrue, host); });
const changes = textChanges.ChangeTracker.with(context, changes => { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ returnTrue, host, formatContext, preferences); });
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, host } = context;
const { sourceFile, program, cancellationToken, host, formatContext, preferences } = context;
const markSeen = nodeSeenTracker();
return codeFixAll(context, errorCodes, (changes, err) => {
doChange(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host);
doChange(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, formatContext, preferences);
});
},
});
@@ -106,7 +106,7 @@ namespace ts.codefix {
return errorCode;
}
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker, host: LanguageServiceHost): Declaration | undefined {
function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker, host: LanguageServiceHost, formatContext: formatting.FormatContext, preferences: UserPreferences): Declaration | undefined {
if (!isParameterPropertyModifier(token.kind) && token.kind !== SyntaxKind.Identifier && token.kind !== SyntaxKind.DotDotDotToken && token.kind !== SyntaxKind.ThisKeyword) {
return undefined;
}
@@ -118,7 +118,7 @@ namespace ts.codefix {
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, host, cancellationToken);
annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken, formatContext, preferences);
return parent;
}
if (isPropertyAccessExpression(parent)) {
@@ -136,7 +136,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, host, cancellationToken);
annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken, formatContext, preferences);
return symbol.valueDeclaration;
}
return undefined;
@@ -152,14 +152,14 @@ namespace ts.codefix {
// Parameter declarations
case Diagnostics.Parameter_0_implicitly_has_an_1_type.code:
if (isSetAccessorDeclaration(containingFunction)) {
annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken);
annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences);
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, sourceFile, param, containingFunction, program, host, cancellationToken);
annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken, formatContext, preferences);
return param;
}
return undefined;
@@ -168,7 +168,7 @@ namespace ts.codefix {
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 (isGetAccessorDeclaration(containingFunction) && isIdentifier(containingFunction.name)) {
annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host);
annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host, formatContext, preferences);
return containingFunction;
}
return undefined;
@@ -176,7 +176,7 @@ namespace ts.codefix {
// Set Accessor declarations
case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code:
if (isSetAccessorDeclaration(containingFunction)) {
annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken);
annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences);
return containingFunction;
}
return undefined;
@@ -194,13 +194,32 @@ namespace ts.codefix {
}
}
function annotateVariableDeclaration(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: VariableDeclaration | PropertyDeclaration | PropertySignature, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void {
function annotateVariableDeclaration(
changes: textChanges.ChangeTracker,
sourceFile: SourceFile,
declaration: VariableDeclaration | PropertyDeclaration | PropertySignature,
program: Program,
host: LanguageServiceHost,
cancellationToken: CancellationToken,
formatContext: formatting.FormatContext,
preferences: UserPreferences,
): void {
if (isIdentifier(declaration.name)) {
annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host);
annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host, formatContext, preferences);
}
}
function annotateParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterDeclaration: ParameterDeclaration, containingFunction: FunctionLike, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void {
function annotateParameters(
changes: textChanges.ChangeTracker,
sourceFile: SourceFile,
parameterDeclaration: ParameterDeclaration,
containingFunction: FunctionLike,
program: Program,
host: LanguageServiceHost,
cancellationToken: CancellationToken,
formatContext: formatting.FormatContext,
preferences: UserPreferences,
): void {
if (!isIdentifier(parameterDeclaration.name)) {
return;
}
@@ -216,7 +235,7 @@ namespace ts.codefix {
if (needParens) changes.insertNodeBefore(sourceFile, first(containingFunction.parameters), createToken(SyntaxKind.OpenParenToken));
for (const { declaration, type } of parameterInferences) {
if (declaration && !declaration.type && !declaration.initializer) {
annotate(changes, sourceFile, declaration, type, program, host);
annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences);
}
}
if (needParens) changes.insertNodeAfter(sourceFile, last(containingFunction.parameters), createToken(SyntaxKind.CloseParenToken));
@@ -248,7 +267,16 @@ namespace ts.codefix {
]);
}
function annotateSetAccessor(changes: textChanges.ChangeTracker, sourceFile: SourceFile, setAccessorDeclaration: SetAccessorDeclaration, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void {
function annotateSetAccessor(
changes: textChanges.ChangeTracker,
sourceFile: SourceFile,
setAccessorDeclaration: SetAccessorDeclaration,
program: Program,
host: LanguageServiceHost,
cancellationToken: CancellationToken,
formatContext: formatting.FormatContext,
preferences: UserPreferences,
): void {
const param = firstOrUndefined(setAccessorDeclaration.parameters);
if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) {
let type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken);
@@ -259,12 +287,12 @@ namespace ts.codefix {
annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type }], program, host);
}
else {
annotate(changes, sourceFile, param, type, program, host);
annotate(changes, sourceFile, param, type, program, host, formatContext, preferences);
}
}
}
function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type, program: Program, host: LanguageServiceHost): void {
function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type, program: Program, host: LanguageServiceHost, formatContext: formatting.FormatContext, preferences: UserPreferences): void {
const typeNode = getTypeNodeIfAccessible(type, declaration, program, host);
if (typeNode) {
if (isInJSFile(sourceFile) && declaration.kind !== SyntaxKind.PropertySignature) {
@@ -276,12 +304,42 @@ namespace ts.codefix {
const typeTag = isGetAccessorDeclaration(declaration) ? createJSDocReturnTag(typeExpression, "") : createJSDocTypeTag(typeExpression, "");
addJSDocTags(changes, sourceFile, parent, [typeTag]);
}
else {
else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences)) {
changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode);
}
}
}
function tryReplaceImportTypeNodeWithAutoImport(typeNode: TypeNode, changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type, program: Program, host: LanguageServiceHost, formatContext: formatting.FormatContext, preferences: UserPreferences): boolean {
if (isLiteralImportTypeNode(typeNode) && typeNode.qualifier && type.symbol) {
// Replace 'import("./a").SomeType' with 'SomeType' and an actual import if possible
const moduleSymbol = find(type.symbol.declarations, d => !!d.getSourceFile().externalModuleIndicator)?.getSourceFile().symbol;
// Symbol for the left-most thing after the dot
if (moduleSymbol) {
const symbol = getFirstIdentifier(typeNode.qualifier).symbol;
const action = getImportCompletionAction(
symbol,
moduleSymbol,
sourceFile,
symbol.name,
host,
program,
formatContext,
declaration.pos,
preferences,
);
if (action.codeAction.changes.length && changes.tryInsertTypeAnnotation(sourceFile, declaration, createTypeReferenceNode(typeNode.qualifier, typeNode.typeArguments))) {
for (const change of action.codeAction.changes) {
const file = sourceFile.fileName === change.fileName ? sourceFile : Debug.assertDefined(program.getSourceFile(change.fileName));
changes.pushRaw(file, change);
}
return true;
}
}
}
return false;
}
function annotateJSDocParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterInferences: readonly ParameterInference[], program: Program, host: LanguageServiceHost): void {
const signature = parameterInferences.length && parameterInferences[0].declaration.parent;
if (!signature) {
@@ -1054,7 +1112,7 @@ namespace ts.codefix {
}
const returnType = combineFromUsage(combineUsages(calls.map(call => call.return_)));
// TODO: GH#18217
return checker.createSignature(/*declaration*/ undefined!, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
return checker.createSignature(/*declaration*/ undefined!, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, SignatureFlags.None);
}
function addCandidateType(usage: Usage, type: Type | undefined) {
+30 -8
View File
@@ -338,6 +338,7 @@ namespace ts.Completions {
): CompletionEntry | undefined {
let insertText: string | undefined;
let replacementSpan: TextSpan | undefined;
const insertQuestionDot = origin && originIsNullableMember(origin);
const useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess;
if (origin && originIsThisType(origin)) {
@@ -780,7 +781,7 @@ namespace ts.Completions {
sourceFile: SourceFile,
isUncheckedFile: boolean,
position: number,
preferences: Pick<UserPreferences, "includeCompletionsForModuleExports" | "includeCompletionsWithInsertText">,
preferences: Pick<UserPreferences, "includeCompletionsForModuleExports" | "includeCompletionsWithInsertText" | "includeAutomaticOptionalChainCompletions">,
detailsEntryId: CompletionEntryIdentifier | undefined,
host: LanguageServiceHost,
): CompletionData | Request | undefined {
@@ -1000,6 +1001,7 @@ namespace ts.Completions {
let completionKind = CompletionKind.None;
let isNewIdentifierLocation = false;
let keywordFilters = KeywordCompletionFilters.None;
// This also gets mutated in nested-functions after the return
let symbols: Symbol[] = [];
const symbolToOriginInfoMap: SymbolOriginInfoMap = [];
const symbolToSortTextMap: SymbolSortTextMap = [];
@@ -1115,8 +1117,17 @@ namespace ts.Completions {
let type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType();
let insertQuestionDot = false;
if (type.isNullableType()) {
insertQuestionDot = isRightOfDot && !isRightOfQuestionDot;
type = type.getNonNullableType();
const canCorrectToQuestionDot =
isRightOfDot &&
!isRightOfQuestionDot &&
preferences.includeAutomaticOptionalChainCompletions !== false;
if (canCorrectToQuestionDot || isRightOfQuestionDot) {
type = type.getNonNullableType();
if (canCorrectToQuestionDot) {
insertQuestionDot = true;
}
}
}
addTypeProperties(type, !!(node.flags & NodeFlags.AwaitContext), insertQuestionDot);
}
@@ -1136,8 +1147,17 @@ namespace ts.Completions {
let type = typeChecker.getTypeAtLocation(node).getNonOptionalType();
let insertQuestionDot = false;
if (type.isNullableType()) {
insertQuestionDot = isRightOfDot && !isRightOfQuestionDot;
type = type.getNonNullableType();
const canCorrectToQuestionDot =
isRightOfDot &&
!isRightOfQuestionDot &&
preferences.includeAutomaticOptionalChainCompletions !== false;
if (canCorrectToQuestionDot || isRightOfQuestionDot) {
type = type.getNonNullableType();
if (canCorrectToQuestionDot) {
insertQuestionDot = true;
}
}
}
addTypeProperties(type, !!(node.flags & NodeFlags.AwaitContext), insertQuestionDot);
}
@@ -1464,7 +1484,7 @@ namespace ts.Completions {
}
/**
* Gathers symbols that can be imported from other files, deduplicating along the way. Symbols can be duplicates
* Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates"
* if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but
* its just an alias to the first, and both have the same name, so we generally want to filter those aliases out,
* if and only if the the first can be imported (it may be excluded due to package.json filtering in
@@ -1548,7 +1568,7 @@ namespace ts.Completions {
// 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`.
if (resolvedModuleSymbol !== moduleSymbol &&
every(resolvedModuleSymbol.declarations, d => !!d.getSourceFile().externalModuleIndicator)) {
every(resolvedModuleSymbol.declarations, d => !!d.getSourceFile().externalModuleIndicator && !findAncestor(d, isGlobalScopeAugmentation))) {
pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true);
}
@@ -1760,7 +1780,7 @@ namespace ts.Completions {
let existingMembers: readonly Declaration[] | undefined;
if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) {
const typeForObject = typeChecker.getContextualType(objectLikeContainer);
const typeForObject = typeChecker.getContextualType(objectLikeContainer, ContextFlags.Completion);
if (!typeForObject) return GlobalsSearch.Fail;
isNewIdentifierLocation = hasIndexSignature(typeForObject);
typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker);
@@ -2406,6 +2426,8 @@ namespace ts.Completions {
return isFunctionLikeBodyKeyword(kind)
|| kind === SyntaxKind.DeclareKeyword
|| kind === SyntaxKind.ModuleKeyword
|| kind === SyntaxKind.TypeKeyword
|| kind === SyntaxKind.NamespaceKeyword
|| isTypeKeyword(kind) && kind !== SyntaxKind.UndefinedKeyword;
case KeywordCompletionFilters.FunctionLikeBodyKeywords:
return isFunctionLikeBodyKeyword(kind);
+4 -2
View File
@@ -1395,8 +1395,10 @@ namespace ts.FindAllReferences.Core {
|| exportSpecifier.name.originalKeywordKind === SyntaxKind.DefaultKeyword;
const exportKind = isDefaultExport ? ExportKind.Default : ExportKind.Named;
const exportSymbol = Debug.assertDefined(exportSpecifier.symbol);
const exportInfo = Debug.assertDefined(getExportInfo(exportSymbol, exportKind, state.checker));
searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
const exportInfo = getExportInfo(exportSymbol, exportKind, state.checker);
if (exportInfo) {
searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state);
}
}
// At `export { x } from "foo"`, also search for the imported symbol `"foo".x`.
+2 -2
View File
@@ -59,8 +59,8 @@ namespace ts.formatting {
// in other cases there should be no space between '?' and next token
rule("NoSpaceAfterQuestionMark", SyntaxKind.QuestionToken, anyToken, [isNonJsxSameLineTokenContext], RuleAction.DeleteSpace),
rule("NoSpaceBeforeDot", anyToken, SyntaxKind.DotToken, [isNonJsxSameLineTokenContext], RuleAction.DeleteSpace),
rule("NoSpaceAfterDot", SyntaxKind.DotToken, anyToken, [isNonJsxSameLineTokenContext], RuleAction.DeleteSpace),
rule("NoSpaceBeforeDot", anyToken, [SyntaxKind.DotToken, SyntaxKind.QuestionDotToken], [isNonJsxSameLineTokenContext], RuleAction.DeleteSpace),
rule("NoSpaceAfterDot", [SyntaxKind.DotToken, SyntaxKind.QuestionDotToken], anyToken, [isNonJsxSameLineTokenContext], RuleAction.DeleteSpace),
rule("NoSpaceBetweenImportParenInImportType", SyntaxKind.ImportKeyword, SyntaxKind.OpenParenToken, [isNonJsxSameLineTokenContext, isImportTypeContext], RuleAction.DeleteSpace),
-19
View File
@@ -158,25 +158,6 @@ namespace ts.JsDoc {
}
}
/**
* Iterates through 'array' by index and performs the callback on each element of array until the callback
* returns a truthy value, then returns that value.
* If no such value is found, the callback is applied to each element of array and undefined is returned.
*/
function forEachUnique<T, U>(array: readonly T[] | undefined, callback: (element: T, index: number) => U): U | undefined {
if (array) {
for (let i = 0; i < array.length; i++) {
if (array.indexOf(array[i]) === i) {
const result = callback(array[i], i);
if (result) {
return result;
}
}
}
}
return undefined;
}
export function getJSDocTagNameCompletions(): CompletionEntry[] {
return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = map(jsDocTagNames, tagName => {
return {
+17 -7
View File
@@ -452,9 +452,19 @@ namespace ts {
isClass(): this is InterfaceType {
return !!(getObjectFlags(this) & ObjectFlags.Class);
}
/**
* This polyfills `referenceType.typeArguments` for API consumers
*/
get typeArguments() {
if (getObjectFlags(this) & ObjectFlags.Reference) {
return this.checker.getTypeArguments(this as Type as TypeReference);
}
return undefined;
}
}
class SignatureObject implements Signature {
flags: SignatureFlags;
checker: TypeChecker;
declaration!: SignatureDeclaration;
typeParameters?: TypeParameter[];
@@ -464,8 +474,6 @@ namespace ts {
resolvedTypePredicate: TypePredicate | undefined;
minTypeArgumentCount!: number;
minArgumentCount!: number;
hasRestParameter!: boolean;
hasLiteralTypes!: boolean;
// Undefined is used to indicate the value has not been computed. If, after computing, the
// symbol has no doc comment, then the empty array will be returned.
@@ -475,9 +483,11 @@ namespace ts {
// symbol has no doc comment, then the empty array will be returned.
jsDocTags?: JSDocTagInfo[];
constructor(checker: TypeChecker) {
constructor(checker: TypeChecker, flags: SignatureFlags) {
this.checker = checker;
this.flags = flags;
}
getDeclaration(): SignatureDeclaration {
return this.declaration;
}
@@ -518,11 +528,11 @@ namespace ts {
let doc = JsDoc.getJsDocCommentsFromDeclarations(declarations);
if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) {
for (const declaration of declarations) {
forEachUnique(declarations, declaration => {
const inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker!); // TODO: GH#18217
// TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs
if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(lineBreakPart(), doc);
}
});
}
return doc;
}
@@ -1629,12 +1639,12 @@ namespace ts {
return NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles);
}
function getEmitOutput(fileName: string, emitOnlyDtsFiles = false) {
function getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean) {
synchronizeHostData();
const sourceFile = getValidSourceFile(fileName);
const customTransformers = host.getCustomTransformers && host.getCustomTransformers();
return getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers);
return getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit);
}
// Signature help
+1 -1
View File
@@ -204,7 +204,7 @@ namespace ts.Completions.StringCompletions {
const candidates: Signature[] = [];
checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount);
const types = flatMap(candidates, candidate => {
if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) return;
if (!signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return;
const type = checker.getParameterType(candidate, argumentInfo.argumentIndex);
isNewIdentifier = isNewIdentifier || !!(type.flags & TypeFlags.String);
return getStringLiteralTypes(type, uniques);
+1 -1
View File
@@ -237,7 +237,7 @@ namespace ts.SymbolDisplay {
// get the signature from the declaration and write it
const functionDeclaration = <FunctionLike>location.parent;
// Use function declaration to write the signatures only if the symbol corresponding to this declaration
const locationIsSymbolDeclaration = find(symbol.declarations, declaration =>
const locationIsSymbolDeclaration = symbol.declarations && find(symbol.declarations, declaration =>
declaration === (location.kind === SyntaxKind.ConstructorKeyword ? functionDeclaration.parent : functionDeclaration));
if (locationIsSymbolDeclaration) {
+15 -2
View File
@@ -248,6 +248,18 @@ namespace ts.textChanges {
/** Public for tests only. Other callers should use `ChangeTracker.with`. */
constructor(private readonly newLineCharacter: string, private readonly formatContext: formatting.FormatContext) {}
public pushRaw(sourceFile: SourceFile, change: FileTextChanges) {
Debug.assertEqual(sourceFile.fileName, change.fileName);
for (const c of change.textChanges) {
this.changes.push({
kind: ChangeKind.Text,
sourceFile,
text: c.newText,
range: createTextRangeFromSpan(c.span),
});
}
}
public deleteRange(sourceFile: SourceFile, range: TextRange): void {
this.changes.push({ kind: ChangeKind.Remove, sourceFile, range });
}
@@ -383,12 +395,12 @@ namespace ts.textChanges {
}
/** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */
public tryInsertTypeAnnotation(sourceFile: SourceFile, node: TypeAnnotatable, type: TypeNode): void {
public tryInsertTypeAnnotation(sourceFile: SourceFile, node: TypeAnnotatable, type: TypeNode): boolean {
let endNode: Node | undefined;
if (isFunctionLike(node)) {
endNode = findChildOfKind(node, SyntaxKind.CloseParenToken, sourceFile);
if (!endNode) {
if (!isArrowFunction(node)) return; // Function missing parentheses, give up
if (!isArrowFunction(node)) return false; // Function missing parentheses, give up
// If no `)`, is an arrow function `x => x`, so use the end of the first parameter
endNode = first(node.parameters);
}
@@ -398,6 +410,7 @@ namespace ts.textChanges {
}
this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " });
return true;
}
public tryInsertThisTypeAnnotation(sourceFile: SourceFile, node: ThisTypeAnnotatable, type: TypeNode): void {
+1
View File
@@ -4,6 +4,7 @@
"outFile": "../../built/local/services.js"
},
"references": [
{ "path": "../shims" },
{ "path": "../compiler" },
{ "path": "../jsTyping" }
],
+8 -2
View File
@@ -68,6 +68,10 @@ namespace ts {
isClass(): this is InterfaceType;
}
export interface TypeReference {
typeArguments?: readonly Type[];
}
export interface Signature {
getDeclaration(): SignatureDeclaration;
getTypeParameters(): TypeParameter[] | undefined;
@@ -239,6 +243,8 @@ namespace ts {
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions): (ResolvedTypeReferenceDirective | undefined)[];
/* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution;
/* @internal */ hasChangedAutomaticTypeDirectiveNames?: boolean;
/* @internal */
getGlobalTypingsCacheLocation?(): string | undefined;
/*
* Required for full import and type reference completions.
@@ -387,7 +393,7 @@ namespace ts {
organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[];
getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[];
getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput;
getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput;
getProgram(): Program | undefined;
@@ -534,7 +540,7 @@ namespace ts {
export interface FileTextChanges {
fileName: string;
textChanges: TextChange[];
textChanges: readonly TextChange[];
isNewFile?: boolean;
}
+19
View File
@@ -1458,6 +1458,25 @@ namespace ts {
export function documentSpansEqual(a: DocumentSpan, b: DocumentSpan): boolean {
return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan);
}
/**
* Iterates through 'array' by index and performs the callback on each element of array until the callback
* returns a truthy value, then returns that value.
* If no such value is found, the callback is applied to each element of array and undefined is returned.
*/
export function forEachUnique<T, U>(array: readonly T[] | undefined, callback: (element: T, index: number) => U): U | undefined {
if (array) {
for (let i = 0; i < array.length; i++) {
if (array.indexOf(array[i]) === i) {
const result = callback(array[i], i);
if (result) {
return result;
}
}
}
}
return undefined;
}
}
// Display-part writer helpers
+212
View File
@@ -0,0 +1,212 @@
/* @internal */
namespace ts {
// NOTE: Due to how the project-reference merging ends up working, `T` isn't considered referenced until `Map` merges with the definition
// in src/compiler/core.ts
// @ts-ignore
export interface Map<T> {
// full type defined in ~/src/compiler/core.ts
}
export function createMapShim(): new <T>() => Map<T> {
/** Create a MapLike with good performance. */
function createDictionaryObject<T>(): Record<string, T> {
const map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null
// Using 'delete' on an object causes V8 to put the object in dictionary mode.
// This disables creation of hidden classes, which are expensive when an object is
// constantly changing shape.
map.__ = undefined;
delete map.__;
return map;
}
interface MapEntry<T> {
readonly key?: string;
value?: T;
// Linked list references for iterators.
nextEntry?: MapEntry<T>;
previousEntry?: MapEntry<T>;
/**
* Specifies if iterators should skip the next entry.
* This will be set when an entry is deleted.
* See https://github.com/Microsoft/TypeScript/pull/27292 for more information.
*/
skipNext?: boolean;
}
class MapIterator<T, U extends (string | T | [string, T])> {
private currentEntry?: MapEntry<T>;
private selector: (key: string, value: T) => U;
constructor(currentEntry: MapEntry<T>, selector: (key: string, value: T) => U) {
this.currentEntry = currentEntry;
this.selector = selector;
}
public next(): { value: U, done: false } | { value: never, done: true } {
// Navigate to the next entry.
while (this.currentEntry) {
const skipNext = !!this.currentEntry.skipNext;
this.currentEntry = this.currentEntry.nextEntry;
if (!skipNext) {
break;
}
}
if (this.currentEntry) {
return { value: this.selector(this.currentEntry.key!, this.currentEntry.value!), done: false };
}
else {
return { value: undefined as never, done: true };
}
}
}
return class <T> implements Map<T> {
private data = createDictionaryObject<MapEntry<T>>();
public size = 0;
// Linked list references for iterators.
// See https://github.com/Microsoft/TypeScript/pull/27292
// for more information.
/**
* The first entry in the linked list.
* Note that this is only a stub that serves as starting point
* for iterators and doesn't contain a key and a value.
*/
private readonly firstEntry: MapEntry<T>;
private lastEntry: MapEntry<T>;
constructor() {
// Create a first (stub) map entry that will not contain a key
// and value but serves as starting point for iterators.
this.firstEntry = {};
// When the map is empty, the last entry is the same as the
// first one.
this.lastEntry = this.firstEntry;
}
get(key: string): T | undefined {
const entry = this.data[key] as MapEntry<T> | undefined;
return entry && entry.value!;
}
set(key: string, value: T): this {
if (!this.has(key)) {
this.size++;
// Create a new entry that will be appended at the
// end of the linked list.
const newEntry: MapEntry<T> = {
key,
value
};
this.data[key] = newEntry;
// Adjust the references.
const previousLastEntry = this.lastEntry;
previousLastEntry.nextEntry = newEntry;
newEntry.previousEntry = previousLastEntry;
this.lastEntry = newEntry;
}
else {
this.data[key].value = value;
}
return this;
}
has(key: string): boolean {
// eslint-disable-next-line no-in-operator
return key in this.data;
}
delete(key: string): boolean {
if (this.has(key)) {
this.size--;
const entry = this.data[key];
delete this.data[key];
// Adjust the linked list references of the neighbor entries.
const previousEntry = entry.previousEntry!;
previousEntry.nextEntry = entry.nextEntry;
if (entry.nextEntry) {
entry.nextEntry.previousEntry = previousEntry;
}
// When the deleted entry was the last one, we need to
// adjust the lastEntry reference.
if (this.lastEntry === entry) {
this.lastEntry = previousEntry;
}
// Adjust the forward reference of the deleted entry
// in case an iterator still references it. This allows us
// to throw away the entry, but when an active iterator
// (which points to the current entry) continues, it will
// navigate to the entry that originally came before the
// current one and skip it.
entry.previousEntry = undefined;
entry.nextEntry = previousEntry;
entry.skipNext = true;
return true;
}
return false;
}
clear(): void {
this.data = createDictionaryObject<MapEntry<T>>();
this.size = 0;
// Reset the linked list. Note that we must adjust the forward
// references of the deleted entries to ensure iterators stuck
// in the middle of the list don't continue with deleted entries,
// but can continue with new entries added after the clear()
// operation.
const firstEntry = this.firstEntry;
let currentEntry = firstEntry.nextEntry;
while (currentEntry) {
const nextEntry = currentEntry.nextEntry;
currentEntry.previousEntry = undefined;
currentEntry.nextEntry = firstEntry;
currentEntry.skipNext = true;
currentEntry = nextEntry;
}
firstEntry.nextEntry = undefined;
this.lastEntry = firstEntry;
}
keys(): Iterator<string> {
return new MapIterator(this.firstEntry, key => key);
}
values(): Iterator<T> {
return new MapIterator(this.firstEntry, (_key, value) => value);
}
entries(): Iterator<[string, T]> {
return new MapIterator(this.firstEntry, (key, value) => [key, value] as [string, T]);
}
forEach(action: (value: T, key: string) => void): void {
const iterator = this.entries();
while (true) {
const iterResult = iterator.next();
if (iterResult.done) {
break;
}
const [key, value] = iterResult.value;
action(value, key);
}
}
};
}
}

Some files were not shown because too many files have changed in this diff Show More