From 648a795ecaa5bb3c108923cc2be3d3b57e179031 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 17 Jan 2019 17:21:39 -0800 Subject: [PATCH] Update LKG. --- lib/enu/diagnosticMessages.generated.json.lcg | 106 +- lib/lib.es5.d.ts | 14 +- lib/protocol.d.ts | 2 + lib/tr/diagnosticMessages.generated.json | 2 +- lib/tsc.js | 2364 +++++++---- lib/tsserver.js | 3677 ++++++++++------ lib/tsserverlibrary.d.ts | 35 +- lib/tsserverlibrary.js | 3755 +++++++++++------ lib/typescript.d.ts | 23 +- lib/typescript.js | 3357 ++++++++++----- lib/typescriptServices.d.ts | 23 +- lib/typescriptServices.js | 3357 ++++++++++----- lib/typingsInstaller.js | 2572 +++++++---- lib/zh-tw/diagnosticMessages.generated.json | 6 +- 14 files changed, 12758 insertions(+), 6535 deletions(-) diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 61eb41991c4..d6970a39e90 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -27,6 +27,18 @@ + + + + + + + + + + + + @@ -1005,6 +1017,12 @@ + + + + + + @@ -2403,6 +2421,12 @@ + + + + + + @@ -3189,12 +3213,6 @@ - - - - - - @@ -3741,12 +3759,6 @@ - - - - - - @@ -3867,6 +3879,12 @@ + + + + + + @@ -4773,6 +4791,12 @@ + + + + + + @@ -5805,6 +5829,18 @@ + + + + + + + + + + + + @@ -5823,6 +5859,12 @@ + + + + + + @@ -5871,9 +5913,9 @@ - + - + @@ -5907,18 +5949,6 @@ - - - - - - - - - - - - @@ -6189,6 +6219,12 @@ + + + + + + @@ -6387,6 +6423,12 @@ + + + + + + @@ -6519,6 +6561,12 @@ + + + + + + @@ -6789,6 +6837,12 @@ + + + + + + diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index d1a9d6f0d2a..50c0326ee1b 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -315,6 +315,16 @@ interface FunctionConstructor { declare const Function: FunctionConstructor; +/** + * Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter. + */ +type ThisParameterType = T extends (this: unknown, ...args: any[]) => any ? unknown : T extends (this: infer U, ...args: any[]) => any ? U : unknown; + +/** + * Removes the 'this' parameter from a function type. + */ +type OmitThisParameter = unknown extends ThisParameterType ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T; + interface CallableFunction extends Function { /** * Calls the function with the specified object as the this value and the elements of specified array as the arguments. @@ -337,7 +347,7 @@ interface CallableFunction extends Function { * @param thisArg The object to be used as the this object. * @param args Arguments to bind to the parameters of the function. */ - bind(this: (this: T, ...args: A) => R, thisArg: T): (...args: A) => R; + bind(this: T, thisArg: ThisParameterType): OmitThisParameter; bind(this: (this: T, arg0: A0, ...args: A) => R, thisArg: T, arg0: A0): (...args: A) => R; bind(this: (this: T, arg0: A0, arg1: A1, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1): (...args: A) => R; bind(this: (this: T, arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: T, arg0: A0, arg1: A1, arg2: A2): (...args: A) => R; @@ -367,7 +377,7 @@ interface NewableFunction extends Function { * @param thisArg The object to be used as the this object. * @param args Arguments to bind to the parameters of the function. */ - bind(this: new (...args: A) => R, thisArg: any): new (...args: A) => R; + bind(this: T, thisArg: any): T; bind(this: new (arg0: A0, ...args: A) => R, thisArg: any, arg0: A0): new (...args: A) => R; bind(this: new (arg0: A0, arg1: A1, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1): new (...args: A) => R; bind(this: new (arg0: A0, arg1: A1, arg2: A2, ...args: A) => R, thisArg: any, arg0: A0, arg1: A1, arg2: A2): new (...args: A) => R; diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 49a507b9881..b02f7ae70d5 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -2279,6 +2279,8 @@ declare namespace ts.server.protocol { readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; readonly lazyConfiguredProjectsFromExternalProject?: boolean; + readonly allowRenameOfImportPath?: boolean; + readonly providePrefixAndSuffixTextForRename?: boolean; } interface CompilerOptions { allowJs?: boolean; diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 284c223d0cd..892fc74d391 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -847,7 +847,7 @@ "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496": "ES3 ve ES5'te bulunan bir ok işlevinde 'arguments' nesnesine başvuru yapılamaz. Standart bir işlev ifadesi kullanmayı göz önünde bulundurun.", "The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES3_and_ES5_Consider_usi_2522": "ES3 ve ES5'te 'arguments' nesnesine zaman uyumsuz bir işlev veya metot içinde başvurulamaz. Standart bir işlev veya metot kullanmayı düşünün.", "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313": "'if' deyiminin gövdesi boş deyim olamaz.", - "The_character_set_of_the_input_files_6163": "Girdi dosyalarının karakter kümesi.", + "The_character_set_of_the_input_files_6163": "Giriş dosyalarının karakter kümesi.", "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "İçeren işlev veya modül gövdesi, denetim akışı analizi için çok büyük.", "The_current_host_does_not_support_the_0_option_5001": "Mevcut ana bilgisayar '{0}' seçeneğini desteklemiyor.", "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Bir dışarı aktarma ataması ifadesi, çevresel bağlamda bir tanımlayıcı veya tam ad olmalıdır.", diff --git a/lib/tsc.js b/lib/tsc.js index 537612cb376..f90b479ba1c 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -61,7 +61,7 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook var ts; (function (ts) { ts.versionMajorMinor = "3.3"; - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = ts.versionMajorMinor + ".0-rc"; })(ts || (ts = {})); (function (ts) { ts.emptyArray = []; @@ -1106,6 +1106,18 @@ var ts; return result; } ts.extend = extend; + function copyProperties(first, second) { + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + first[id] = second[id]; + } + } + } + ts.copyProperties = copyProperties; + function maybeBind(obj, fn) { + return fn ? fn.bind(obj) : undefined; + } + ts.maybeBind = maybeBind; function createMultiMap() { var map = createMap(); map.add = multiMapAdd; @@ -1699,7 +1711,11 @@ var ts; } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; function fill(length, cb) { - return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + var result = Array(length); + for (var i = 0; i < length; i++) { + result[i] = cb(i); + } + return result; } ts.fill = fill; })(ts || (ts = {})); @@ -2160,6 +2176,11 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + ts.generateDjb2Hash = generateDjb2Hash; function setStackTraceLimit() { if (Error.stackTraceLimit < 100) { Error.stackTraceLimit = 100; @@ -2910,10 +2931,6 @@ var ts; return; } } - function generateDjb2Hash(data) { - var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); - return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); - } function createMD5HashUsingNativeCrypto(data) { var hash = _crypto.createHash("md5"); hash.update(data); @@ -3258,6 +3275,9 @@ var ts; Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), + An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."), + A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."), + A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -3413,8 +3433,6 @@ var ts; Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), - Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), - Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), @@ -3428,7 +3446,7 @@ var ts; A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), - In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values: diag(2474, ts.DiagnosticCategory.Error, "const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values_2474", "const enum member initializers can only contain literal values and other computed enum values."), 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: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'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."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), @@ -3444,11 +3462,11 @@ var ts; The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), - Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Tuple_type_0_of_length_1_has_no_element_at_index_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493", "Tuple type '{0}' of length '{1}' has no element at index '{2}'."), Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), - Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export: diag(2497, ts.DiagnosticCategory.Error, "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497", "This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export."), Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), @@ -3637,6 +3655,11 @@ var ts; Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), + No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments: diag(2743, ts.DiagnosticCategory.Error, "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743", "No overload expects {0} type arguments, but overloads do exist that expect either {1} or {2} type arguments."), + Type_parameter_defaults_can_only_reference_previously_declared_type_parameters: diag(2744, ts.DiagnosticCategory.Error, "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744", "Type parameter defaults can only reference previously declared type parameters."), + This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."), + This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."), + _0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -3986,6 +4009,7 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -4064,6 +4088,7 @@ var ts; JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), + Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -4200,6 +4225,7 @@ var ts; Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), + Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"), }; })(ts || (ts = {})); var ts; @@ -4374,14 +4400,12 @@ var ts; return result; } ts.computeLineStarts = computeLineStarts; - function getPositionOfLineAndCharacter(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); + function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) { + return sourceFile.getPositionOfLineAndCharacter ? + sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) : + computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; - function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, true); - } - ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { if (line < 0 || line >= lineStarts.length) { if (allowEdits) { @@ -4885,6 +4909,7 @@ var ts; result = text.substring(start, end); } if (decimalFragment !== undefined || tokenFlags & 16) { + checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16)); return { type: 8, value: "" + +result @@ -4893,9 +4918,29 @@ var ts; else { tokenValue = result; var type = checkBigIntSuffix(); + checkForIdentifierStartAfterNumericLiteral(start); return { type: type, value: tokenValue }; } } + function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { + if (!isIdentifierStart(text.charCodeAt(pos), languageVersion)) { + return; + } + var identifierStart = pos; + var length = scanIdentifierParts().length; + if (length === 1 && text[identifierStart] === "n") { + if (isScientific) { + error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1); + } + else { + error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1); + } + } + else { + error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length); + pos = identifierStart; + } + } function scanOctalDigits() { var start = pos; while (isOctalDigit(text.charCodeAt(pos))) { @@ -6638,7 +6683,7 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, node.pos); } var isMissing = nodeIsMissing(errorNode); - var pos = isMissing + var pos = isMissing || ts.isJsxText(node) ? errorNode.pos : ts.skipTrivia(sourceFile.text, errorNode.pos); if (isMissing) { @@ -7723,6 +7768,7 @@ var ts; return node.initializer; } } + ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration; function getSingleVariableOfVariableStatement(node) { return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } @@ -9534,10 +9580,10 @@ var ts; } if (getCheckFlags(s) & 6) { var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 ? 8 : - checkFlags & 64 ? 4 : + var accessModifier = checkFlags & 512 ? 8 : + checkFlags & 128 ? 4 : 16; - var staticModifier = checkFlags & 512 ? 32 : 0; + var staticModifier = checkFlags & 1024 ? 32 : 0; return accessModifier | staticModifier; } if (s.flags & 4194304) { @@ -9756,6 +9802,10 @@ var ts; || kind === 290; } ts.isTypeNodeKind = isTypeNodeKind; + function isAccessExpression(node) { + return node.kind === 189 || node.kind === 190; + } + ts.isAccessExpression = isAccessExpression; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -12212,6 +12262,7 @@ var ts; return path; } ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; function comparePathsWorker(a, b, componentComparer) { if (a === b) return 0; @@ -12219,14 +12270,24 @@ var ts; return -1; if (b === undefined) return 1; + var aRoot = a.substring(0, ts.getRootLength(a)); + var bRoot = b.substring(0, ts.getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0) { + return result; + } + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 0; i < sharedLength; i++) { - var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; - var result = stringComparer(aComponents[i], bComponents[i]); - if (result !== 0) { - return result; + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0) { + return result_1; } } return ts.compareValues(aComponents.length, bComponents.length); @@ -13474,15 +13535,15 @@ var ts; if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6) { - var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, false, undefined, undefined); - result_1.referencedFiles = ts.emptyArray; - result_1.typeReferenceDirectives = ts.emptyArray; - result_1.libReferenceDirectives = ts.emptyArray; - result_1.amdDependencies = ts.emptyArray; - result_1.hasNoDefaultLib = false; - result_1.pragmas = ts.emptyMap; - return result_1; + var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, false, undefined, undefined); + result_2.referencedFiles = ts.emptyArray; + result_2.typeReferenceDirectives = ts.emptyArray; + result_2.libReferenceDirectives = ts.emptyArray; + result_2.amdDependencies = ts.emptyArray; + result_2.hasNoDefaultLib = false; + result_2.pragmas = ts.emptyMap; + return result_2; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); @@ -14224,20 +14285,11 @@ var ts; return parseElement(); } function currentNode(parsingContext) { - if (parseErrorBeforeNextFinishedNode) { - return undefined; - } - if (!syntaxCursor) { + if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } var node = syntaxCursor.currentNode(scanner.getStartPos()); - if (ts.nodeIsMissing(node)) { - return undefined; - } - if (node.intersectsChange) { - return undefined; - } - if (ts.containsParseError(node)) { + if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) { return undefined; } var nodeContextFlags = node.flags & 12679168; @@ -14257,6 +14309,22 @@ var ts; nextToken(); return node; } + function isReusableParsingContext(parsingContext) { + switch (parsingContext) { + case 5: + case 2: + case 0: + case 1: + case 3: + case 6: + case 4: + case 8: + case 17: + case 16: + return true; + } + return false; + } function canReuseNode(node, parsingContext) { switch (parsingContext) { case 5: @@ -14276,17 +14344,6 @@ var ts; case 17: case 16: return isReusableParameter(node); - case 18: - return false; - case 22: - case 19: - case 21: - case 20: - case 11: - case 12: - case 7: - case 13: - case 14: } return false; } @@ -18506,17 +18563,18 @@ var ts; var typeReferenceDirectives_1 = context.typeReferenceDirectives; var libReferenceDirectives_1 = context.libReferenceDirectives; ts.forEach(ts.toArray(entryOrList), function (arg) { + var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path; if (arg.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; } - else if (arg.arguments.types) { - typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + else if (types) { + typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value }); } - else if (arg.arguments.lib) { - libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + else if (lib) { + libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value }); } - else if (arg.arguments.path) { - referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + else if (path) { + referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value }); } else { reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); @@ -20065,12 +20123,12 @@ var ts; } function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, !configParseResult.configFileSpecs ? function (_) { return false; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); - }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), exclude: configParseResult.configFileSpecs.validatedExcludeSpecs } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); @@ -20088,23 +20146,23 @@ var ts; } function matchesSpecs(path, includeSpecs, excludeSpecs) { if (!includeSpecs) - return function (_) { return false; }; + return function (_) { return true; }; var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { - return function (path) { return includeRe.test(path) && !excludeRe.test(path); }; + return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; } - return function (path) { return includeRe.test(path); }; + return function (path) { return !includeRe.test(path); }; } if (excludeRe) { - return function (path) { return !excludeRe.test(path); }; + return function (path) { return excludeRe.test(path); }; } - return function (_) { return false; }; + return function (_) { return true; }; } function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") { return undefined; } else if (optionDefinition.type === "list") { @@ -20242,7 +20300,7 @@ var ts; result.push(tab + "}"); } result.push("}"); - return result.join(newLine); + return result.join(newLine) + newLine; } } ts.generateTSConfig = generateTSConfig; @@ -22111,6 +22169,9 @@ var ts; if (symbolFlags & (32 | 64 | 2048 | 4096) && !symbol.members) { symbol.members = ts.createSymbolTable(); } + if (symbol.constEnumOnlyModule && (symbol.flags & (16 | 32 | 256))) { + symbol.constEnumOnlyModule = false; + } if (symbolFlags & 67220415) { setValueDeclaration(symbol, node); } @@ -22502,7 +22563,7 @@ var ts; } function isNarrowableReference(expr) { return expr.kind === 72 || expr.kind === 100 || expr.kind === 98 || - ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || ts.isElementAccessExpression(expr) && expr.argumentExpression && (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && isNarrowableReference(expr.expression); @@ -25491,10 +25552,10 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(262144); - var markerSubType = createType(262144); + var markerSuperType = createTypeParameter(); + var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(262144); + var markerOtherType = createTypeParameter(); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, undefined, 0, false, false); @@ -25600,7 +25661,6 @@ var ts; var _jsxFactoryEntity; var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); - var definitelyAssignableRelation = ts.createMap(); var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); @@ -26161,13 +26221,15 @@ var ts; } } break; + case 197: + if (compilerOptions.target >= 2) { + break; + } case 156: - case 155: case 157: case 158: case 159: case 239: - case 197: if (meaning & 3 && name === "arguments") { result = argumentsSymbol; break loop; @@ -26205,7 +26267,7 @@ var ts; lastLocation = location; location = location.parent; } - if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol) && !isInTypeQuery(originalLocation)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { result.isReferenced |= meaning; } if (!result) { @@ -26268,7 +26330,8 @@ var ts; } } if (result && isInExternalModule && (meaning & 67220415) === 67220415 && !(originalLocation.flags & 2097152)) { - if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { + var merged = getMergedSymbol(result); + if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); } } @@ -26941,7 +27004,10 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { if (!(symbol.flags & (1536 | 3)) && !ts.getDeclarationOfKind(symbol, 279)) { - error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 + ? "allowSyntheticDefaultImports" + : "esModuleInterop"; + error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); return symbol; } if (compilerOptions.esModuleInterop) { @@ -27219,6 +27285,12 @@ var ts; function createTypeofType() { return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); } + function createTypeParameter(symbol) { + var type = createType(262144); + if (symbol) + type.symbol = symbol; + return type; + } function isReservedMemberName(name) { return name.charCodeAt(0) === 95 && name.charCodeAt(1) === 95 && @@ -28083,12 +28155,12 @@ var ts; return ts.createKeywordTypeNode(120); } function addPropertyToElementList(propertySymbol, context, typeElements) { - var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048); + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 4096); var propertyType = propertyIsReverseMapped && context.flags & 33554432 ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 2048) { var decl = ts.first(propertySymbol.declarations); if (hasLateBindableName(decl)) { trackComputedName(decl.name, saveEnclosingDeclaration, context); @@ -28252,7 +28324,7 @@ var ts; } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; - var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384; var dotDotDotToken = isRest ? ts.createToken(25) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -28261,7 +28333,7 @@ var ts; cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); - var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096; + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192; var questionToken = isOptional ? ts.createToken(56) : undefined; var parameterNode = ts.createParameter(undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, undefined); context.approximateLength += ts.symbolName(parameterSymbol).length + 3; @@ -28631,6 +28703,21 @@ var ts; function isDefaultBindingContext(location) { return location.kind === 279 || ts.isAmbientModule(location); } + function getNameOfSymbolFromNameType(symbol, context) { + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 384) { + var name = "" + nameType.value; + if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { + return "\"" + ts.escapeString(name, 34) + "\""; + } + return name; + } + if (nameType.flags & 8192) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; + } + } + } function getNameOfSymbolAsWritten(symbol, context) { if (context && symbol.escapedName === "default" && !(context.flags & 16384) && (!(context.flags & 16777216) || @@ -28640,12 +28727,18 @@ var ts; } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - var name = ts.getNameOfDeclaration(declaration); - if (name) { + var name_2 = ts.getNameOfDeclaration(declaration); + if (name_2) { if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { return ts.symbolName(symbol); } - return ts.declarationNameToString(name); + if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 2048) && symbol.nameType && symbol.nameType.flags & 384) { + var result = getNameOfSymbolFromNameType(symbol, context); + if (result !== undefined) { + return result; + } + } + return ts.declarationNameToString(name_2); } if (declaration.parent && declaration.parent.kind === 237) { return ts.declarationNameToString(declaration.parent.name); @@ -28660,16 +28753,8 @@ var ts; return declaration.kind === 209 ? "(Anonymous class)" : "(Anonymous function)"; } } - var nameType = symbol.nameType; - if (nameType) { - if (nameType.flags & 128 && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { - return "\"" + ts.escapeString(nameType.value, 34) + "\""; - } - if (nameType && nameType.flags & 8192) { - return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; - } - } - return ts.symbolName(symbol); + var name = getNameOfSymbolFromNameType(symbol, context); + return name !== undefined ? name : ts.symbolName(symbol); } function isDeclarationVisible(node) { if (node) { @@ -28854,6 +28939,9 @@ var ts; var prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } + function getTypeOfPropertyOrIndexSignature(type, name) { + return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1) || getIndexTypeOfType(type, 0) || unknownType; + } function isTypeAny(type) { return type && (type.flags & 1) !== 0; } @@ -28898,6 +28986,55 @@ var ts; var numberIndexInfo = getIndexInfoOfType(source, 1); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); } + function getFlowTypeOfDestructuring(node, declaredType) { + var reference = getSyntheticElementAccess(node); + return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType; + } + function getSyntheticElementAccess(node) { + var parentAccess = getParentElementAccess(node); + if (parentAccess && parentAccess.flowNode) { + var propName = getDestructuringPropertyName(node); + if (propName) { + var result = ts.createNode(190, node.pos, node.end); + result.parent = node; + result.expression = parentAccess; + var literal = ts.createNode(10, node.pos, node.end); + literal.parent = result; + literal.text = propName; + result.argumentExpression = literal; + result.flowNode = parentAccess.flowNode; + return result; + } + } + } + function getParentElementAccess(node) { + var ancestor = node.parent.parent; + switch (ancestor.kind) { + case 186: + case 275: + return getSyntheticElementAccess(ancestor); + case 187: + return getSyntheticElementAccess(node.parent); + case 237: + return ancestor.initializer; + case 204: + return ancestor.right; + } + } + function getDestructuringPropertyName(node) { + var parent = node.parent; + if (node.kind === 186 && parent.kind === 184) { + return getLiteralPropertyNameText(node.propertyName || node.name); + } + if (node.kind === 275 || node.kind === 276) { + return getLiteralPropertyNameText(node.name); + } + return "" + parent.elements.indexOf(node); + } + function getLiteralPropertyNameText(name) { + var type = getLiteralTypeFromPropertyName(name); + return type.flags & (128 | 256) ? "" + type.value : undefined; + } function getTypeForBindingElement(declaration) { var pattern = declaration.parent; var parentType = getTypeForBindingElementParent(pattern.parent); @@ -28931,9 +29068,9 @@ var ts; } else { var name = declaration.propertyName || declaration.name; - var exprType = getLiteralTypeFromPropertyName(name); - var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); - type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); + var indexType = getLiteralTypeFromPropertyName(name); + var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); } } else { @@ -28944,20 +29081,13 @@ var ts; mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } + else if (isArrayLikeType(parentType)) { + var indexType = getLiteralType(index_1); + var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, declaration.name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); + } else { - var index_2 = pattern.elements.indexOf(declaration); - type = everyType(parentType, isTupleLikeType) ? - getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : - elementType; - if (!type) { - if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); - } - else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); - } - return errorType; - } + type = elementType; } } if (strictNullChecks && declaration.initializer && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768)) { @@ -29350,12 +29480,11 @@ var ts; if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) { return anyType; } - if (ts.isSourceFile(declaration)) { - var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - if (!jsonSourceFile.statements.length) { + if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) { + if (!declaration.statements.length) { return emptyObjectType; } - var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + var type_1 = getWidenedLiteralType(checkExpression(declaration.statements[0].expression)); if (type_1.flags & 524288) { return getRegularTypeOfObjectLiteral(type_1); } @@ -29365,6 +29494,9 @@ var ts; return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); } if (!pushTypeResolution(symbol, 0)) { + if (symbol.flags & 512) { + return getTypeOfFuncClassEnumModule(symbol); + } return errorType; } var type; @@ -29378,7 +29510,8 @@ var ts; || ts.isClassDeclaration(declaration) || ts.isFunctionDeclaration(declaration) || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { + || ts.isMethodSignature(declaration) + || ts.isSourceFile(declaration)) { if (symbol.flags & (16 | 8192 | 32 | 384 | 512)) { return getTypeOfFuncClassEnumModule(symbol); } @@ -29415,6 +29548,9 @@ var ts; return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } if (!popTypeResolution()) { + if (symbol.flags & 512) { + return getTypeOfFuncClassEnumModule(symbol); + } type = reportCircularityError(symbol); } return type; @@ -29596,7 +29732,7 @@ var ts; if (ts.getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } - if (ts.getCheckFlags(symbol) & 2048) { + if (ts.getCheckFlags(symbol) & 4096) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -29927,9 +30063,8 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(262144); + type.thisType = createTypeParameter(symbol); type.thisType.isThisType = true; - type.thisType.symbol = symbol; type.thisType.constraint = type; } } @@ -30060,19 +30195,11 @@ var ts; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var type = createType(262144); - type.symbol = symbol; - links.declaredType = type; - } - return links.declaredType; + return links.declaredType || (links.declaredType = createTypeParameter(symbol)); } function getDeclaredTypeOfAlias(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); - } - return links.declaredType; + return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol))); } function getDeclaredTypeOfSymbol(symbol) { return tryGetDeclaredTypeOfSymbol(symbol) || errorType; @@ -30216,7 +30343,7 @@ var ts; return ts.Debug.fail(); } function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { - ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024), "Expected a late-bound symbol."); + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 2048), "Expected a late-bound symbol."); symbol.flags |= symbolFlags; getSymbolLinks(member.symbol).lateSymbol = symbol; if (!symbol.declarations) { @@ -30242,14 +30369,14 @@ var ts; var symbolFlags = decl.symbol.flags; var lateSymbol = lateSymbols.get(memberName); if (!lateSymbol) - lateSymbols.set(memberName, lateSymbol = createSymbol(0, memberName, 1024)); + lateSymbols.set(memberName, lateSymbol = createSymbol(0, memberName, 2048)); var earlySymbol = earlySymbols && earlySymbols.get(memberName); if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) { var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_2 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); - lateSymbol = createSymbol(0, memberName, 1024); + var name_3 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + lateSymbol = createSymbol(0, memberName, 2048); } lateSymbol.nameType = type; addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); @@ -30408,8 +30535,8 @@ var ts; var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; var restParams = ts.map(elementTypes, function (t, i) { var name = getParameterNameAtPosition(sig, restIndex_1 + i); - var checkFlags = i === tupleRestIndex_1 ? 8192 : - i >= minLength_1 ? 4096 : 0; + var checkFlags = i === tupleRestIndex_1 ? 16384 : + i >= minLength_1 ? 8192 : 0; var symbol = createSymbol(1, name, checkFlags); symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; return symbol; @@ -30475,7 +30602,13 @@ var ts; } function getUnionSignatures(signatureLists) { var result; + var indexWithLengthOverOne; for (var i = 0; i < signatureLists.length; i++) { + if (signatureLists[i].length === 0) + return ts.emptyArray; + if (signatureLists[i].length > 1) { + indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; + } for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { var signature = _a[_i]; if (!result || !findMatchingSignature(result, signature, false, true, true)) { @@ -30497,8 +30630,73 @@ var ts; } } } + if (!ts.length(result) && indexWithLengthOverOne !== -1) { + var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; + var results = masterList.slice(); + var _loop_5 = function (signatures) { + if (signatures !== masterList) { + var signature_1 = signatures[0]; + ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); + results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); + if (!results) { + return "break"; + } + } + }; + for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) { + var signatures = signatureLists_1[_b]; + var state_2 = _loop_5(signatures); + if (state_2 === "break") + break; + } + result = results; + } return result || ts.emptyArray; } + function combineUnionThisParam(left, right) { + if (!left || !right) { + return left || right; + } + var thisType = getUnionType([getTypeOfSymbol(left), getTypeOfSymbol(right)], 2); + return createSymbolWithType(left, thisType); + } + function combineUnionParameters(left, right) { + var longest = getParameterCount(left) >= getParameterCount(right) ? left : right; + var shorter = longest === left ? right : left; + var longestCount = getParameterCount(longest); + var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (var i = 0; i < longestCount; i++) { + var longestParamType = tryGetTypeAtPosition(longest, i); + var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + var unionParamType = getIntersectionType([longestParamType, shorterParamType]); + var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + var leftName = getParameterNameAtPosition(left, i); + var rightName = getParameterNameAtPosition(right, i); + var paramSymbol = createSymbol(1 | (isOptional && !isRestParam ? 16777216 : 0), leftName === rightName ? leftName : "arg" + i); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + var restParamSymbol = createSymbol(1, "args"); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfUnionMembers(left, right) { + var declaration = left.declaration; + var params = combineUnionParameters(left, right); + var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); + var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + var hasRestParam = left.hasRestParameter || right.hasRestParameter; + var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; + var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, undefined, undefined, minArgCount, hasRestParam, hasLiteralTypes); + result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); + return result; + } function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; @@ -30514,7 +30712,7 @@ var ts; return createIndexInfo(getUnionType(indexTypes, 2), isAnyReadonly); } function resolveUnionTypeMembers(type) { - var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0); })); + var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0); })); var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1); })); var stringIndexInfo = getUnionIndexInfo(type.types, 0); var numberIndexInfo = getUnionIndexInfo(type.types, 1); @@ -30548,7 +30746,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_5 = function (i) { + var _loop_6 = function (i) { var t = type.types[i]; if (mixinCount === 0 || mixinCount === types.length && i === 0 || !isMixinConstructorType(t)) { var signatures = getSignaturesOfType(t, 1); @@ -30566,7 +30764,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1)); }; for (var i = 0; i < types.length; i++) { - _loop_5(i); + _loop_6(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -30633,7 +30831,7 @@ var ts; var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { var prop = _a[_i]; - var checkFlags = 2048 | (readonlyMask && isReadonlySymbol(prop) ? 8 : 0); + var checkFlags = 4096 | (readonlyMask && isReadonlySymbol(prop) ? 8 : 0); var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.escapedName, checkFlags); inferredProp.declarations = prop.declarations; inferredProp.nameType = prop.nameType; @@ -30644,6 +30842,34 @@ var ts; } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); } + function getLowerBoundOfKeyType(type) { + if (type.flags & (1 | 131068)) { + return type; + } + if (type.flags & 4194304) { + return getIndexType(getApparentType(type.type)); + } + if (type.flags & 16777216) { + return getLowerBoundOfConditionalType(type); + } + if (type.flags & 1048576) { + return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); + } + if (type.flags & 2097152) { + return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); + } + return neverType; + } + function getLowerBoundOfConditionalType(type) { + if (type.root.isDistributive) { + var constraint = getLowerBoundOfKeyType(type.checkType); + if (constraint !== type.checkType) { + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); var stringIndexInfo; @@ -30668,8 +30894,7 @@ var ts; } } else { - var iterationType = constraintType.flags & 4194304 ? getIndexType(getApparentType(constraintType.type)) : constraintType; - forEachType(iterationType, addMemberForKeyType); + forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); function addMemberForKeyType(t) { @@ -30833,7 +31058,7 @@ var ts; return list.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); }); } function getAllPossiblePropertiesOfTypes(types) { @@ -30891,7 +31116,7 @@ var ts; if (type.root.isDistributive) { var simplified = getSimplifiedType(type.checkType); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; - if (constraint) { + if (constraint && constraint !== type.checkType) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); if (!(instantiated.flags & 131072)) { @@ -31096,10 +31321,10 @@ var ts; commonFlags &= prop.flags; props = ts.appendIfUnique(props, prop); checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | - (!(modifiers & 24) ? 64 : 0) | - (modifiers & 16 ? 128 : 0) | - (modifiers & 8 ? 256 : 0) | - (modifiers & 32 ? 512 : 0); + (!(modifiers & 24) ? 128 : 0) | + (modifiers & 16 ? 256 : 0) | + (modifiers & 8 ? 512 : 0) | + (modifiers & 32 ? 1024 : 0); if (!isPrototypeProperty(prop)) { syntheticFlag = 2; } @@ -31123,39 +31348,38 @@ var ts; return props[0]; } var declarations; - var commonType; + var firstType; var nameType; var propTypes = []; - var first = true; - var commonValueDeclaration; + var firstValueDeclaration; var hasNonUniformValueDeclaration = false; for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { var prop = props_1[_b]; - if (!commonValueDeclaration) { - commonValueDeclaration = prop.valueDeclaration; + if (!firstValueDeclaration) { + firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== commonValueDeclaration) { + else if (prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = ts.addRange(declarations, prop.declarations); var type = getTypeOfSymbol(prop); - if (first) { - commonType = type; + if (!firstType) { + firstType = type; nameType = prop.nameType; - first = false; } - else { - if (type !== commonType) { - checkFlags |= 32; - } + else if (type !== firstType) { + checkFlags |= 32; + } + if (isLiteralType(type)) { + checkFlags |= 64; } propTypes.push(type); } ts.addRange(propTypes, indexTypes); var result = createSymbol(4 | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; - if (!hasNonUniformValueDeclaration && commonValueDeclaration) { - result.valueDeclaration = commonValueDeclaration; + if (!hasNonUniformValueDeclaration && firstValueDeclaration) { + result.valueDeclaration = firstValueDeclaration; } result.declarations = declarations; result.nameType = nameType; @@ -31324,18 +31548,16 @@ var ts; var numTypeArguments = ts.length(typeArguments); if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { var result = typeArguments ? typeArguments.slice() : []; - var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); for (var i = numTypeArguments; i < numTypeParameters; i++) { - result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + result[i] = errorType; } + var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny); for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, result); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { defaultType = anyType; } - result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType; } result.length = typeParameters.length; return result; @@ -31411,7 +31633,7 @@ var ts; var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); - var syntheticArgsSymbol = createSymbol(3, "args", 8192); + var syntheticArgsSymbol = createSymbol(3, "args", 16384); syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; if (lastParamVariadicType) { parameters.pop(); @@ -32209,7 +32431,7 @@ var ts; if (arity) { typeParameters = new Array(arity); for (var i = 0; i < arity; i++) { - var typeParameter = typeParameters[i] = createType(262144); + var typeParameter = typeParameters[i] = createTypeParameter(); if (i < maxLength) { var property = createSymbol(4 | (i >= minLength ? 16777216 : 0), "" + i); property.type = typeParameter; @@ -32231,7 +32453,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(262144); + type.thisType = createTypeParameter(); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -32671,8 +32893,13 @@ var ts; if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { - var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + if (prop.escapedName === "default") { + type = getLiteralType("default"); + } + else { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + } } if (type && type.flags & include) { return type; @@ -32753,13 +32980,13 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 190 ? accessNode : undefined; - var propName = isTypeUsableAsLateBoundName(indexType) - ? getLateBoundNameFromType(indexType) - : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) - ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) - : accessNode && ts.isPropertyName(accessNode) - ? ts.getPropertyNameForPropertyNameNode(accessNode) - : undefined; + var propName = isTypeUsableAsLateBoundName(indexType) ? + getLateBoundNameFromType(indexType) : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, false) ? + ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : + accessNode && ts.isPropertyName(accessNode) ? + ts.getPropertyNameForPropertyNameNode(accessNode) : + undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { @@ -32781,7 +33008,12 @@ var ts; if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { var indexNode = getIndexNodeForAccessExpression(accessNode); - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + if (isTupleType(objectType)) { + error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName)); + } + else { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } } return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } @@ -32895,21 +33127,12 @@ var ts; } } if (isGenericMappedType(objectType)) { - return type.simplified = substituteIndexedMappedType(objectType, type); - } - if (objectType.flags & 262144) { - var constraint = getConstraintOfTypeParameter(objectType); - if (constraint && isGenericMappedType(constraint)) { - return type.simplified = substituteIndexedMappedType(constraint, type); - } + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var templateMapper = combineTypeMappers(objectType.mapper, mapper); + return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType); } return type.simplified = type; } - function substituteIndexedMappedType(objectType, type) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); - } function getIndexedAccessType(objectType, indexType, accessNode, missingType) { if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { @@ -32984,27 +33207,27 @@ var ts; if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } - var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704); + var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 | 134217728); var combinedMapper; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, undefined, 0); - if (!isDeferred) { + if (!checkTypeInstantiable) { inferTypes(context.inferences, checkType, extendsType, 32 | 64); } combinedMapper = combineTypeMappers(mapper, context); } - if (!isDeferred) { - if (extendsType.flags & 3) { + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 | 134217728)) { + if (inferredExtendsType.flags & 3) { return instantiateType(root.trueType, mapper); } if (checkType.flags & 1) { return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); } - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; - if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { return instantiateType(root.falseType, mapper); } - if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, undefined)) { + if (isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) { return instantiateType(root.trueType, combinedMapper || mapper); } } @@ -33530,12 +33753,17 @@ var ts; function createReplacementMapper(source, target, baseMapper) { return function (t) { return t === source ? target : baseMapper(t); }; } - function wildcardMapper(type) { + function permissiveMapper(type) { return type.flags & 262144 ? wildcardType : type; } + function getRestrictiveTypeParameter(tp) { + return !tp.constraint ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol)); + } + function restrictiveMapper(type) { + return type.flags & 262144 ? getRestrictiveTypeParameter(type) : type; + } function cloneTypeParameter(typeParameter) { - var result = createType(262144); - result.symbol = typeParameter.symbol; + var result = createTypeParameter(typeParameter.symbol); result.target = typeParameter; return result; } @@ -33579,7 +33807,7 @@ var ts; symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); } - var result = createSymbol(symbol.flags, symbol.escapedName, 1 | ts.getCheckFlags(symbol) & (1024 | 4096 | 8192)); + var result = createSymbol(symbol.flags, symbol.escapedName, 1 | ts.getCheckFlags(symbol) & (2048 | 8192 | 16384)); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -33814,9 +34042,13 @@ var ts; } return type; } - function getWildcardInstantiation(type) { + function getPermissiveInstantiation(type) { return type.flags & (131068 | 3 | 131072) ? type : - type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); + type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); + } + function getRestrictiveInstantiation(type) { + return type.flags & (131068 | 3 | 131072) ? type : + type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); @@ -33871,8 +34103,7 @@ var ts; return hasContextSensitiveReturnExpression(node); } function hasContextSensitiveReturnExpression(node) { - var body = node.body; - return body.kind === 218 ? false : isContextSensitive(body); + return !!node.body && node.body.kind !== 218 && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -33966,7 +34197,7 @@ var ts; case 187: return elaborateArrayLiteral(node, source, target, relation); case 268: - return elaborateJsxAttributes(node, source, target, relation); + return elaborateJsxComponents(node, source, target, relation); case 197: return elaborateArrowFunction(node, source, target, relation); } @@ -34096,8 +34327,112 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target, relation) { - return elaborateElementwise(generateJsxAttributes(node), source, target, relation); + function generateJsxChildren(node, getInvalidTextDiagnostic) { + var memberOffset, i, child, nameType, elem; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!ts.length(node.children)) + return [2]; + memberOffset = 0; + i = 0; + _a.label = 1; + case 1: + if (!(i < node.children.length)) return [3, 5]; + child = node.children[i]; + nameType = getLiteralType(i - memberOffset); + elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic); + if (!elem) return [3, 3]; + return [4, elem]; + case 2: + _a.sent(); + return [3, 4]; + case 3: + memberOffset++; + _a.label = 4; + case 4: + i++; + return [3, 1]; + case 5: return [2]; + } + }); + } + function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { + switch (child.kind) { + case 270: + return { errorNode: child, innerExpression: child.expression, nameType: nameType }; + case 11: + if (child.containsOnlyWhiteSpaces) { + break; + } + return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; + case 260: + case 261: + case 264: + return { errorNode: child, innerExpression: child, nameType: nameType }; + default: + return ts.Debug.assertNever(child, "Found invalid jsx child"); + } + } + function elaborateJsxComponents(node, source, target, relation) { + var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation); + var invalidTextDiagnostic; + if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) { + var containingElement = node.parent.parent; + var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName); + var childrenNameType = getLiteralType(childrenPropName); + var childrenTargetType = getIndexedAccessType(target, childrenNameType); + var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; }); + if (!ts.length(validChildren)) { + return result; + } + var moreThanOneRealChildren = ts.length(validChildren) > 1; + var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType); + var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); }); + if (moreThanOneRealChildren) { + if (arrayLikeTargetParts !== neverType) { + var realSource = createTupleType(checkJsxChildren(containingElement, 0)); + result = elaborateElementwise(generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic), realSource, arrayLikeTargetParts, relation) || result; + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + result = true; + error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, typeToString(childrenTargetType)); + } + } + else { + if (nonArrayLikeTargetParts !== neverType) { + var child = validChildren[0]; + var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic); + if (elem_1) { + result = elaborateElementwise((function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4, elem_1]; + case 1: + _a.sent(); + return [2]; + } + }); })(), source, target, relation) || result; + } + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + result = true; + error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, typeToString(childrenTargetType)); + } + } + } + return result; + function getInvalidTextualChildDiagnostic() { + if (!invalidTextDiagnostic) { + var tagNameText = ts.getTextOfNode(node.parent.tagName); + var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName); + var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName)); + var diagnostic = ts.Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2; + invalidTextDiagnostic = __assign({}, diagnostic, { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) }); + } + return invalidTextDiagnostic; + } } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -34323,7 +34658,7 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 524288 ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + return type.flags & 524288 ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & 67108864 ? true : type.flags & 1048576 ? ts.some(type.types, isEmptyObjectType) : type.flags & 2097152 ? ts.every(type.types, isEmptyObjectType) : @@ -34406,9 +34741,7 @@ var ts; return true; if (s & 524288 && t & 67108864) return true; - if (s & 8192 || t & 8192) - return false; - if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { + if (relation === assignableRelation || relation === comparableRelation) { if (s & 1) return true; if (s & (8 | 256) && !(s & 1024) && (t & 32 || t & 256 && t & 1024)) @@ -34555,7 +34888,7 @@ var ts; target = target.regularType; } if (source.flags & 33554432) { - source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; + source = source.substitute; } if (target.flags & 33554432) { target = target.typeVariable; @@ -34689,22 +35022,23 @@ var ts; if (!noImplicitAny && ts.getObjectFlags(target) & 16384) { return false; } - if (maybeTypeOfKind(target, 524288) && !(ts.getObjectFlags(target) & 512)) { + if (isExcessPropertyCheckTarget(target)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096); - if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && + if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } if (discriminant) { return hasExcessProperties(source, discriminant, undefined, reportErrors); } - var _loop_6 = function (prop) { + var _loop_7 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { + var errorTarget = filterType(target, isExcessPropertyCheckTarget); if (!errorNode) return { value: ts.Debug.fail() }; if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) { - reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget)); } else { var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations); @@ -34715,14 +35049,14 @@ var ts; errorNode = propDeclaration; var name = propDeclaration.name; if (ts.isIdentifier(name)) { - suggestion = getSuggestionForNonexistentProperty(name, target); + suggestion = getSuggestionForNonexistentProperty(name, errorTarget); } } if (suggestion !== undefined) { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion); } else { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget)); } } } @@ -34731,9 +35065,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_6(prop); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_7(prop); + if (typeof state_3 === "object") + return state_3.value; } } return false; @@ -34770,7 +35104,8 @@ var ts; var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || - findBestTypeForInvokable(source, target); + findBestTypeForInvokable(source, target) || + findMostOverlappyType(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], true); } return 0; @@ -34805,6 +35140,30 @@ var ts; return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); } } + function findMostOverlappyType(source, unionTarget) { + var bestMatch; + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target_1 = _a[_i]; + var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]); + if (overlap.flags & 4194304) { + bestMatch = target_1; + matchingCount = Infinity; + } + else if (overlap.flags & 1048576) { + var len = ts.length(ts.filter(overlap.types, isUnitType)); + if (len >= matchingCount) { + bestMatch = target_1; + matchingCount = len; + } + } + else if (isUnitType(overlap) && 1 >= matchingCount) { + bestMatch = target_1; + matchingCount = 1; + } + } + return bestMatch; + } function findMatchingDiscriminantType(source, target) { if (target.flags & 1048576) { var sourceProperties = getPropertiesOfObjectType(source); @@ -34955,30 +35314,27 @@ var ts; } return result; } - function getConstraintForRelation(type) { - return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); - } function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { var flags = source.flags & target.flags; if (relation === identityRelation && !(flags & 524288)) { if (flags & 4194304) { return isRelatedTo(source.type, target.type, false); } - var result_2 = 0; + var result_3 = 0; if (flags & 8388608) { - if (result_2 = isRelatedTo(source.objectType, target.objectType, false)) { - if (result_2 &= isRelatedTo(source.indexType, target.indexType, false)) { - return result_2; + if (result_3 = isRelatedTo(source.objectType, target.objectType, false)) { + if (result_3 &= isRelatedTo(source.indexType, target.indexType, false)) { + return result_3; } } } if (flags & 16777216) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_2 = isRelatedTo(source.checkType, target.checkType, false)) { - if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, false)) { - if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { - if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { - return result_2; + if (result_3 = isRelatedTo(source.checkType, target.checkType, false)) { + if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, false)) { + if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { + if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { + return result_3; } } } @@ -35020,18 +35376,17 @@ var ts; return result; } } - if (relation !== definitelyAssignableRelation) { - var simplified = getSimplifiedType(target.type); - var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); - if (constraint) { - if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1) { - return -1; - } + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1) { + return -1; } } } else if (target.flags & 8388608) { - if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + if (relation !== identityRelation && + !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { var constraint = getBaseConstraintOfType(target); if (constraint && constraint !== target) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -35069,8 +35424,8 @@ var ts; return result; } } - var constraint = getConstraintForRelation(source); - if (!constraint || (source.flags & 262144 && constraint.flags & 3)) { + var constraint = getConstraintOfType(source); + if (!constraint || (source.flags & 262144 && constraint.flags & 1)) { if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864))) { errorInfo = saveErrorInfo; return result; @@ -35104,7 +35459,7 @@ var ts; } } } - else if (relation !== definitelyAssignableRelation) { + else { var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { @@ -35122,7 +35477,7 @@ var ts; } } else { - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + if (isPartialMappedType(target) && isEmptyObjectType(source)) { return -1; } if (isGenericMappedType(target)) { @@ -35134,9 +35489,6 @@ var ts; } return 0; } - if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { - return 0; - } var sourceIsPrimitive = !!(source.flags & 131068); if (relation !== identityRelation) { source = getApparentType(source); @@ -35188,10 +35540,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_3; - if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_4; + if (result_4 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_4 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0; @@ -35201,10 +35553,10 @@ var ts; return propertiesIdenticalTo(source, target); } var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); - var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, false); if (unmatchedProperty) { if (reportErrors) { - var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, false)); if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { suppressNextError = true; @@ -35280,7 +35632,7 @@ var ts; var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; - if (ts.getCheckFlags(sourceProp) & 256 && hasDifferingDeclarations) { + if (ts.getCheckFlags(sourceProp) & 512 && hasDifferingDeclarations) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -35854,6 +36206,9 @@ var ts; function isTupleLikeType(type) { return isTupleType(type) || !!getPropertyOfType(type, "0"); } + function isArrayOrTupleLikeType(type) { + return isArrayLikeType(type) || isTupleLikeType(type); + } function getTupleElementType(type, index) { var propType = getTypeOfPropertyOfType(type, "" + index); if (propType) { @@ -36116,6 +36471,9 @@ var ts; var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 ? t : getWidenedTypeWithContext(t, unionContext_1); }); return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 : 1); } + if (type.flags & 2097152) { + return getIntersectionType(ts.sameMap(type.types, getWidenedType)); + } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); } @@ -36190,6 +36548,9 @@ var ts; break; case 186: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + if (!noImplicitAny) { + return; + } break; case 289: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); @@ -36370,8 +36731,8 @@ var ts; inferTypes([inference], sourceType, templateType); return getTypeFromInference(inference); } - function getUnmatchedProperties(source, target, requireOptionalProperties) { - var properties, _i, properties_4, targetProp, sourceProp; + function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) { + var properties, _i, properties_4, targetProp, sourceProp, targetType, sourceType; return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -36379,24 +36740,34 @@ var ts; _i = 0, properties_4 = properties; _a.label = 1; case 1: - if (!(_i < properties_4.length)) return [3, 4]; + if (!(_i < properties_4.length)) return [3, 6]; targetProp = properties_4[_i]; - if (!(requireOptionalProperties || !(targetProp.flags & 16777216))) return [3, 3]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216))) return [3, 5]; sourceProp = getPropertyOfType(source, targetProp.escapedName); if (!!sourceProp) return [3, 3]; return [4, targetProp]; case 2: _a.sent(); - _a.label = 3; + return [3, 5]; case 3: + if (!matchDiscriminantProperties) return [3, 5]; + targetType = getTypeOfSymbol(targetProp); + if (!(targetType.flags & 109440)) return [3, 5]; + sourceType = getTypeOfSymbol(sourceProp); + if (!!(sourceType.flags & 1 || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3, 5]; + return [4, targetProp]; + case 4: + _a.sent(); + _a.label = 5; + case 5: _i++; return [3, 1]; - case 4: return [2]; + case 6: return [2]; } }); } - function getUnmatchedProperty(source, target, requireOptionalProperties) { - return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; + function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next().value; } function tupleTypesDefinitelyUnrelated(source, target) { return target.target.minLength > source.target.minLength || @@ -36404,7 +36775,8 @@ var ts; } function typesDefinitelyUnrelated(source, target) { return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || - !!getUnmatchedProperty(source, target, false) && !!getUnmatchedProperty(target, source, false); + !!getUnmatchedProperty(source, target, false, true) && + !!getUnmatchedProperty(target, source, false, true); } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2) : @@ -36919,47 +37291,31 @@ var ts; return !!ts.findAncestor(node, function (n) { return n.kind === 167 ? true : n.kind === 72 || n.kind === 148 ? false : "quit"; }); } function getFlowCacheKey(node) { - if (node.kind === 72) { - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; - } - if (node.kind === 100) { - return "0"; - } - if (node.kind === 189) { - var key = getFlowCacheKey(node.expression); - return key && key + "." + ts.idText(node.name); - } - if (node.kind === 186) { - var container = node.parent.parent; - var key = container.kind === 186 ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); - var text = getBindingElementNameText(node); - var result = key && text && (key + "." + text); - return result; + switch (node.kind) { + case 72: + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + case 100: + return "0"; + case 213: + case 195: + return getFlowCacheKey(node.expression); + case 189: + case 190: + var propName = getAccessedPropertyName(node); + if (propName !== undefined) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + propName; + } } return undefined; } - function getBindingElementNameText(element) { - var parent = element.parent; - if (parent.kind === 184) { - var name = element.propertyName || element.name; - switch (name.kind) { - case 72: - return ts.idText(name); - case 149: - return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; - case 10: - case 8: - return name.text; - default: - ts.Debug.fail("Unexpected name kind for binding element name"); - } - } - else { - return "" + parent.elements.indexOf(element); - } - } function isMatchingReference(source, target) { + switch (target.kind) { + case 195: + case 213: + return isMatchingReference(source, target.expression); + } switch (source.kind) { case 72: return target.kind === 72 && getResolvedSymbol(source) === getResolvedSymbol(target) || @@ -36969,34 +37325,24 @@ var ts; return target.kind === 100; case 98: return target.kind === 98; + case 213: + case 195: + return isMatchingReference(source.expression, target); case 189: case 190: - return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 186: - if (target.kind !== 189) - return false; - var t = target; - if (t.name.escapedText !== getBindingElementNameText(source)) - return false; - if (source.parent.parent.kind === 186 && isMatchingReference(source.parent.parent, t.expression)) { - return true; - } - if (source.parent.parent.kind === 237) { - var maybeId = source.parent.parent.initializer; - return !!maybeId && isMatchingReference(maybeId, t.expression); - } } return false; } function getAccessedPropertyName(access) { - return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + return access.kind === 189 ? access.name.escapedText : ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : undefined; } function containsMatchingReference(source, target) { - while (source.kind === 189) { + while (ts.isAccessExpression(source)) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -37005,42 +37351,37 @@ var ts; return false; } function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 189 && + var name; + return ts.isAccessExpression(target) && containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + (name = getAccessedPropertyName(target)) !== undefined && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), name); } function getDeclaredTypeOfReference(expr) { if (expr.kind === 72) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 189) { + if (ts.isAccessExpression(expr)) { var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + if (type) { + var propName = getAccessedPropertyName(expr); + return propName !== undefined ? getTypeOfPropertyOfType(type, propName) : undefined; + } } return undefined; } function isDiscriminantType(type) { - if (type.flags & 1048576) { - if (type.flags & (16 | 1024)) { - return true; - } - var combined = 0; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - combined |= t.flags; - } - if (combined & 109440 && !(combined & 63176704)) { - return true; - } - } - return false; + return !!(type.flags & 1048576 && + (type.flags & (16 | 1024) || !isGenericIndexType(type))); } function isDiscriminantProperty(type, name) { if (type && type.flags & 1048576) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32) && isDiscriminantType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = + (prop.checkFlags & 96) === 96 && + isDiscriminantType(getTypeOfSymbol(prop)); } return !!prop.isDiscriminantProperty; } @@ -37800,25 +38141,23 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 1048576) || - expr.kind !== 189 && expr.kind !== 190) { + if (!(computedType.flags & 1048576) || !ts.isAccessExpression(expr)) { return false; } - var access = expr; - var name = getAccessedPropertyName(access); - if (!name) { + var name = getAccessedPropertyName(expr); + if (name === undefined) { return false; } - return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); - if (!propName) { + if (propName === undefined) { return type; } var propType = getTypeOfPropertyOfType(type, propName); var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOrIndexSignature(t, propName), narrowedPropType); }); } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { @@ -38108,9 +38447,8 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 190 || invokedExpression.kind === 189) { - var accessExpression = invokedExpression; - var possibleReference = ts.skipParentheses(accessExpression.expression); + if (ts.isAccessExpression(invokedExpression)) { + var possibleReference = ts.skipParentheses(invokedExpression.expression); if (isMatchingReference(reference, possibleReference)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } @@ -38457,7 +38795,7 @@ var ts; } function checkThisBeforeSuper(node, container, diagnosticMessage) { var containingClassDecl = container.parent; - var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); + var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl); if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { var superCall = getSuperCallInConstructor(container); if (!superCall || superCall.end > node.pos) { @@ -38673,7 +39011,7 @@ var ts; } } var classLikeDeclaration = container.parent; - if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { + if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); return errorType; } @@ -38812,35 +39150,39 @@ var ts; tryGetTypeAtPosition(contextualSignature, index); } } + function getContextualTypeForVariableLikeDeclaration(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + switch (declaration.kind) { + case 151: + return getContextuallyTypedParameterType(declaration); + case 186: + return getContextualTypeForBindingElement(declaration); + } + } + function getContextualTypeForBindingElement(declaration) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + var parentType = getContextualTypeForVariableLikeDeclaration(parentDeclaration); + if (parentType && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text !== undefined) { + return getTypeOfPropertyOfType(parentType, text); + } + } + } function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; if (ts.hasInitializer(declaration) && node === declaration.initializer) { - var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - return getTypeFromTypeNode(typeNode); - } - if (declaration.kind === 151) { - var type = getContextuallyTypedParameterType(declaration); - if (type) { - return type; - } + var result = getContextualTypeForVariableLikeDeclaration(declaration); + if (result) { + return result; } if (ts.isBindingPattern(declaration.name)) { return getTypeFromBindingPattern(declaration.name, true, false); } - if (ts.isBindingPattern(declaration.parent)) { - var parentDeclaration = declaration.parent.parent; - var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 186) { - var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); - if (parentTypeNode && !ts.isBindingPattern(name)) { - var text = ts.getTextOfPropertyName(name); - if (text) { - return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); - } - } - } - } } return undefined; } @@ -39067,17 +39409,29 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForChildJsxExpression(node) { + function getContextualTypeForChildJsxExpression(node, child) { var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); - return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { + return undefined; + } + var childIndex = node.children.indexOf(child); + var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName); + return childFieldType && mapType(childFieldType, function (t) { + if (isArrayLikeType(t)) { + return getIndexedAccessType(t, getLiteralType(childIndex)); + } + else { + return t; + } + }, true); } function getContextualTypeForJsxExpression(node) { var exprParent = node.parent; return ts.isJsxAttributeLike(exprParent) ? getContextualType(node) : ts.isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent, node) : undefined; } function getContextualTypeForJsxAttribute(attribute) { @@ -39214,6 +39568,22 @@ var ts; return propsType; } function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + if (sig.unionSignatures) { + var results = []; + for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + var instance = getReturnTypeOfSignature(signature); + if (isTypeAny(instance)) { + return instance; + } + var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation); + if (!propType) { + return; + } + results.push(propType); + } + return getIntersectionType(results); + } var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } @@ -39543,7 +39913,7 @@ var ts; var nameType = computedNameType && computedNameType.flags & 8576 ? computedNameType : undefined; var prop = nameType ? - createSymbol(4 | member.flags, getLateBoundNameFromType(nameType), 1024) : + createSymbol(4 | member.flags, getLateBoundNameFromType(nameType), 2048) : createSymbol(4 | member.flags, member.escapedName); if (nameType) { prop.nameType = nameType; @@ -40029,7 +40399,7 @@ var ts; return true; } } - else if (targetType.flags & 3145728) { + else if (targetType.flags & 3145728 && isExcessPropertyCheckTarget(targetType)) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -40037,12 +40407,14 @@ var ts; } } } - else if (targetType.flags & 16777216) { - return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || - isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); - } return false; } + function isExcessPropertyCheckTarget(type) { + return !!(type.flags & 524288 && !(ts.getObjectFlags(type) & 512) || + type.flags & 67108864 || + type.flags & 1048576 && ts.some(type.types, isExcessPropertyCheckTarget) || + type.flags & 2097152 && ts.every(type.types, isExcessPropertyCheckTarget)); + } function checkJsxExpression(node, checkMode) { if (node.expression) { var type = checkExpression(node.expression, checkMode); @@ -40071,7 +40443,7 @@ var ts; function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 148 ? node.right : node.kind === 183 ? node : node.name; - if (ts.getCheckFlags(prop) & 256) { + if (ts.getCheckFlags(prop) & 512) { error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; } @@ -40379,7 +40751,7 @@ var ts; } } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (nodeForCheckWriteOnly && isInTypeQuery(nodeForCheckWriteOnly) || !(prop.flags & 106500) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8)) { + if (!prop || !(prop.flags & 106500) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 && !(prop.flags & 32768))) { @@ -40404,7 +40776,7 @@ var ts; } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind !== 183 && node.expression.kind === 98, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind === 189 && node.expression.kind === 98, property.escapedName, type) && (!(property.flags & 8192) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -40977,15 +41349,30 @@ var ts; return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { - var min = Infinity; - var max = -Infinity; + var argCount = typeArguments.length; + if (signatures.length === 1) { + var sig = signatures[0]; + var min_1 = getMinTypeArgumentCount(sig.typeParameters); + var max = ts.length(sig.typeParameters); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, min_1 < max ? min_1 + "-" + max : min_1, argCount); + } + var belowArgCount = -Infinity; + var aboveArgCount = Infinity; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, ts.length(sig.typeParameters)); + var min_2 = getMinTypeArgumentCount(sig.typeParameters); + var max = ts.length(sig.typeParameters); + if (min_2 > argCount) { + aboveArgCount = Math.min(aboveArgCount, min_2); + } + else if (max < argCount) { + belowArgCount = Math.max(belowArgCount, max); + } } - var paramCount = min === max ? min : min + "-" + max; - return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) { + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { var isTaggedTemplate = node.kind === 193; @@ -41144,7 +41531,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_7 = function (i) { + var _loop_8 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -41155,7 +41542,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_7(i); + _loop_8(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -41278,7 +41665,7 @@ var ts; return resolveCall(node, callSignatures, candidatesOutArray, isForSignatureHelp); } function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 || + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144) || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 | 131072)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { @@ -41703,6 +42090,7 @@ var ts; if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152, "default"); + newSymbol.nameType = getLiteralType("default"); newSymbol.target = resolveSymbol(symbol); memberTable.set("default", newSymbol); var anonymousSymbol = createSymbol(2048, "__type"); @@ -42578,19 +42966,18 @@ var ts; if (rightIsThis === void 0) { rightIsThis = false; } if (property.kind === 275 || property.kind === 276) { var name = property.name; - if (name.kind === 149) { - checkComputedPropertyName(name); - } - if (isComputedNonLiteralName(name)) { - return undefined; - } - var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); - if (type) { - return checkDestructuringAssignment(property.kind === 276 ? property : property.initializer, type); - } - else { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + var text = ts.getTextOfPropertyName(name); + if (text) { + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, false, objectLiteralType, prop); + } } + var exprType = getLiteralTypeFromPropertyName(name); + var elementType = getIndexedAccessType(objectLiteralType, exprType, name); + var type = getFlowTypeOfDestructuring(property, elementType); + return checkDestructuringAssignment(property.kind === 276 ? property : property.initializer, type); } else if (property.kind === 277) { if (languageVersion < 6) { @@ -42610,23 +42997,6 @@ var ts; error(property, ts.Diagnostics.Property_assignment_expected); } } - function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { - if (isTypeAny(objectLiteralType)) { - return objectLiteralType; - } - var type; - var text = ts.getTextOfPropertyName(name); - if (text) { - var prop = getPropertyOfType(objectLiteralType, text); - if (prop) { - markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, false, objectLiteralType, prop); - type = getTypeOfSymbol(prop); - } - type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1) : undefined); - } - return type || getIndexTypeOfType(objectLiteralType, 0); - } function checkArrayLiteralAssignment(node, sourceType, checkMode) { var elements = node.elements; if (languageVersion < 2 && compilerOptions.downlevelIteration) { @@ -42643,37 +43013,28 @@ var ts; var element = elements[elementIndex]; if (element.kind !== 210) { if (element.kind !== 208) { - var propName = "" + elementIndex; - var type = isTypeAny(sourceType) ? sourceType : - everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : - elementType; - if (type) { + var indexType = getLiteralType(elementIndex); + if (isArrayLikeType(sourceType)) { + var elementType_2 = getIndexedAccessType(sourceType, indexType, createSyntheticExpression(element, indexType)); + var type = getFlowTypeOfDestructuring(element, elementType_2); return checkDestructuringAssignment(element, type, checkMode); } - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } + return checkDestructuringAssignment(element, elementType, checkMode); + } + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { - if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + var restExpression = element.expression; + if (restExpression.kind === 204 && restExpression.operatorToken.kind === 59) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { - var restExpression = element.expression; - if (restExpression.kind === 204 && restExpression.operatorToken.kind === 59) { - error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - else { - checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = everyType(sourceType, isTupleType) ? - mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : - createArrayType(elementType); - return checkDestructuringAssignment(restExpression, type, checkMode); - } + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); } } } @@ -43142,7 +43503,8 @@ var ts; var type = getTypeOfExpression(initializer, true); var widened = ts.getCombinedNodeFlags(declaration) & 2 || ts.isDeclarationReadonly(declaration) || - isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + isTypeAssertion(initializer) || + isLiteralOfContextualType(type, getContextualType(initializer)) ? type : getWidenedLiteralType(type); if (ts.isInJSFile(declaration)) { if (widened.flags & 98304) { reportImplicitAny(declaration, anyType); @@ -43725,7 +44087,7 @@ var ts; !!n.initializer; } var containingClassDecl = node.parent; - if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { + if (ts.getClassExtendsHeritageElement(containingClassDecl)) { captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); @@ -43903,7 +44265,6 @@ var ts; break; } } - checkGrammarForDisallowedTrailingComma(node.elementTypes); ts.forEach(node.elementTypes, checkSourceElement); } function checkUnionOrIntersectionType(node) { @@ -44223,10 +44584,10 @@ var ts; case 248: case 251: case 250: - var result_4 = 0; + var result_5 = 0; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); - return result_4; + ts.forEach(target.declarations, function (d) { result_5 |= getDeclarationSpaces(d); }); + return result_5; case 237: case 186: case 239: @@ -44573,7 +44934,12 @@ var ts; return; } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 ? node.name.right : node.name)); + if (ts.isQualifiedName(node.name)) { + error(node.name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(node.name), ts.entityNameToString(node.name.left)); + } + else { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name)); + } } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && @@ -45821,6 +46187,7 @@ var ts; if (produceDiagnostics) { if (node.default) { seenDefault = true; + checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i); } else if (seenDefault) { error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); @@ -45834,6 +46201,22 @@ var ts; } } } + function checkTypeParametersNotReferenced(root, typeParameters, index) { + visit(root); + function visit(node) { + if (node.kind === 164) { + var type = getTypeFromTypeReference(node); + if (type.flags & 262144) { + for (var i = index; i < typeParameters.length; i++) { + if (type.symbol === getSymbolOfNode(typeParameters[i])) { + error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters); + } + } + } + } + ts.forEachChild(node, visit); + } + } function checkTypeParameterListsIdentical(symbol) { if (symbol.declarations.length === 1) { return; @@ -46006,7 +46389,7 @@ var ts; } function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { var issuedMemberError = false; - var _loop_8 = function (member) { + var _loop_9 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -46024,7 +46407,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_8(member); + _loop_9(member); } if (!issuedMemberError) { checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); @@ -46261,7 +46644,7 @@ var ts; return 0; } else if (isConstEnum) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values); } else if (member.parent.flags & 4194304) { error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); @@ -48101,7 +48484,7 @@ var ts; isLateBound: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); var symbol = node && getSymbolOfNode(node); - return !!(symbol && ts.getCheckFlags(symbol) & 1024); + return !!(symbol && ts.getCheckFlags(symbol) & 2048); }, getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { @@ -48655,9 +49038,6 @@ var ts; if (!(parameter.flags & 4194304)) { checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); } - if (ts.isBindingPattern(parameter.name)) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } if (parameter.questionToken) { return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); } @@ -49557,9 +49937,6 @@ var ts; JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes"; JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; })(JsxNames || (JsxNames = {})); - function typeIsLiteralType(type) { - return !!(type.flags & 2944); - } })(ts || (ts = {})); var ts; (function (ts) { @@ -54453,10 +54830,16 @@ var ts; ts.createSourceMapGenerator = createSourceMapGenerator; var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; - function tryGetSourceMappingURL(text, lineStarts) { - if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } - for (var index = lineStarts.length - 1; index >= 0; index--) { - var line = text.substring(lineStarts[index], lineStarts[index + 1]); + function getLineInfo(text, lineStarts) { + return { + getLineCount: function () { return lineStarts.length; }, + getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); } + }; + } + ts.getLineInfo = getLineInfo; + function tryGetSourceMappingURL(lineInfo) { + for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) { + var line = lineInfo.getLineText(index); var comment = sourceMapCommentRegExp.exec(line); if (comment) { return comment[1]; @@ -54681,7 +55064,8 @@ var ts; && left.sourcePosition === right.sourcePosition; } function compareSourcePositions(left, right) { - return ts.compareValues(left.sourceIndex, right.sourceIndex); + ts.Debug.assert(left.sourceIndex === right.sourceIndex); + return ts.compareValues(left.sourcePosition, right.sourcePosition); } function compareGeneratedPositions(left, right) { return ts.compareValues(left.generatedPosition, right.generatedPosition); @@ -54696,11 +55080,9 @@ var ts; var mapDirectory = ts.getDirectoryPath(mapPath); var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); - var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); - var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath); var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); - var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); - var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; })); var decodedMappings; var generatedMappings; var sourceMappings; @@ -54710,16 +55092,15 @@ var ts; }; function processMapping(mapping) { var generatedPosition = generatedFile !== undefined - ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, true) : -1; var source; var sourcePosition; if (isSourceMapping(mapping)) { - var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; - var sourceFile = host.getSourceFileLike(sourceFilePath); + var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]); source = map.sources[mapping.sourceIndex]; sourcePosition = sourceFile !== undefined - ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, true) : -1; } return { @@ -56271,6 +56652,7 @@ var ts; switch (node.literal.kind) { case 10: return ts.createIdentifier("String"); + case 202: case 8: return ts.createIdentifier("Number"); case 9: @@ -59006,7 +59388,7 @@ var ts; if (node.name) { enableSubstitutionsForBlockScopedBindings(); } - var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + var extendsClauseElement = ts.getClassExtendsHeritageElement(node); var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter(undefined, undefined, undefined, ts.createFileLevelUniqueName("_super"))] : [], undefined, transformClassBody(node, extendsClauseElement)); ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536) | 524288); var inner = ts.createPartiallyEmittedExpression(classFunction); @@ -59233,16 +59615,16 @@ var ts; statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 72 && !inConstructorWithSynthesizedSuper; + return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper); } function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) { var parameter = ts.lastOrUndefined(node.parameters); if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) { return; } - var declarationName = ts.getMutableClone(parameter.name); + var declarationName = parameter.name.kind === 72 ? ts.getMutableClone(parameter.name) : ts.createTempVariable(undefined); ts.setEmitFlags(declarationName, 48); - var expressionName = ts.getSynthesizedClone(parameter.name); + var expressionName = parameter.name.kind === 72 ? ts.getSynthesizedClone(parameter.name) : declarationName; var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ @@ -59258,6 +59640,9 @@ var ts; ts.setEmitFlags(forStatement, 1048576); ts.startOnNewLine(forStatement); statements.push(forStatement); + if (parameter.name.kind !== 72) { + statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0, expressionName))), parameter), 1048576)); + } } function addCaptureThisForNodeIfNeeded(statements, node) { if (node.transformFlags & 16384 && node.kind !== 197) { @@ -64560,6 +64945,7 @@ var ts; case 241: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; + case 166: case 161: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; @@ -64578,6 +64964,7 @@ var ts; diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; + case 165: case 239: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; @@ -65102,7 +65489,10 @@ var ts; if (!ts.isLateVisibilityPaintedStatement(i)) { return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); } + var priorNeedsDeclare = needsDeclare; + needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); var result = transformTopLevelDeclaration(i, true); + needsDeclare = priorNeedsDeclare; lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); } return ts.visitNodes(statements, visitLateVisibilityMarkedStatements); @@ -65428,7 +65818,8 @@ var ts; var members = ts.createNodeArray(ts.concatenate(parameterProperties, ts.visitNodes(input.members, visitDeclarationSubtree))); var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96) { - var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); + var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default"; + var newId_1 = ts.createOptimisticUniqueName(oldId + "_base"); getSymbolAccessibilityDiagnostic = function () { return ({ diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: extendsClause_1, @@ -65577,7 +65968,7 @@ var ts; var prop = ts.createProperty(undefined, maskModifiers(node, undefined, (!accessors.setAccessor) ? 64 : 0), node.name, node.questionToken, ensureType(node, accessorType), undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_9 = function (range) { + var _loop_10 = function (range) { if (range.kind === 3) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -65591,7 +65982,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_9(range); + _loop_10(range); } } return prop; @@ -67265,18 +67656,20 @@ var ts; function emitPropertyAccessExpression(node) { var indentBeforeDot = false; var indentAfterDot = false; + var dotRangeFirstCommentStart = ts.skipTrivia(currentSourceFile.text, node.expression.end, false, true); + var dotRangeStart = ts.skipTrivia(currentSourceFile.text, dotRangeFirstCommentStart); + var dotRangeEnd = dotRangeStart + 1; if (!(ts.getEmitFlags(node) & 131072)) { - var dotRangeStart = node.expression.end; - var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; var dotToken = ts.createToken(24); - dotToken.pos = dotRangeStart; + dotToken.pos = node.expression.end; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } emitExpression(node.expression); increaseIndentIf(indentBeforeDot, false); - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + var dotHasCommentTrivia = dotRangeFirstCommentStart !== dotRangeStart; + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression, dotHasCommentTrivia); if (shouldEmitDotDot) { writePunctuation("."); } @@ -67285,12 +67678,12 @@ var ts; emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); } - function needsDotDotForPropertyAccess(expression) { + function needsDotDotForPropertyAccess(expression, dotHasTrivia) { expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { var text = getLiteralTextOfNode(expression, true); - return !expression.numericLiteralFlags - && !ts.stringContains(text, ts.tokenToString(24)); + return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24)) && + (!dotHasTrivia || printerOptions.removeComments); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { var constantValue = ts.getConstantValue(expression); @@ -68001,6 +68394,7 @@ var ts; function emitJsxSelfClosingElement(node) { writePunctuation("<"); emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); writeSpace(); emit(node.attributes); writePunctuation("/>"); @@ -68014,6 +68408,7 @@ var ts; writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } @@ -69443,7 +69838,7 @@ var ts; if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { return; } - var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character; sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, undefined); } function emitSourcePos(source, pos) { @@ -69802,7 +70197,7 @@ var ts; }, flags); } function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { - return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2); } function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); @@ -69872,7 +70267,7 @@ var ts; var text; try { ts.performance.mark("beforeIORead"); - text = system.readFile(fileName, options.charset); + text = compilerHost.readFile(fileName); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -69898,7 +70293,12 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - system.createDirectory(directoryPath); + if (compilerHost.createDirectory) { + compilerHost.createDirectory(directoryPath); + } + else { + system.createDirectory(directoryPath); + } } } var outputFingerprints; @@ -69949,7 +70349,7 @@ var ts; } var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); var realpath = system.realpath && (function (path) { return system.realpath(path); }); - return { + var compilerHost = { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -69965,10 +70365,109 @@ var ts; getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }, + createDirectory: function (d) { return system.createDirectory(d); } }; + return compilerHost; } ts.createCompilerHostWorker = createCompilerHostWorker; + function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) { + var originalReadFile = host.readFile; + var originalFileExists = host.fileExists; + var originalDirectoryExists = host.directoryExists; + var originalCreateDirectory = host.createDirectory; + var originalWriteFile = host.writeFile; + var readFileCache = ts.createMap(); + var fileExistsCache = ts.createMap(); + var directoryExistsCache = ts.createMap(); + var sourceFileCache = ts.createMap(); + var readFileWithCache = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value || undefined; + return setReadFileCache(key, fileName); + }; + var setReadFileCache = function (key, fileName) { + var newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue || false); + return newValue; + }; + host.readFile = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value; + if (!ts.fileExtensionIs(fileName, ".json")) { + return originalReadFile.call(host, fileName); + } + return setReadFileCache(key, fileName); + }; + var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { + var key = toPath(fileName); + var value = sourceFileCache.get(key); + if (value) + return value; + var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile); + if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json"))) { + sourceFileCache.set(key, sourceFile); + } + return sourceFile; + } : undefined; + host.fileExists = function (fileName) { + var key = toPath(fileName); + var value = fileExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + if (originalWriteFile) { + host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) { + var key = toPath(fileName); + fileExistsCache.delete(key); + var value = readFileCache.get(key); + if (value && value !== data) { + readFileCache.delete(key); + sourceFileCache.delete(key); + } + else if (getSourceFileWithCache) { + var sourceFile = sourceFileCache.get(key); + if (sourceFile && sourceFile.text !== data) { + sourceFileCache.delete(key); + } + } + originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles); + }; + } + if (originalDirectoryExists && originalCreateDirectory) { + host.directoryExists = function (directory) { + var key = toPath(directory); + var value = directoryExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + return { + originalReadFile: originalReadFile, + originalFileExists: originalFileExists, + originalDirectoryExists: originalDirectoryExists, + originalCreateDirectory: originalCreateDirectory, + originalWriteFile: originalWriteFile, + getSourceFileWithCache: getSourceFileWithCache, + readFileWithCache: readFileWithCache + }; + } + ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (ts.getEmitDeclarations(program.getCompilerOptions())) { @@ -70258,7 +70757,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); - var configParsingHost = parseConfigHostFromCompilerHost(host); + var configParsingHost = parseConfigHostFromCompilerHostLike(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); @@ -70346,7 +70845,10 @@ var ts; }); } } - missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) { + var path = _a[0], file = _a[1]; + return file === undefined ? path : undefined; + })); files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); processingDefaultLibFiles = undefined; processingOtherFiles = undefined; @@ -70472,13 +70974,13 @@ var ts; } var oldSourceFile = oldProgram && oldProgram.getSourceFile(containingFile); if (oldSourceFile !== file && file.resolvedModules) { - var result_5 = []; + var result_6 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_5.push(resolvedModule); + result_6.push(resolvedModule); } - return result_5; + return result_6; } var unknownModuleNames; var result; @@ -70841,7 +71343,7 @@ var ts; return getSourceFileByPath(toPath(fileName)); } function getSourceFileByPath(path) { - return filesByName.get(path); + return filesByName.get(path) || undefined; } function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { if (sourceFile) { @@ -71264,7 +71766,7 @@ var ts; } } function getSourceFileFromReference(referencingFile, ref) { - return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; }); } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { @@ -71363,7 +71865,9 @@ var ts; processReferencedFiles(file_1, isDefaultLib); processTypeReferenceDirectives(file_1); } - processLibReferenceDirectives(file_1); + if (!options.noLib) { + processLibReferenceDirectives(file_1); + } modulesWithElidedImports.set(file_1.path, false); processImportedModules(file_1); } @@ -71373,7 +71877,7 @@ var ts; processImportedModules(file_1); } } - return file_1; + return file_1 || undefined; } var redirectedPath; if (refFile) { @@ -71429,7 +71933,9 @@ var ts; processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } - processLibReferenceDirectives(file); + if (!options.noLib) { + processLibReferenceDirectives(file); + } processImportedModules(file); if (isDefaultLib) { processingDefaultLibFiles.push(file); @@ -71441,9 +71947,12 @@ var ts; return file; } function addFileToFilesByName(file, path, redirectedPath) { - filesByName.set(path, file); if (redirectedPath) { filesByName.set(redirectedPath, file); + filesByName.set(path, file || false); + } + else { + filesByName.set(path, file); } } function getProjectReferenceRedirect(fileName) { @@ -72053,21 +72562,22 @@ var ts; } } ts.createProgram = createProgram; - function parseConfigHostFromCompilerHost(host) { + function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) { + if (directoryStructureHost === void 0) { directoryStructureHost = host; } return { - fileExists: function (f) { return host.fileExists(f); }, + fileExists: function (f) { return directoryStructureHost.fileExists(f); }, readDirectory: function (root, extensions, excludes, includes, depth) { - ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(root, extensions, excludes, includes, depth); + ts.Debug.assertDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); }, - readFile: function (f) { return host.readFile(f); }, + readFile: function (f) { return directoryStructureHost.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, - onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }), trace: host.trace ? function (s) { return host.trace(s); } : undefined }; } - ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike; function resolveProjectReferencePath(hostOrRef, ref) { var passedInRef = ref ? ref : hostOrRef; return ts.resolveConfigFileProjectName(passedInRef.path); @@ -72125,6 +72635,10 @@ var ts; } } ts.getFileEmitOutput = getFileEmitOutput; + function cloneMapOrUndefined(map) { + return map ? ts.cloneMap(map) : undefined; + } + ts.cloneMapOrUndefined = cloneMapOrUndefined; })(ts || (ts = {})); (function (ts) { var BuilderState; @@ -72242,12 +72756,28 @@ var ts; fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, - allFilesExcludingDefaultLibraryFile: undefined, - allFileNames: undefined + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature }; } BuilderState.create = create; + function releaseCache(state) { + state.allFilesExcludingDefaultLibraryFile = undefined; + state.allFileNames = undefined; + } + BuilderState.releaseCache = releaseCache; + function clone(state) { + var fileInfos = ts.createMap(); + state.fileInfos.forEach(function (value, key) { + fileInfos.set(key, __assign({}, value)); + }); + return { + fileInfos: fileInfos, + referencedMap: ts.cloneMapOrUndefined(state.referencedMap), + exportedModulesMap: ts.cloneMapOrUndefined(state.exportedModulesMap), + hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature), + }; + } + BuilderState.clone = clone; function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) { var signatureCache = cacheToUpdateSignature || ts.createMap(); var sourceFile = programOfThisState.getSourceFileByPath(path); @@ -72431,14 +72961,14 @@ var ts; } var seenFileNamesMap = ts.createMap(); seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); - var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath); while (queue.length > 0) { var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); seenFileNamesMap.set(currentPath, currentSourceFile); if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { - queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + queue.push.apply(queue, getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } } @@ -72455,22 +72985,28 @@ var ts; var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); - if (!compilerOptions.outFile && !compilerOptions.out) { + state.compilerOptions = compilerOptions; + if (!compilerOptions.outFile && !compilerOptions.out && !compilerOptions.isolatedModules) { state.semanticDiagnosticsPerFile = ts.createMap(); } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; + var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); if (useOldState) { if (!oldState.currentChangedFilePath) { - ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + var affectedSignatures = oldState.currentAffectedFilesSignatures; + ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); } if (canCopySemanticDiagnostics) { ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); } ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit; + state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; + } } var referencedMap = state.referencedMap; var oldReferencedMap = useOldState ? oldState.referencedMap : undefined; @@ -72487,7 +73023,7 @@ var ts; state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { - var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + var sourceFile = newProgram.getSourceFileByPath(sourceFilePath); if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { return; } @@ -72506,6 +73042,30 @@ var ts; }); return state; } + function releaseCache(state) { + ts.BuilderState.releaseCache(state); + state.program = undefined; + } + function cloneBuilderProgramState(state) { + var newState = ts.BuilderState.clone(state); + newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile); + newState.changedFilesSet = ts.cloneMap(state.changedFilesSet); + newState.affectedFiles = state.affectedFiles; + newState.affectedFilesIndex = state.affectedFilesIndex; + newState.currentChangedFilePath = state.currentChangedFilePath; + newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures); + newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap); + newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles); + newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; + newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState); + newState.program = state.program; + newState.compilerOptions = state.compilerOptions; + newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit; + newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; + newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles); + newState.programEmitComplete = state.programEmitComplete; + return newState; + } function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); } @@ -72536,30 +73096,48 @@ var ts; if (nextKey.done) { return undefined; } - var compilerOptions = state.program.getCompilerOptions(); + var program = ts.Debug.assertDefined(state.program); + var compilerOptions = program.getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); - return state.program; + return program; } state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); if (state.exportedModulesMap) { state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); } - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); } } + function getNextAffectedFilePendingEmit(state) { + var affectedFilesPendingEmit = state.affectedFilesPendingEmit; + if (affectedFilesPendingEmit) { + var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap()); + for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) { + var affectedFile = ts.Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]); + if (affectedFile && !seenEmittedFiles.has(affectedFile.path)) { + state.affectedFilesPendingEmitIndex = i; + return affectedFile; + } + } + state.affectedFilesPendingEmit = undefined; + state.affectedFilesPendingEmitIndex = undefined; + } + return undefined; + } function cleanSemanticDiagnosticsOfAffectedFile(state, affectedFile) { if (removeSemanticDiagnosticsOf(state, affectedFile.path)) { return; } if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { state.cleanedDiagnosticsOfLibFiles = true; - var options_2 = state.program.getCompilerOptions(); - if (ts.forEach(state.program.getSourceFiles(), function (f) { - return state.program.isSourceFileDefaultLibrary(f) && + var program_1 = ts.Debug.assertDefined(state.program); + var options_2 = program_1.getCompilerOptions(); + if (ts.forEach(program_1.getSourceFiles(), function (f) { + return program_1.isSourceFileDefaultLibrary(f) && !ts.skipTypeChecking(f, options_2) && removeSemanticDiagnosticsOf(state, f.path); })) { @@ -72604,10 +73182,17 @@ var ts; })) { return true; } - return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && exportedModules.has(filePath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); + })) { + return true; + } + return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) { + return referencesInFile.has(filePath) && + !seenFileAndExportsOfFile.has(referencingFilePath) && + removeSemanticDiagnosticsOf(state, referencingFilePath); }); } function removeSemanticDiagnosticsOf(state, path) { @@ -72618,27 +73203,37 @@ var ts; state.semanticDiagnosticsPerFile.delete(path); return !state.semanticDiagnosticsFromOldState.size; } - function doneWithAffectedFile(state, affected) { + function doneWithAffectedFile(state, affected, isPendingEmit) { if (affected === state.program) { state.changedFilesSet.clear(); + state.programEmitComplete = true; } else { state.seenAffectedFiles.set(affected.path, true); - state.affectedFilesIndex++; + if (isPendingEmit) { + state.affectedFilesPendingEmitIndex++; + } + else { + state.affectedFilesIndex++; + } } } - function toAffectedFileResult(state, result, affected) { - doneWithAffectedFile(state, affected); + function toAffectedFileResult(state, result, affected, isPendingEmit) { + doneWithAffectedFile(state, affected, isPendingEmit); return { result: result, affected: affected }; } function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { var path = sourceFile.path; - var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); - if (cachedDiagnostics) { - return cachedDiagnostics; + if (state.semanticDiagnosticsPerFile) { + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + if (cachedDiagnostics) { + return cachedDiagnostics; + } + } + var diagnostics = ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); + if (state.semanticDiagnosticsPerFile) { + state.semanticDiagnosticsPerFile.set(path, diagnostics); } - var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); - state.semanticDiagnosticsPerFile.set(path, diagnostics); return diagnostics; } var BuilderProgramKind; @@ -72663,7 +73258,7 @@ var ts; rootNames: newProgramOrRootNames, options: hostOrOptions, host: oldProgramOrHost, - oldProgram: oldProgram && oldProgram.getProgram(), + oldProgram: oldProgram && oldProgram.getProgramOrUndefined(), configFileParsingDiagnostics: configFileParsingDiagnostics, projectReferences: projectReferences }); @@ -72687,25 +73282,28 @@ var ts; return oldProgram; } var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var computeHash = host.createHash || ts.identity; + var computeHash = host.createHash || ts.generateDjb2Hash; var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + var backupState; newProgram = undefined; oldProgram = undefined; oldState = undefined; - var result = { - getState: function () { return state; }, - getProgram: function () { return state.program; }, - getCompilerOptions: function () { return state.program.getCompilerOptions(); }, - getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, - getSourceFiles: function () { return state.program.getSourceFiles(); }, - getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, - getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, - getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, - getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, - getSemanticDiagnostics: getSemanticDiagnostics, - emit: emit, - getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, - getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + var result = createRedirectedBuilderProgram(state, configFileParsingDiagnostics); + result.getState = function () { return state; }; + result.backupState = function () { + ts.Debug.assert(backupState === undefined); + backupState = cloneBuilderProgramState(state); + }; + result.restoreState = function () { + state = ts.Debug.assertDefined(backupState); + backupState = undefined; + }; + result.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.assertDefined(state.program), sourceFile); }; + result.getSemanticDiagnostics = getSemanticDiagnostics; + result.emit = emit; + result.releaseProgram = function () { + releaseCache(state); + backupState = undefined; }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; @@ -72719,10 +73317,28 @@ var ts; return result; function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { var affected = getNextAffectedFile(state, cancellationToken, computeHash); + var isPendingEmitFile = false; if (!affected) { - return undefined; + if (!state.compilerOptions.out && !state.compilerOptions.outFile) { + affected = getNextAffectedFilePendingEmit(state); + if (!affected) { + return undefined; + } + isPendingEmitFile = true; + } + else { + var program = ts.Debug.assertDefined(state.program); + if (state.programEmitComplete || !ts.some(program.getProjectReferences(), function (ref) { return !!ref.prepend; })) { + state.programEmitComplete = true; + return undefined; + } + affected = program; + } } - return toAffectedFileResult(state, state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + if (state.affectedFilesPendingEmit && state.program !== affected) { + (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.path, true); + } + return toAffectedFileResult(state, ts.Debug.assertDefined(state.program).emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected, isPendingEmitFile); } function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { @@ -72747,7 +73363,7 @@ var ts; }; } } - return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return ts.Debug.assertDefined(state.program).emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); } function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { while (true) { @@ -72767,22 +73383,30 @@ var ts; } function getSemanticDiagnostics(sourceFile, cancellationToken) { assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); - var compilerOptions = state.program.getCompilerOptions(); + var compilerOptions = ts.Debug.assertDefined(state.program).getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); - return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + return ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); } if (sourceFile) { return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); } - if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { - var affected = void 0; - while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { - doneWithAffectedFile(state, affected); + var affected; + var affectedFilesPendingEmit; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + if (affected !== state.program && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push(affected.path); + } + doneWithAffectedFile(state, affected); + } + if (affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, affectedFilesPendingEmit); + if (state.affectedFilesPendingEmitIndex === undefined) { + state.affectedFilesPendingEmitIndex = 0; } } var diagnostics; - for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { var sourceFile_2 = _a[_i]; diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); } @@ -72790,6 +73414,32 @@ var ts; } } ts.createBuilderProgram = createBuilderProgram; + function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { + return { + getState: ts.notImplemented, + backupState: ts.noop, + restoreState: ts.noop, + getProgram: getProgram, + getProgramOrUndefined: function () { return state.program; }, + releaseProgram: function () { return state.program = undefined; }, + getCompilerOptions: function () { return state.compilerOptions; }, + getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); }, + getSourceFiles: function () { return getProgram().getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); }, + emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); }, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); } + }; + function getProgram() { + return ts.Debug.assertDefined(state.program); + } + } + ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram; })(ts || (ts = {})); (function (ts) { function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { @@ -72801,22 +73451,8 @@ var ts; } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; - return { - getProgram: function () { return program; }, - getState: ts.notImplemented, - getCompilerOptions: ts.notImplemented, - getSourceFile: ts.notImplemented, - getSourceFiles: ts.notImplemented, - getOptionsDiagnostics: ts.notImplemented, - getGlobalDiagnostics: ts.notImplemented, - getConfigFileParsingDiagnostics: ts.notImplemented, - getSyntacticDiagnostics: ts.notImplemented, - getSemanticDiagnostics: ts.notImplemented, - emit: ts.notImplemented, - getAllDependencies: ts.notImplemented, - getCurrentDirectory: ts.notImplemented - }; + var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics; + return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics); } ts.createAbstractBuilder = createAbstractBuilder; })(ts || (ts = {})); @@ -73505,7 +74141,7 @@ var ts; if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { return; } - var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0; }); + var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0; }); if (target === undefined) return; var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); @@ -73838,34 +74474,91 @@ var ts; var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); return { onWatchStatusChange: onWatchStatusChange, - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + watchFile: ts.maybeBind(system, system.watchFile) || (function () { return noopFileWatcher; }), + watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return noopFileWatcher; }), + setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop, + clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop }; } ts.createWatchHost = createWatchHost; - function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { - if (system === void 0) { system = ts.sys; } - if (!createProgram) { - createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; + function createWatchFactory(host, options) { + var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop; + var result = ts.getWatchFactory(watchLogLevel, writeLog); + result.writeLog = writeLog; + return result; + } + ts.createWatchFactory = createWatchFactory; + function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) { + if (directoryStructureHost === void 0) { directoryStructureHost = host; } + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); }); + return { + getSourceFile: function (fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, getCompilerOptions().charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + }, + getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); }, + fileExists: function (f) { return host.fileExists(f); }, + readFile: function (f) { return host.readFile(f); }, + trace: ts.maybeBind(host, host.trace), + directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: ts.maybeBind(host, host.realpath), + getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }), + createHash: ts.maybeBind(host, host.createHash), + readDirectory: ts.maybeBind(host, host.readDirectory), + }; + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + if (host.createDirectory) + host.createDirectory(directoryPath); + } } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost; + function createProgramHost(system, createProgram) { + var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); }); var host = system; host; - var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; - var writeFileName = function (s) { return system.write(s + system.newLine); }; - var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getNewLine: function () { return system.newLine; }, - getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, fileExists: function (path) { return system.fileExists(path); }, @@ -73873,29 +74566,28 @@ var ts; directoryExists: function (path) { return system.directoryExists(path); }, getDirectories: function (path) { return system.getDirectories(path); }, readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, - realpath: system.realpath && (function (path) { return system.realpath(path); }), - getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: watchFile, - watchDirectory: watchDirectory, - setTimeout: setTimeout, - clearTimeout: clearTimeout, - trace: function (s) { return system.write(s); }, - onWatchStatusChange: onWatchStatusChange, + realpath: ts.maybeBind(system, system.realpath), + getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable), + trace: function (s) { return system.write(s + system.newLine); }, createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, - createHash: system.createHash && (function (s) { return system.createHash(s); }), - createProgram: createProgram, - afterProgramCreate: emitFilesAndReportErrorUsingBuilder + createHash: ts.maybeBind(system, system.createHash), + createProgram: createProgram }; - function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); - } - function emitFilesAndReportErrorUsingBuilder(builderProgram) { + } + ts.createProgramHost = createProgramHost; + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var writeFileName = function (s) { return system.write(s + system.newLine); }; + var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram); + ts.copyProperties(result, createWatchHost(system, reportWatchStatus)); + result.afterProgramCreate = function (builderProgram) { var compilerOptions = builderProgram.getCompilerOptions(); var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); - } + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); + }; + return result; } function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { reportDiagnostic(diagnostic); @@ -73942,8 +74634,6 @@ var ts; var hasChangedAutomaticTypeDirectiveNames = false; var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); var currentDirectory = host.getCurrentDirectory(); - var getCurrentDirectory = function () { return currentDirectory; }; - var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; @@ -73955,15 +74645,7 @@ var ts; host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } var directoryStructureHost = cachedDirectoryStructureHost || host; - var parseConfigFileHost = { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, - fileExists: function (path) { return host.fileExists(path); }, - readFile: readFile, - getCurrentDirectory: getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, - trace: host.trace ? function (s) { return host.trace(s); } : undefined - }; + var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost); var newLine = updateNewLine(); if (configFileName && host.configFileParsingResult) { setConfigFileParsingResult(host.configFileParsingResult); @@ -73976,50 +74658,38 @@ var ts; parseConfigFile(); newLine = updateNewLine(); } - var trace = host.trace && (function (s) { host.trace(s + newLine); }); - var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : - compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; - var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; - var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; + var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); if (configFileName) { watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); } - var compilerHost = { - getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, - getSourceFileByPath: getVersionedSourceFileByPath, - getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), - getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, - writeFile: writeFile, - getCurrentDirectory: getCurrentDirectory, - useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, - getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return newLine; }, - fileExists: fileExists, - readFile: readFile, - trace: trace, - directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), - getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), - realpath: host.realpath && (function (s) { return host.realpath(s); }), - getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), - onReleaseOldSourceFile: onReleaseOldSourceFile, - createHash: host.createHash && (function (data) { return host.createHash(data); }), - toPath: toPath, - getCompilationSettings: function () { return compilerOptions; }, - watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, - watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, - getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, - onInvalidatedResolution: scheduleProgramUpdate, - onChangedAutomaticTypeDirectiveNames: function () { - hasChangedAutomaticTypeDirectiveNames = true; - scheduleProgramUpdate(); - }, - maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, - getCurrentProgram: getCurrentProgram, - writeLog: writeLog, - readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost); + var getNewSourceFile = compilerHost.getSourceFile; + compilerHost.getSourceFile = function (fileName) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return getVersionedSourceFileByPath.apply(void 0, [fileName, toPath(fileName)].concat(args)); }; + compilerHost.getSourceFileByPath = getVersionedSourceFileByPath; + compilerHost.getNewLine = function () { return newLine; }; + compilerHost.fileExists = fileExists; + compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + compilerHost.toPath = toPath; + compilerHost.getCompilationSettings = function () { return compilerOptions; }; + compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }; + compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }; + compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; + compilerHost.onInvalidatedResolution = scheduleProgramUpdate; + compilerHost.onChangedAutomaticTypeDirectiveNames = function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }; + compilerHost.maxNumberOfFilesToIterateForInvalidation = host.maxNumberOfFilesToIterateForInvalidation; + compilerHost.getCurrentProgram = getCurrentProgram; + compilerHost.writeLog = writeLog; var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : currentDirectory, false); @@ -74066,11 +74736,9 @@ var ts; return builderProgram; } function createNewProgram(program, hasInvalidatedResolution) { - if (watchLogLevel !== ts.WatchLogLevel.None) { - writeLog("CreatingProgramWith::"); - writeLog(" roots: " + JSON.stringify(rootFileNames)); - writeLog(" options: " + JSON.stringify(compilerOptions)); - } + writeLog("CreatingProgramWith::"); + writeLog(" roots: " + JSON.stringify(rootFileNames)); + writeLog(" options: " + JSON.stringify(compilerOptions)); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -74123,7 +74791,7 @@ var ts; return undefined; } if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { - var sourceFile = getNewSourceFile(); + var sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { if (shouldCreateNewSourceFile) { hostSourceFile.version++; @@ -74155,21 +74823,6 @@ var ts; return sourceFile; } return hostSourceFile.sourceFile; - function getNewSourceFile() { - var text; - try { - ts.performance.mark("beforeIORead"); - text = host.readFile(fileName, compilerOptions.charset); - ts.performance.mark("afterIORead"); - ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; - } } function nextSourceFileVersion(path) { var hostSourceFile = sourceFilesCache.get(path); @@ -74320,28 +74973,7 @@ var ts; reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; scheduleProgramUpdate(); } - }, flags, "Wild card directories"); - } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - host.createDirectory(directoryPath); - } - } - function writeFile(fileName, text, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } + }, flags, "Wild card directory"); } } ts.createWatchProgram = createWatchProgram; @@ -74488,9 +75120,8 @@ var ts; }; } ts.createBuilderStatusReporter = createBuilderStatusReporter; - function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { - if (system === void 0) { system = ts.sys; } - var host = ts.createCompilerHostWorker({}, undefined, system); + function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) { + var host = ts.createProgramHost(system, createProgram); host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; @@ -74498,21 +75129,18 @@ var ts; host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); return host; } - function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { if (system === void 0) { system = ts.sys; } - var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus); host.reportErrorSummary = reportErrorSummary; return host; } ts.createSolutionBuilderHost = createSolutionBuilderHost; - function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { - var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus); var watchHost = ts.createWatchHost(system, reportWatchStatus); - host.onWatchStatusChange = watchHost.onWatchStatusChange; - host.watchFile = watchHost.watchFile; - host.watchDirectory = watchHost.watchDirectory; - host.setTimeout = watchHost.setTimeout; - host.clearTimeout = watchHost.clearTimeout; + ts.copyProperties(host, watchHost); return host; } ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; @@ -74527,7 +75155,7 @@ var ts; var hostWithWatch = host; var currentDirectory = host.getCurrentDirectory(); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host); var options = defaultOptions; var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); var configFileCache = createFileMap(toPath); @@ -74536,6 +75164,13 @@ var ts; var missingRoots = ts.createMap(); var globalDependencyGraph; var writeFileName = function (s) { return host.trace && host.trace(s); }; + var readFileWithCache = function (f) { return host.readFile(f); }; + var projectCompilerOptions = baseCompilerOptions; + var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; }); + var originalGetSourceFile = compilerHost.getSourceFile; + var computeHash = host.createHash || ts.generateDjb2Hash; + updateGetSourceFile(); + var builderPrograms = createFileMap(toPath); var diagnostics = createFileMap(toPath); var projectPendingBuild = createFileMap(toPath); var projectErrorsReported = createFileMap(toPath); @@ -74543,6 +75178,7 @@ var ts; var nextProjectToBuild = 0; var timerToBuildInvalidatedProject; var reportFileChangeDetected = false; + var _a = ts.createWatchFactory(host, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; var allWatchedWildcardDirectories = createFileMap(toPath); var allWatchedInputFiles = createFileMap(toPath); var allWatchedConfigFiles = createFileMap(toPath); @@ -74582,6 +75218,30 @@ var ts; ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + builderPrograms.clear(); + updateGetSourceFile(); + } + function updateGetSourceFile() { + if (options.watch) { + if (compilerHost.getSourceFile === originalGetSourceFile) { + compilerHost.getSourceFile = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); + if (result && options.watch) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + } + else { + if (compilerHost.getSourceFile !== originalGetSourceFile) { + compilerHost.getSourceFile = originalGetSourceFile; + } + } } function isParsedCommandLine(entry) { return !!entry.options; @@ -74628,34 +75288,34 @@ var ts; } function watchConfigFile(resolved) { if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { - allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + allWatchedConfigFiles.setValue(resolved, watchFile(hostWithWatch, resolved, function () { invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); - })); + }, ts.PollingInterval.High, "Config file", resolved)); } } function watchWildCardDirectories(resolved, parsed) { if (!options.watch) return; ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { - return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + return watchDirectory(hostWithWatch, dir, function (fileOrDirectory) { var fileOrDirectoryPath = toPath(fileOrDirectory); if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { + writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory); return; } if (isOutputFile(fileOrDirectory, parsed)) { + writeLog(fileOrDirectory + " is output file"); return; } invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); - }, !!(flags & 1)); + }, flags, "Wild card directory", resolved); }); } function watchInputFiles(resolved, parsed) { if (!options.watch) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { - createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); - }); }, + createNewValue: function (path, input) { return watchFilePath(hostWithWatch, input, function () { return invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, path, "Source file", resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -74946,15 +75606,34 @@ var ts; reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); return; } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes) { + updateOutputTimestamps(proj); + return; + } var buildResult = buildSingleProject(resolved); - var dependencyGraph = getGlobalDependencyGraph(); - var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (buildResult & BuildResultFlags.AnyErrors) + return; + var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue; + var referencingProjects = referencingProjectsMap.getValue(resolved); if (!referencingProjects) return; - for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { - var project = _a[_i]; + for (var index = buildQueue.indexOf(resolved) + 1; index < buildQueue.length; index++) { + var project = buildQueue[index]; var prepend = referencingProjects.getValue(project); - if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + if (prepend !== undefined) { + var status_1 = projectStatus.getValue(project); + if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { + if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) { + projectStatus.setValue(project, { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: status_1.oldestOutputFileName, + newerProjectName: resolved + }); + } + } + else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) { + status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes; + } addProjToQueue(project); } } @@ -75019,94 +75698,110 @@ var ts; reportAndStoreErrors(proj, configFile.errors); return BuildResultFlags.None; } - var programOptions = { - projectReferences: configFile.projectReferences, - host: host, - rootNames: configFile.fileNames, - options: configFile.options, - configFileParsingDiagnostics: configFile.errors - }; - if (host.beforeCreateProgram) { - host.beforeCreateProgram(options); - } - var program = ts.createProgram(programOptions); - var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + projectCompilerOptions = configFile.options; + var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences); + projectCompilerOptions = baseCompilerOptions; + var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } - if (ts.getEmitDeclarations(program.getCompilerOptions())) { - var declDiagnostics = program.getDeclarationDiagnostics(); - if (declDiagnostics.length) { - return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); - } - } var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } + program.backupState(); var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - var emitDiagnostics; - var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; - ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, undefined, function (fileName, content, writeBom, onError) { + var declDiagnostics; + var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; + var outputFiles = []; + ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }); + if (declDiagnostics) { + program.restoreState(); + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); + } + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emittedOutputs = createFileMap(toPath); + outputFiles.forEach(function (_a) { + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName)) { - if (host.fileExists(fileName) && host.readFile(fileName) === content) { - priorChangeTime = host.getModifiedTime(fileName); + if (!anyDtsChanged && isDeclarationFile(name)) { + if (host.fileExists(name) && readFileWithCache(name) === text) { + priorChangeTime = host.getModifiedTime(name); } else { resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + emittedOutputs.setValue(name, true); + ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(name, priorChangeTime); } }); - if (emitDiagnostics) { + var emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); } + newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(configFile, newestDeclarationFileContentChangedTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); var status = { type: UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime, + oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile) }; diagnostics.removeKey(proj); projectStatus.setValue(proj, status); - if (host.afterProgramEmitAndDiagnostics) { - host.afterProgramEmitAndDiagnostics(program); - } + afterProgramCreate(proj, program); return resultFlags; function buildErrors(diagnostics, errorFlags, errorType) { resultFlags |= errorFlags; reportAndStoreErrors(proj, diagnostics); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); - if (host.afterProgramEmitAndDiagnostics) { - host.afterProgramEmitAndDiagnostics(program); - } + afterProgramCreate(proj, program); return resultFlags; } } + function afterProgramCreate(proj, program) { + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + if (options.watch) { + program.releaseProgram(); + builderPrograms.setValue(proj, program); + } + } function updateOutputTimestamps(proj) { if (options.dry) { return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (options.verbose) { - reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); - } - var now = new Date(); - var outputs = getAllProjectOutputs(proj); - var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { - var file = outputs_2[_i]; - if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); - } - host.setModifiedTime(file, now); - } + var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } + function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { + var outputs = getAllProjectOutputs(proj); + if (!skipOutputs || outputs.length !== skipOutputs.getSize()) { + if (options.verbose) { + reportStatus(verboseMessage, proj.options.configFilePath); + } + var now = host.now ? host.now() : new Date(); + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; + if (skipOutputs && skipOutputs.hasKey(file)) { + continue; + } + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + } + host.setModifiedTime(file, now); + if (proj.options.listEmittedFiles) { + writeFileName("TSFILE: " + file); + } + } + } + return priorNewestUpdateTime; + } function getFilesToClean() { var graph = getGlobalDependencyGraph(); var filesToDelete = []; @@ -75149,11 +75844,22 @@ var ts; if (options.watch) { reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); } + var savedReadFileWithCache = readFileWithCache; + var savedGetSourceFile = compilerHost.getSourceFile; + var _a = ts.changeCompilerHostLikeToUseCache(host, toPath, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return savedGetSourceFile.call.apply(savedGetSourceFile, [compilerHost].concat(args)); + }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, newReadFileWithCache = _a.readFileWithCache; + readFileWithCache = newReadFileWithCache; + compilerHost.getSourceFile = getSourceFileWithCache; var graph = getGlobalDependencyGraph(); reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; + for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) { + var next = _b[_i]; var proj = parseConfigFile(next); if (proj === undefined) { reportParseConfigFileDiagnostic(next); @@ -75190,6 +75896,13 @@ var ts; anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } reportErrorSummary(); + host.readFile = originalReadFile; + host.fileExists = originalFileExists; + host.directoryExists = originalDirectoryExists; + host.createDirectory = originalCreateDirectory; + host.writeFile = originalWriteFile; + compilerHost.getSourceFile = savedGetSourceFile; + readFileWithCache = savedReadFileWithCache; return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } function reportParseConfigFileDiagnostic(proj) { @@ -75209,7 +75922,7 @@ var ts; } } function relName(path) { - return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); } function verboseReportProjectStatus(configFileName, status) { if (!options.verbose) @@ -75239,6 +75952,19 @@ var ts; } } ts.getAllProjectOutputs = getAllProjectOutputs; + function getFirstProjectOutput(project) { + if (project.options.outFile || project.options.out) { + return ts.first(getOutFileOutputs(project)); + } + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + var outputs = getOutputFileNames(inputFile, project); + if (outputs.length) { + return ts.first(outputs); + } + } + return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output"); + } function formatUpToDateStatus(configFileName, status, relName, formatMessage) { switch (status.type) { case UpToDateStatusType.OutOfDateWithSelf: @@ -75280,17 +76006,17 @@ var ts; } ts.inspectValue = inspectValue; function getRecurser() { - var seen = new Set(); + var seen = []; var nameStack = []; return function (obj, name, cbOk, cbFail) { - if (seen.has(obj) || nameStack.length > 4) { - return cbFail(seen.has(obj), nameStack); + if (seen.indexOf(obj) !== -1 || nameStack.length > 4) { + return cbFail(seen.indexOf(obj) !== -1, nameStack); } - seen.add(obj); + seen.push(obj); nameStack.push(name); var res = cbOk(); nameStack.pop(); - seen.delete(obj); + seen.pop(); return res; }; } @@ -75347,8 +76073,8 @@ var ts; return key === "constructor" ? undefined : getValueInfo(key, value, recurser); }); } - var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); - var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + var ignoredProperties = ["arguments", "caller", "constructor", "eval", "super_"]; + var reservedFunctionProperties = Object.getOwnPropertyNames(ts.noop); function getEntriesOfObject(obj) { var seen = ts.createMap(); var entries = []; @@ -75357,8 +76083,8 @@ var ts; for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { var key = _a[_i]; if (!isJsPrivate(key) && - !ignoredProperties.has(key) && - (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + ignoredProperties.indexOf(key) === -1 && + (typeof obj !== "function" || reservedFunctionProperties.indexOf(key) === -1) && ts.addToSeen(seen, key)) { var value = safeGetPropertyOfObject(chain, key); if (!(key === "toString" && typeof value === "function" && value.length === 0)) { @@ -75384,7 +76110,7 @@ var ts; return { kind: 0, name: name, typeName: "any", comment: comment }; } function isJsPrivate(name) { - return name.startsWith("_"); + return ts.startsWith(name, "_"); } ts.isJsPrivate = isJsPrivate; function tryRequire(fileNameToRequire) { @@ -75509,6 +76235,11 @@ var ts; if (configFileName) { var configParseResult = ts.parseConfigFileWithSystem(configFileName, commandLineOptions, ts.sys, reportDiagnostic); // TODO: GH#18217 if (commandLineOptions.showConfig) { + if (configParseResult.errors.length !== 0) { + updateReportDiagnostic(configParseResult.options); + configParseResult.errors.forEach(reportDiagnostic); + return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } // tslint:disable-next-line:no-null-keyword ts.sys.write(JSON.stringify(ts.convertToTSConfig(configParseResult, configFileName, ts.sys), null, 4) + ts.sys.newLine); return ts.sys.exit(ts.ExitStatus.Success); @@ -75570,12 +76301,11 @@ var ts; if (buildOptions.watch) { reportWatchModeWithoutSysSupport(); } - // TODO: change this to host if watch => watchHost otherwiue without watch var buildHost = buildOptions.watch ? - ts.createSolutionBuilderWithWatchHost(ts.sys, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createWatchStatusReporter()) : - ts.createSolutionBuilderHost(ts.sys, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createReportErrorSummary(buildOptions)); - buildHost.beforeCreateProgram = enableStatistics; - buildHost.afterProgramEmitAndDiagnostics = reportStatistics; + ts.createSolutionBuilderWithWatchHost(ts.sys, ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createWatchStatusReporter()) : + ts.createSolutionBuilderHost(ts.sys, ts.createAbstractBuilder, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createReportErrorSummary(buildOptions)); + updateCreateProgram(buildHost); + buildHost.afterProgramEmitAndDiagnostics = function (program) { return reportStatistics(program.getProgram()); }; var builder = ts.createSolutionBuilder(buildHost, projects, buildOptions); if (buildOptions.clean) { return ts.sys.exit(builder.cleanAllProjects()); @@ -75593,6 +76323,9 @@ var ts; } function performCompilation(rootNames, projectReferences, options, configFileParsingDiagnostics) { var host = ts.createCompilerHost(options); + var currentDirectory = host.getCurrentDirectory(); + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); }); enableStatistics(options); var programOptions = { rootNames: rootNames, @@ -75606,15 +76339,18 @@ var ts; reportStatistics(program); return ts.sys.exit(exitStatus); } - function updateWatchCompilationHost(watchCompilerHost) { - var compileUsingBuilder = watchCompilerHost.createProgram; - watchCompilerHost.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) { + function updateCreateProgram(host) { + var compileUsingBuilder = host.createProgram; + host.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) { ts.Debug.assert(rootNames !== undefined || (options === undefined && !!oldProgram)); if (options !== undefined) { enableStatistics(options); } return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); }; + } + function updateWatchCompilationHost(watchCompilerHost) { + updateCreateProgram(watchCompilerHost); var emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate; // TODO: GH#18217 watchCompilerHost.afterProgramCreate = function (builderProgram) { emitFilesUsingBuilder(builderProgram); diff --git a/lib/tsserver.js b/lib/tsserver.js index d7f25907257..4cf85b4c5f3 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -88,7 +88,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = ts.versionMajorMinor + ".0-rc"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -1280,6 +1280,18 @@ var ts; return result; } ts.extend = extend; + function copyProperties(first, second) { + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + first[id] = second[id]; + } + } + } + ts.copyProperties = copyProperties; + function maybeBind(obj, fn) { + return fn ? fn.bind(obj) : undefined; + } + ts.maybeBind = maybeBind; function createMultiMap() { var map = createMap(); map.add = multiMapAdd; @@ -1998,7 +2010,11 @@ var ts; } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; function fill(length, cb) { - return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + var result = Array(length); + for (var i = 0; i < length; i++) { + result[i] = cb(i); + } + return result; } ts.fill = fill; })(ts || (ts = {})); @@ -3255,15 +3271,17 @@ var ts; CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; - CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; - CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; - CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; - CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; - CheckFlags[CheckFlags["Late"] = 1024] = "Late"; - CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter"; - CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter"; + CheckFlags[CheckFlags["HasLiteralType"] = 64] = "HasLiteralType"; + CheckFlags[CheckFlags["ContainsPublic"] = 128] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 256] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 512] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 1024] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 2048] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 4096] = "ReverseMapped"; + CheckFlags[CheckFlags["OptionalParameter"] = 8192] = "OptionalParameter"; + CheckFlags[CheckFlags["RestParameter"] = 16384] = "RestParameter"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + CheckFlags[CheckFlags["Discriminant"] = 96] = "Discriminant"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; (function (InternalSymbolName) { @@ -4015,6 +4033,16 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + /* @internal */ + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + ts.generateDjb2Hash = generateDjb2Hash; /** * Set a high stack trace limit to provide more information in case of an error. * Called for command-line and server use cases. @@ -4891,14 +4919,6 @@ var ts; return; } } - /** - * djb2 hashing algorithm - * http://www.cse.yorku.ca/~oz/hash.html - */ - function generateDjb2Hash(data) { - var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); - return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); - } function createMD5HashUsingNativeCrypto(data) { var hash = _crypto.createHash("md5"); hash.update(data); @@ -5252,6 +5272,9 @@ var ts; Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), + An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."), + A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."), + A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5407,8 +5430,6 @@ var ts; Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), - Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), - Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), @@ -5422,7 +5443,7 @@ var ts; A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), - In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values: diag(2474, ts.DiagnosticCategory.Error, "const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values_2474", "const enum member initializers can only contain literal values and other computed enum values."), 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: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'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."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), @@ -5438,11 +5459,11 @@ var ts; The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), - Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Tuple_type_0_of_length_1_has_no_element_at_index_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493", "Tuple type '{0}' of length '{1}' has no element at index '{2}'."), Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), - Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export: diag(2497, ts.DiagnosticCategory.Error, "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497", "This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export."), Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), @@ -5631,6 +5652,11 @@ var ts; Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), + No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments: diag(2743, ts.DiagnosticCategory.Error, "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743", "No overload expects {0} type arguments, but overloads do exist that expect either {1} or {2} type arguments."), + Type_parameter_defaults_can_only_reference_previously_declared_type_parameters: diag(2744, ts.DiagnosticCategory.Error, "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744", "Type parameter defaults can only reference previously declared type parameters."), + This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."), + This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."), + _0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5980,6 +6006,7 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -6058,6 +6085,7 @@ var ts; JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), + Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -6194,6 +6222,7 @@ var ts; Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), + Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"), }; })(ts || (ts = {})); var ts; @@ -6418,16 +6447,13 @@ var ts; return result; } ts.computeLineStarts = computeLineStarts; - function getPositionOfLineAndCharacter(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); + function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) { + return sourceFile.getPositionOfLineAndCharacter ? + sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) : + computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; /* @internal */ - function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); - } - ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; - /* @internal */ function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { if (line < 0 || line >= lineStarts.length) { if (allowEdits) { @@ -7003,6 +7029,7 @@ var ts; result = text.substring(start, end); // No need to use all the fragments; no _ removal needed } if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */)); return { type: 8 /* NumericLiteral */, value: "" + +result // if value is not an integer, it can be safely coerced to a number @@ -7011,9 +7038,29 @@ var ts; else { tokenValue = result; var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + checkForIdentifierStartAfterNumericLiteral(start); return { type: type, value: tokenValue }; } } + function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { + if (!isIdentifierStart(text.charCodeAt(pos), languageVersion)) { + return; + } + var identifierStart = pos; + var length = scanIdentifierParts().length; + if (length === 1 && text[identifierStart] === "n") { + if (isScientific) { + error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1); + } + else { + error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1); + } + } + else { + error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length); + pos = identifierStart; + } + } function scanOctalDigits() { var start = pos; while (isOctalDigit(text.charCodeAt(pos))) { @@ -8922,7 +8969,7 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, node.pos); } var isMissing = nodeIsMissing(errorNode); - var pos = isMissing + var pos = isMissing || ts.isJsxText(node) ? errorNode.pos : ts.skipTrivia(sourceFile.text, errorNode.pos); // These asserts should all be satisfied for a properly constructed `errorNode`. @@ -10117,6 +10164,7 @@ var ts; return node.initializer; } } + ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration; function getSingleVariableOfVariableStatement(node) { return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } @@ -12155,10 +12203,10 @@ var ts; } if (getCheckFlags(s) & 6 /* Synthetic */) { var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : - checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + var accessModifier = checkFlags & 512 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 128 /* ContainsPublic */ ? 4 /* Public */ : 16 /* Protected */; - var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + var staticModifier = checkFlags & 1024 /* ContainsStatic */ ? 32 /* Static */ : 0; return accessModifier | staticModifier; } if (s.flags & 4194304 /* Prototype */) { @@ -12405,6 +12453,10 @@ var ts; || kind === 290 /* JSDocVariadicType */; } ts.isTypeNodeKind = isTypeNodeKind; + function isAccessExpression(node) { + return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */; + } + ts.isAccessExpression = isAccessExpression; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -15283,6 +15335,8 @@ var ts; return path; } ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; function comparePathsWorker(a, b, componentComparer) { if (a === b) return 0 /* EqualTo */; @@ -15290,14 +15344,30 @@ var ts; return -1 /* LessThan */; if (b === undefined) return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, ts.getRootLength(a)); + var bRoot = b.substring(0, ts.getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var 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. var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 0; i < sharedLength; i++) { - var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; - var result = stringComparer(aComponents[i], bComponents[i]); - if (result !== 0 /* EqualTo */) { - return result; + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; } } return ts.compareValues(aComponents.length, bComponents.length); @@ -16789,15 +16859,15 @@ var ts; if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6 /* JSON */) { - var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); - result_1.referencedFiles = ts.emptyArray; - result_1.typeReferenceDirectives = ts.emptyArray; - result_1.libReferenceDirectives = ts.emptyArray; - result_1.amdDependencies = ts.emptyArray; - result_1.hasNoDefaultLib = false; - result_1.pragmas = ts.emptyMap; - return result_1; + var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_2.referencedFiles = ts.emptyArray; + result_2.typeReferenceDirectives = ts.emptyArray; + result_2.libReferenceDirectives = ts.emptyArray; + result_2.amdDependencies = ts.emptyArray; + result_2.hasNoDefaultLib = false; + result_2.pragmas = ts.emptyMap; + return result_2; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); @@ -17676,6 +17746,8 @@ var ts; return parseElement(); } function currentNode(parsingContext) { + // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse. + // // If there is an outstanding parse error that we've encountered, but not attached to // some node, then we cannot get a node from the old source tree. This is because we // want to mark the next node we encounter as being unusable. @@ -17683,25 +17755,15 @@ var ts; // Note: This may be too conservative. Perhaps we could reuse the node and set the bit // on it (or its leftmost child) as having the error. For now though, being conservative // is nice and likely won't ever affect perf. - if (parseErrorBeforeNextFinishedNode) { - return undefined; - } - if (!syntaxCursor) { - // if we don't have a cursor, we could never return a node from the old tree. + if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } var node = syntaxCursor.currentNode(scanner.getStartPos()); // Can't reuse a missing node. - if (ts.nodeIsMissing(node)) { - return undefined; - } // Can't reuse a node that intersected the change range. - if (node.intersectsChange) { - return undefined; - } // Can't reuse a node that contains a parse error. This is necessary so that we // produce the same set of errors again. - if (ts.containsParseError(node)) { + if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) { return undefined; } // We can only reuse a node if it was parsed under the same strict mode that we're @@ -17736,6 +17798,22 @@ var ts; nextToken(); return node; } + function isReusableParsingContext(parsingContext) { + switch (parsingContext) { + case 5 /* ClassMembers */: + case 2 /* SwitchClauses */: + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + case 6 /* EnumMembers */: + case 4 /* TypeMembers */: + case 8 /* VariableDeclarations */: + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + return true; + } + return false; + } function canReuseNode(node, parsingContext) { switch (parsingContext) { case 5 /* ClassMembers */: @@ -17755,22 +17833,20 @@ var ts; case 17 /* JSDocParameters */: case 16 /* Parameters */: return isReusableParameter(node); - case 18 /* RestProperties */: - return false; // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the // parser reached while looking ahead might be in the edited range (see the example // in canReuseVariableDeclaratorNode for a good case of this). - case 22 /* HeritageClauses */: + // case ParsingContext.HeritageClauses: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 19 /* TypeParameters */: + // case ParsingContext.TypeParameters: // This would probably be safe to reuse. There is no speculative parsing with // type parameters. Note that that's because type *parameters* only occur in // unambiguous *type* contexts. While type *arguments* occur in very ambiguous // *expression* contexts. - case 21 /* TupleElementTypes */: + // case ParsingContext.TupleElementTypes: // This would probably be safe to reuse. There is no speculative parsing with // tuple types. // Technically, type argument list types are probably safe to reuse. While @@ -17778,24 +17854,24 @@ var ts; // produced from speculative parsing a < as a type argument list), we only have // the types because speculative parsing succeeded. Thus, the lookahead never // went past the end of the list and rewound. - case 20 /* TypeArguments */: + // case ParsingContext.TypeArguments: // Note: these are almost certainly not safe to ever reuse. Expressions commonly // need a large amount of lookahead, and we should not reuse them as they may // have actually intersected the edit. - case 11 /* ArgumentExpressions */: + // case ParsingContext.ArgumentExpressions: // This is not safe to reuse for the same reason as the 'AssignmentExpression' // cases. i.e. a property assignment may end with an expression, and thus might // have lookahead far beyond it's old node. - case 12 /* ObjectLiteralMembers */: + // case ParsingContext.ObjectLiteralMembers: // This is probably not safe to reuse. There can be speculative parsing with // type names in a heritage clause. There can be generic names in the type // name list, and there can be left hand side expressions (which can have type // arguments.) - case 7 /* HeritageClauseElement */: + // case ParsingContext.HeritageClauseElement: // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes // on any given element. Same for children. - case 13 /* JsxAttributes */: - case 14 /* JsxChildren */: + // case ParsingContext.JsxAttributes: + // case ParsingContext.JsxChildren: } return false; } @@ -23025,17 +23101,18 @@ var ts; var libReferenceDirectives_1 = context.libReferenceDirectives; ts.forEach(ts.toArray(entryOrList), function (arg) { // TODO: GH#18217 + var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path; if (arg.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; } - else if (arg.arguments.types) { - typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + else if (types) { + typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value }); } - else if (arg.arguments.lib) { - libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + else if (lib) { + libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value }); } - else if (arg.arguments.path) { - referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + else if (path) { + referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value }); } else { reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); @@ -24707,12 +24784,12 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, !configParseResult.configFileSpecs ? function (_) { return false; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); - }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), exclude: configParseResult.configFileSpecs.validatedExcludeSpecs } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); @@ -24730,23 +24807,23 @@ var ts; } function matchesSpecs(path, includeSpecs, excludeSpecs) { if (!includeSpecs) - return function (_) { return false; }; + return function (_) { return true; }; var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { - return function (path) { return includeRe.test(path) && !excludeRe.test(path); }; + return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; } - return function (path) { return includeRe.test(path); }; + return function (path) { return !includeRe.test(path); }; } if (excludeRe) { - return function (path) { return !excludeRe.test(path); }; + return function (path) { return excludeRe.test(path); }; } - return function (_) { return false; }; + return function (_) { return true; }; } function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") { // this is of a type CommandLineOptionOfPrimitiveType return undefined; } @@ -24903,7 +24980,7 @@ var ts; result.push(tab + "}"); } result.push("}"); - return result.join(newLine); + return result.join(newLine) + newLine; } } ts.generateTSConfig = generateTSConfig; @@ -27188,6 +27265,10 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } + // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate) + if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) { + symbol.constEnumOnlyModule = false; + } if (symbolFlags & 67220415 /* Value */) { setValueDeclaration(symbol, node); } @@ -27676,7 +27757,7 @@ var ts; } function isNarrowableReference(expr) { return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || - ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || ts.isElementAccessExpression(expr) && expr.argumentExpression && (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && isNarrowableReference(expr.expression); @@ -31120,10 +31201,10 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(262144 /* TypeParameter */); - var markerSubType = createType(262144 /* TypeParameter */); + var markerSuperType = createTypeParameter(); + var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(262144 /* TypeParameter */); + var markerOtherType = createTypeParameter(); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); @@ -31313,7 +31394,6 @@ var ts; var _jsxFactoryEntity; var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); - var definitelyAssignableRelation = ts.createMap(); var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); @@ -32031,13 +32111,18 @@ var ts; } } break; + case 197 /* ArrowFunction */: + // when targeting ES6 or higher there is no 'arguments' in an arrow function + // for lower compile targets the resolved symbol is used to emit an error + if (compilerOptions.target >= 2 /* ES2015 */) { + break; + } + // falls through case 156 /* MethodDeclaration */: - case 155 /* MethodSignature */: case 157 /* Constructor */: case 158 /* GetAccessor */: case 159 /* SetAccessor */: case 239 /* FunctionDeclaration */: - case 197 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -32093,7 +32178,7 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol) && !isInTypeQuery(originalLocation)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { result.isReferenced |= meaning; } if (!result) { @@ -32171,7 +32256,8 @@ var ts; } // If we're in an external module, we can't reference value symbols created from UMD export declarations if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { - if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { + var merged = getMergedSymbol(result); + if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } @@ -32931,7 +33017,10 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { - error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 + ? "allowSyntheticDefaultImports" + : "esModuleInterop"; + error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); return symbol; } if (compilerOptions.esModuleInterop) { @@ -33226,6 +33315,12 @@ var ts; function createTypeofType() { return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); } + function createTypeParameter(symbol) { + var type = createType(262144 /* TypeParameter */); + if (symbol) + type.symbol = symbol; + return type; + } // A reserved member name starts with two underscores, but the third character cannot be an underscore // or the @ symbol. A third underscore indicates an escaped form of an identifer that started // with at least two underscores. The @ character indicates that the name is denoted by a well known ES @@ -34179,12 +34274,12 @@ var ts; return ts.createKeywordTypeNode(120 /* AnyKeyword */); } function addPropertyToElementList(propertySymbol, context, typeElements) { - var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 4096 /* ReverseMapped */); var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 2048 /* Late */) { var decl = ts.first(propertySymbol.declarations); if (hasLateBindableName(decl)) { trackComputedName(decl.name, saveEnclosingDeclaration, context); @@ -34357,7 +34452,7 @@ var ts; } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; - var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* RestParameter */; var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -34366,7 +34461,7 @@ var ts; cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); - var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* OptionalParameter */; var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, @@ -34762,6 +34857,21 @@ var ts; function isDefaultBindingContext(location) { return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); } + function getNameOfSymbolFromNameType(symbol, context) { + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 384 /* StringOrNumberLiteral */) { + var name = "" + nameType.value; + if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { + return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\""; + } + return name; + } + if (nameType.flags & 8192 /* UniqueESSymbol */) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; + } + } + } /** * Gets a human-readable name for a symbol. * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. @@ -34781,12 +34891,19 @@ var ts; } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - var name = ts.getNameOfDeclaration(declaration); - if (name) { + var name_2 = ts.getNameOfDeclaration(declaration); + if (name_2) { if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { return ts.symbolName(symbol); } - return ts.declarationNameToString(name); + if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 2048 /* Late */) && symbol.nameType && symbol.nameType.flags & 384 /* StringOrNumberLiteral */) { + // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name + var result = getNameOfSymbolFromNameType(symbol, context); + if (result !== undefined) { + return result; + } + } + return ts.declarationNameToString(name_2); } if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -34801,16 +34918,8 @@ var ts; return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } - var nameType = symbol.nameType; - if (nameType) { - if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { - return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; - } - if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { - return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; - } - } - return ts.symbolName(symbol); + var name = getNameOfSymbolFromNameType(symbol, context); + return name !== undefined ? name : ts.symbolName(symbol); } function isDeclarationVisible(node) { if (node) { @@ -35030,6 +35139,9 @@ var ts; var prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } + function getTypeOfPropertyOrIndexSignature(type, name) { + return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType; + } function isTypeAny(type) { return type && (type.flags & 1 /* Any */) !== 0; } @@ -35076,6 +35188,64 @@ var ts; var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); } + // Determine the control flow type associated with a destructuring declaration or assignment. The following + // forms of destructuring are possible: + // let { x } = obj; // BindingElement + // let [ x ] = obj; // BindingElement + // { x } = obj; // ShorthandPropertyAssignment + // { x: v } = obj; // PropertyAssignment + // [ x ] = obj; // Expression + // We construct a synthetic element access expression corresponding to 'obj.x' such that the control + // flow analyzer doesn't have to handle all the different syntactic forms. + function getFlowTypeOfDestructuring(node, declaredType) { + var reference = getSyntheticElementAccess(node); + return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType; + } + function getSyntheticElementAccess(node) { + var parentAccess = getParentElementAccess(node); + if (parentAccess && parentAccess.flowNode) { + var propName = getDestructuringPropertyName(node); + if (propName) { + var result = ts.createNode(190 /* ElementAccessExpression */, node.pos, node.end); + result.parent = node; + result.expression = parentAccess; + var literal = ts.createNode(10 /* StringLiteral */, node.pos, node.end); + literal.parent = result; + literal.text = propName; + result.argumentExpression = literal; + result.flowNode = parentAccess.flowNode; + return result; + } + } + } + function getParentElementAccess(node) { + var ancestor = node.parent.parent; + switch (ancestor.kind) { + case 186 /* BindingElement */: + case 275 /* PropertyAssignment */: + return getSyntheticElementAccess(ancestor); + case 187 /* ArrayLiteralExpression */: + return getSyntheticElementAccess(node.parent); + case 237 /* VariableDeclaration */: + return ancestor.initializer; + case 204 /* BinaryExpression */: + return ancestor.right; + } + } + function getDestructuringPropertyName(node) { + var parent = node.parent; + if (node.kind === 186 /* BindingElement */ && parent.kind === 184 /* ObjectBindingPattern */) { + return getLiteralPropertyNameText(node.propertyName || node.name); + } + if (node.kind === 275 /* PropertyAssignment */ || node.kind === 276 /* ShorthandPropertyAssignment */) { + return getLiteralPropertyNameText(node.name); + } + return "" + parent.elements.indexOf(node); + } + function getLiteralPropertyNameText(name) { + var type = getLiteralTypeFromPropertyName(name); + return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined; + } /** Return the inferred type for a binding element */ function getTypeForBindingElement(declaration) { var pattern = declaration.parent; @@ -35116,9 +35286,9 @@ var ts; else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; - var exprType = getLiteralTypeFromPropertyName(name); - var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); - type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); + var indexType = getLiteralTypeFromPropertyName(name); + var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); } } else { @@ -35135,21 +35305,13 @@ var ts; mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } + else if (isArrayLikeType(parentType)) { + var indexType = getLiteralType(index_1); + var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, declaration.name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); + } else { - // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_2 = pattern.elements.indexOf(declaration); - type = everyType(parentType, isTupleLikeType) ? - getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : - elementType; - if (!type) { - if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); - } - else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); - } - return errorType; - } + type = elementType; } } // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -35600,12 +35762,11 @@ var ts; return anyType; } // Handle export default expressions - if (ts.isSourceFile(declaration)) { - var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - if (!jsonSourceFile.statements.length) { + if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) { + if (!declaration.statements.length) { return emptyObjectType; } - var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + var type_1 = getWidenedLiteralType(checkExpression(declaration.statements[0].expression)); if (type_1.flags & 524288 /* Object */) { return getRegularTypeOfObjectLiteral(type_1); } @@ -35616,6 +35777,10 @@ var ts; } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & 512 /* ValueModule */) { + return getTypeOfFuncClassEnumModule(symbol); + } return errorType; } var type; @@ -35629,7 +35794,8 @@ var ts; || ts.isClassDeclaration(declaration) || ts.isFunctionDeclaration(declaration) || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { + || ts.isMethodSignature(declaration) + || ts.isSourceFile(declaration)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { return getTypeOfFuncClassEnumModule(symbol); @@ -35669,6 +35835,10 @@ var ts; return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } if (!popTypeResolution()) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & 512 /* ValueModule */) { + return getTypeOfFuncClassEnumModule(symbol); + } type = reportCircularityError(symbol); } return type; @@ -35862,7 +36032,7 @@ var ts; if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } - if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) { + if (ts.getCheckFlags(symbol) & 4096 /* ReverseMapped */) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -36241,9 +36411,8 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(262144 /* TypeParameter */); + type.thisType = createTypeParameter(symbol); type.thisType.isThisType = true; - type.thisType.symbol = symbol; type.thisType.constraint = type; } } @@ -36379,19 +36548,11 @@ var ts; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var type = createType(262144 /* TypeParameter */); - type.symbol = symbol; - links.declaredType = type; - } - return links.declaredType; + return links.declaredType || (links.declaredType = createTypeParameter(symbol)); } function getDeclaredTypeOfAlias(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); - } - return links.declaredType; + return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol))); } function getDeclaredTypeOfSymbol(symbol) { return tryGetDeclaredTypeOfSymbol(symbol) || errorType; @@ -36588,7 +36749,7 @@ var ts; * members. */ function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { - ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol."); + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 2048 /* Late */), "Expected a late-bound symbol."); symbol.flags |= symbolFlags; getSymbolLinks(member.symbol).lateSymbol = symbol; if (!symbol.declarations) { @@ -36645,7 +36806,7 @@ var ts; // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations. var lateSymbol = lateSymbols.get(memberName); if (!lateSymbol) - lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */)); + lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 2048 /* Late */)); // Report an error if a late-bound member has the same name as an early-bound member, // or if we have another early-bound symbol declaration with the same name and // conflicting flags. @@ -36654,10 +36815,10 @@ var ts; // If we have an existing early-bound member, combine its declarations so that we can // report an error at each declaration. var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_2 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); - lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); + var name_3 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + lateSymbol = createSymbol(0 /* None */, memberName, 2048 /* Late */); } lateSymbol.nameType = type; addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); @@ -36833,8 +36994,8 @@ var ts; var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; var restParams = ts.map(elementTypes, function (t, i) { var name = getParameterNameAtPosition(sig, restIndex_1 + i); - var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ : - i >= minLength_1 ? 4096 /* OptionalParameter */ : 0; + var checkFlags = i === tupleRestIndex_1 ? 16384 /* RestParameter */ : + i >= minLength_1 ? 8192 /* OptionalParameter */ : 0; var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; return symbol; @@ -36907,7 +37068,13 @@ var ts; // type is the union of the constituent return types. function getUnionSignatures(signatureLists) { var result; + var indexWithLengthOverOne; for (var i = 0; i < signatureLists.length; i++) { + if (signatureLists[i].length === 0) + return ts.emptyArray; + if (signatureLists[i].length > 1) { + indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets + } for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { var signature = _a[_i]; // Only process signatures with parameter lists that aren't already in the result list @@ -36932,8 +37099,82 @@ var ts; } } } + if (!ts.length(result) && indexWithLengthOverOne !== -1) { + // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single + // signature that handles all over them. We only do this when there are overloads in only one constituent. + // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of + // signatures from the type, whose ordering would be non-obvious) + var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; + var results = masterList.slice(); + var _loop_5 = function (signatures) { + if (signatures !== masterList) { + var signature_1 = signatures[0]; + ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); + results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); + if (!results) { + return "break"; + } + } + }; + for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) { + var signatures = signatureLists_1[_b]; + var state_2 = _loop_5(signatures); + if (state_2 === "break") + break; + } + result = results; + } return result || ts.emptyArray; } + function combineUnionThisParam(left, right) { + if (!left || !right) { + return left || right; + } + // A signature `this` type might be a read or a write position... It's very possible that it should be invariant + // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be + // permissive when calling, for now, we'll union the `this` types just like the overlapping-union-signature check does + var thisType = getUnionType([getTypeOfSymbol(left), getTypeOfSymbol(right)], 2 /* Subtype */); + return createSymbolWithType(left, thisType); + } + function combineUnionParameters(left, right) { + var longest = getParameterCount(left) >= getParameterCount(right) ? left : right; + var shorter = longest === left ? right : left; + var longestCount = getParameterCount(longest); + var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (var i = 0; i < longestCount; i++) { + var longestParamType = tryGetTypeAtPosition(longest, i); + var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + var unionParamType = getIntersectionType([longestParamType, shorterParamType]); + var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + var leftName = getParameterNameAtPosition(left, i); + var rightName = getParameterNameAtPosition(right, i); + var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), leftName === rightName ? leftName : "arg" + i); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args"); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfUnionMembers(left, right) { + var declaration = left.declaration; + var params = combineUnionParameters(left, right); + var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); + var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + var hasRestParam = left.hasRestParameter || right.hasRestParameter; + var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; + var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); + return result; + } function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; @@ -36951,7 +37192,7 @@ var ts; function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union // type use getPropertiesOfType (only the language service uses this). - var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); })); var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); @@ -36987,7 +37228,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_5 = function (i) { + var _loop_6 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -37010,7 +37251,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_5(i); + _loop_6(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -37086,7 +37327,7 @@ var ts; var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { var prop = _a[_i]; - var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + var checkFlags = 4096 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); inferredProp.declarations = prop.declarations; inferredProp.nameType = prop.nameType; @@ -37097,6 +37338,37 @@ var ts; } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); } + // Return the lower bound of the key type in a mapped type. Intuitively, the lower + // bound includes those keys that are known to always be present, for example because + // because of constraints on type parameters (e.g. 'keyof T' for a constrained T). + function getLowerBoundOfKeyType(type) { + if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) { + return type; + } + if (type.flags & 4194304 /* Index */) { + return getIndexType(getApparentType(type.type)); + } + if (type.flags & 16777216 /* Conditional */) { + return getLowerBoundOfConditionalType(type); + } + if (type.flags & 1048576 /* Union */) { + return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); + } + if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); + } + return neverType; + } + function getLowerBoundOfConditionalType(type) { + if (type.root.isDistributive) { + var constraint = getLowerBoundOfKeyType(type.checkType); + if (constraint !== type.checkType) { + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** Resolve the members of a mapped type { [P in K]: T } */ function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); @@ -37126,10 +37398,7 @@ var ts; } } else { - // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Then iterate over the constituents of the key type. - var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; - forEachType(iterationType, addMemberForKeyType); + forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); function addMemberForKeyType(t) { @@ -37313,7 +37582,7 @@ var ts; return list.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); }); } function getAllPossiblePropertiesOfTypes(types) { @@ -37377,7 +37646,7 @@ var ts; if (type.root.isDistributive) { var simplified = getSimplifiedType(type.checkType); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; - if (constraint) { + if (constraint && constraint !== type.checkType) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); if (!(instantiated.flags & 131072 /* Never */)) { @@ -37622,10 +37891,10 @@ var ts; commonFlags &= prop.flags; props = ts.appendIfUnique(props, prop); checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | - (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | - (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | - (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | - (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 512 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 1024 /* ContainsStatic */ : 0); if (!isPrototypeProperty(prop)) { syntheticFlag = 2 /* SyntheticProperty */; } @@ -37649,39 +37918,38 @@ var ts; return props[0]; } var declarations; - var commonType; + var firstType; var nameType; var propTypes = []; - var first = true; - var commonValueDeclaration; + var firstValueDeclaration; var hasNonUniformValueDeclaration = false; for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { var prop = props_1[_b]; - if (!commonValueDeclaration) { - commonValueDeclaration = prop.valueDeclaration; + if (!firstValueDeclaration) { + firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== commonValueDeclaration) { + else if (prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = ts.addRange(declarations, prop.declarations); var type = getTypeOfSymbol(prop); - if (first) { - commonType = type; + if (!firstType) { + firstType = type; nameType = prop.nameType; - first = false; } - else { - if (type !== commonType) { - checkFlags |= 32 /* HasNonUniformType */; - } + else if (type !== firstType) { + checkFlags |= 32 /* HasNonUniformType */; + } + if (isLiteralType(type)) { + checkFlags |= 64 /* HasLiteralType */; } propTypes.push(type); } ts.addRange(propTypes, indexTypes); var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; - if (!hasNonUniformValueDeclaration && commonValueDeclaration) { - result.valueDeclaration = commonValueDeclaration; + if (!hasNonUniformValueDeclaration && firstValueDeclaration) { + result.valueDeclaration = firstValueDeclaration; } result.declarations = declarations; result.nameType = nameType; @@ -37881,21 +38149,17 @@ var ts; var numTypeArguments = ts.length(typeArguments); if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { var result = typeArguments ? typeArguments.slice() : []; - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + // Map invalid forward references in default types to the error type for (var i = numTypeArguments; i < numTypeParameters; i++) { - result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + result[i] = errorType; } + var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny); for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, result); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { defaultType = anyType; } - result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType; } result.length = typeParameters.length; return result; @@ -37984,7 +38248,7 @@ var ts; var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); - var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */); + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 16384 /* RestParameter */); syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; if (lastParamVariadicType) { // Replace the last parameter with a rest parameter. @@ -38855,7 +39119,7 @@ var ts; if (arity) { typeParameters = new Array(arity); for (var i = 0; i < arity; i++) { - var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); + var typeParameter = typeParameters[i] = createTypeParameter(); if (i < maxLength) { var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); property.type = typeParameter; @@ -38877,7 +39141,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(262144 /* TypeParameter */); + type.thisType = createTypeParameter(); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -39378,8 +39642,13 @@ var ts; if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { - var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + if (prop.escapedName === "default" /* Default */) { + type = getLiteralType("default"); + } + else { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + } } if (type && type.flags & include) { return type; @@ -39469,14 +39738,14 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = isTypeUsableAsLateBoundName(indexType) - ? getLateBoundNameFromType(indexType) - : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) - ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) - : accessNode && ts.isPropertyName(accessNode) + var propName = isTypeUsableAsLateBoundName(indexType) ? + getLateBoundNameFromType(indexType) : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? + ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : + accessNode && ts.isPropertyName(accessNode) ? // late bound names are handled in the first branch, so here we only need to handle normal names - ? ts.getPropertyNameForPropertyNameNode(accessNode) - : undefined; + ts.getPropertyNameForPropertyNameNode(accessNode) : + undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { @@ -39498,7 +39767,12 @@ var ts; if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { var indexNode = getIndexNodeForAccessExpression(accessNode); - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + if (isTupleType(objectType)) { + error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName)); + } + else { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } } return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } @@ -39623,24 +39897,14 @@ var ts; // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we - // construct the type Box. We do not further simplify the result because mapped types can be recursive - // and we might never terminate. + // construct the type Box. if (isGenericMappedType(objectType)) { - return type.simplified = substituteIndexedMappedType(objectType, type); - } - if (objectType.flags & 262144 /* TypeParameter */) { - var constraint = getConstraintOfTypeParameter(objectType); - if (constraint && isGenericMappedType(constraint)) { - return type.simplified = substituteIndexedMappedType(constraint, type); - } + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var templateMapper = combineTypeMappers(objectType.mapper, mapper); + return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType); } return type.simplified = type; } - function substituteIndexedMappedType(objectType, type) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); - } function getIndexedAccessType(objectType, indexType, accessNode, missingType) { if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { @@ -39728,14 +39992,11 @@ var ts; if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } - // If this is a distributive conditional type and the check type is generic we need to defer - // resolution of the conditional type such that a later instantiation will properly distribute - // over union types. - var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); + var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */); var combinedMapper; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); - if (!isDeferred) { + if (!checkTypeInstantiable) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. @@ -39743,28 +40004,30 @@ var ts; } combinedMapper = combineTypeMappers(mapper, context); } - if (!isDeferred) { - if (extendsType.flags & 3 /* AnyOrUnknown */) { + // Instantiate the extends type including inferences for 'infer T' type parameters + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // We attempt to resolve the conditional type only when the check and extends types are non-generic + if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */)) { + if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) { return instantiateType(root.trueType, mapper); } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & 1 /* Any */) { return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); } - // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; // Return falseType for a definitely false extends check. We check an instantations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instatiations will be and we can just return the false branch type. - if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { return instantiateType(root.falseType, mapper); } - // Return trueType for a definitely true extends check. The definitely assignable relation excludes - // type variable constraints from consideration. Without the definitely assignable relation, the type + // Return trueType for a definitely true extends check. We check instantiations of the two + // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter + // that has no constraint. This ensures that, for example, the type // type Foo = T extends { x: string } ? string : number - // would immediately resolve to 'string' instead of being deferred. - if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + // doesn't immediately resolve to 'string' instead of being deferred. + if (isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) { return instantiateType(root.trueType, combinedMapper || mapper); } } @@ -40313,12 +40576,17 @@ var ts; function createReplacementMapper(source, target, baseMapper) { return function (t) { return t === source ? target : baseMapper(t); }; } - function wildcardMapper(type) { + function permissiveMapper(type) { return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; } + function getRestrictiveTypeParameter(tp) { + return !tp.constraint ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol)); + } + function restrictiveMapper(type) { + return type.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(type) : type; + } function cloneTypeParameter(typeParameter) { - var result = createType(262144 /* TypeParameter */); - result.symbol = typeParameter.symbol; + var result = createTypeParameter(typeParameter.symbol); result.target = typeParameter; return result; } @@ -40377,7 +40645,7 @@ var ts; } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */)); + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */)); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -40649,9 +40917,13 @@ var ts; } return type; } - function getWildcardInstantiation(type) { + function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : - type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); + type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); + } + function getRestrictiveInstantiation(type) { + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : + type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); @@ -40715,8 +40987,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - var body = node.body; - return body.kind === 218 /* Block */ ? false : isContextSensitive(body); + return !!node.body && node.body.kind !== 218 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -40833,7 +41104,7 @@ var ts; case 187 /* ArrayLiteralExpression */: return elaborateArrayLiteral(node, source, target, relation); case 268 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target, relation); + return elaborateJsxComponents(node, source, target, relation); case 197 /* ArrowFunction */: return elaborateArrowFunction(node, source, target, relation); } @@ -40974,8 +41245,117 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target, relation) { - return elaborateElementwise(generateJsxAttributes(node), source, target, relation); + function generateJsxChildren(node, getInvalidTextDiagnostic) { + var memberOffset, i, child, nameType, elem; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!ts.length(node.children)) + return [2 /*return*/]; + memberOffset = 0; + i = 0; + _a.label = 1; + case 1: + if (!(i < node.children.length)) return [3 /*break*/, 5]; + child = node.children[i]; + nameType = getLiteralType(i - memberOffset); + elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic); + if (!elem) return [3 /*break*/, 3]; + return [4 /*yield*/, elem]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + memberOffset++; + _a.label = 4; + case 4: + i++; + return [3 /*break*/, 1]; + case 5: return [2 /*return*/]; + } + }); + } + function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { + switch (child.kind) { + case 270 /* JsxExpression */: + // child is of the type of the expression + return { errorNode: child, innerExpression: child.expression, nameType: nameType }; + case 11 /* JsxText */: + if (child.containsOnlyWhiteSpaces) { + break; // Whitespace only jsx text isn't real jsx text + } + // child is a string + return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + // child is of type JSX.Element + return { errorNode: child, innerExpression: child, nameType: nameType }; + default: + return ts.Debug.assertNever(child, "Found invalid jsx child"); + } + } + function elaborateJsxComponents(node, source, target, relation) { + var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation); + var invalidTextDiagnostic; + if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) { + var containingElement = node.parent.parent; + var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName); + var childrenNameType = getLiteralType(childrenPropName); + var childrenTargetType = getIndexedAccessType(target, childrenNameType); + var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; }); + if (!ts.length(validChildren)) { + return result; + } + var moreThanOneRealChildren = ts.length(validChildren) > 1; + var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType); + var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); }); + if (moreThanOneRealChildren) { + if (arrayLikeTargetParts !== neverType) { + var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */)); + result = elaborateElementwise(generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic), realSource, arrayLikeTargetParts, relation) || result; + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + // arity mismatch + result = true; + error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, typeToString(childrenTargetType)); + } + } + else { + if (nonArrayLikeTargetParts !== neverType) { + var child = validChildren[0]; + var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic); + if (elem_1) { + result = elaborateElementwise((function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, elem_1]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); })(), source, target, relation) || result; + } + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + // arity mismatch + result = true; + error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, typeToString(childrenTargetType)); + } + } + } + return result; + function getInvalidTextualChildDiagnostic() { + if (!invalidTextDiagnostic) { + var tagNameText = ts.getTextOfNode(node.parent.tagName); + var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName); + var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName)); + var diagnostic = ts.Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2; + invalidTextDiagnostic = __assign({}, diagnostic, { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) }); + } + return invalidTextDiagnostic; + } } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -41228,7 +41608,7 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & 67108864 /* NonPrimitive */ ? true : type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : @@ -41311,9 +41691,7 @@ var ts; return true; if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) return true; - if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) - return false; - if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { + if (relation === assignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) return true; // Type number or any numeric literal type is assignable to any numeric enum type or any @@ -41483,7 +41861,7 @@ var ts; target = target.regularType; } if (source.flags & 33554432 /* Substitution */) { - source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; + source = source.substitute; } if (target.flags & 33554432 /* Substitution */) { target = target.typeVariable; @@ -41658,9 +42036,9 @@ var ts; if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + if (isExcessPropertyCheckTarget(target)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && + if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } @@ -41668,9 +42046,12 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_6 = function (prop) { + var _loop_7 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { + // Report error in terms of object types in the target as those are the only ones + // we check in isKnownProperty. + var errorTarget = filterType(target, isExcessPropertyCheckTarget); // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. @@ -41680,7 +42061,7 @@ var ts; // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) - reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget)); } else { // use the property's value declaration if the property is assigned inside the literal itself @@ -41692,14 +42073,14 @@ var ts; errorNode = propDeclaration; var name = propDeclaration.name; if (ts.isIdentifier(name)) { - suggestion = getSuggestionForNonexistentProperty(name, target); + suggestion = getSuggestionForNonexistentProperty(name, errorTarget); } } if (suggestion !== undefined) { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion); } else { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget)); } } } @@ -41708,9 +42089,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_6(prop); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_7(prop); + if (typeof state_3 === "object") + return state_3.value; } } return false; @@ -41747,7 +42128,8 @@ var ts; var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || - findBestTypeForInvokable(source, target); + findBestTypeForInvokable(source, target) || + findMostOverlappyType(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -41782,6 +42164,34 @@ var ts; return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); } } + function findMostOverlappyType(source, unionTarget) { + var bestMatch; + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target_1 = _a[_i]; + var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]); + if (overlap.flags & 4194304 /* Index */) { + // perfect overlap of keys + bestMatch = target_1; + matchingCount = Infinity; + } + else if (overlap.flags & 1048576 /* Union */) { + // We only want to account for literal types otherwise. + // If we have a union of index types, it seems likely that we + // needed to elaborate between two generic mapped types anyway. + var len = ts.length(ts.filter(overlap.types, isUnitType)); + if (len >= matchingCount) { + bestMatch = target_1; + matchingCount = len; + } + } + else if (isUnitType(overlap) && 1 >= matchingCount) { + bestMatch = target_1; + matchingCount = 1; + } + } + return bestMatch; + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { if (target.flags & 1048576 /* Union */) { @@ -41955,30 +42365,27 @@ var ts; } return result; } - function getConstraintForRelation(type) { - return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); - } function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { var flags = source.flags & target.flags; if (relation === identityRelation && !(flags & 524288 /* Object */)) { if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_2 = 0 /* False */; + var result_3 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_2; + if (result_3 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_3; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_2; + if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_3; } } } @@ -42027,24 +42434,23 @@ var ts; } // A type S is assignable to keyof T if S is assignable to keyof C, where C is the // simplified form of T or, if T doesn't simplify, the constraint of T. - if (relation !== definitelyAssignableRelation) { - var simplified = getSimplifiedType(target.type); - var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); - if (constraint) { - // We require Ternary.True here such that circular constraints don't cause - // false positives. For example, given 'T extends { [K in keyof T]: string }', - // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when - // related to other types. - if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { - return -1 /* True */; - } + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } else if (target.flags & 8388608 /* IndexedAccess */) { // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, // where C is the base constraint of T[K] - if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + if (relation !== identityRelation && + !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { var constraint = getBaseConstraintOfType(target); if (constraint && constraint !== target) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -42085,8 +42491,8 @@ var ts; return result; } } - var constraint = getConstraintForRelation(source); - if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + var constraint = getConstraintOfType(source); + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { errorInfo = saveErrorInfo; @@ -42126,7 +42532,7 @@ var ts; } } } - else if (relation !== definitelyAssignableRelation) { + else { var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { @@ -42145,7 +42551,7 @@ var ts; } else { // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + if (isPartialMappedType(target) && isEmptyObjectType(source)) { return -1 /* True */; } if (isGenericMappedType(target)) { @@ -42157,9 +42563,6 @@ var ts; } return 0 /* False */; } - if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { - return 0 /* False */; - } var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); if (relation !== identityRelation) { source = getApparentType(source); @@ -42239,10 +42642,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_3; - if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_4; + if (result_4 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_4 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -42252,10 +42655,10 @@ var ts; return propertiesIdenticalTo(source, target); } var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); - var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false); if (unmatchedProperty) { if (reportErrors) { - var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false)); if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it @@ -42331,7 +42734,7 @@ var ts; var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; - if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */ && hasDifferingDeclarations) { + if (ts.getCheckFlags(sourceProp) & 512 /* ContainsPrivate */ && hasDifferingDeclarations) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -43007,6 +43410,9 @@ var ts; function isTupleLikeType(type) { return isTupleType(type) || !!getPropertyOfType(type, "0"); } + function isArrayOrTupleLikeType(type) { + return isArrayLikeType(type) || isTupleLikeType(type); + } function getTupleElementType(type, index) { var propType = getTypeOfPropertyOfType(type, "" + index); if (propType) { @@ -43296,6 +43702,9 @@ var ts; // union includes empty object types (e.g. reducing {} | string to just {}). return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); } + if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.sameMap(type.types, getWidenedType)); + } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); } @@ -43382,6 +43791,10 @@ var ts; break; case 186 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + if (!noImplicitAny) { + // Don't issue a suggestion for binding elements since the codefix doesn't yet support them. + return; + } break; case 289 /* JSDocFunctionType */: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); @@ -43579,8 +43992,8 @@ var ts; inferTypes([inference], sourceType, templateType); return getTypeFromInference(inference); } - function getUnmatchedProperties(source, target, requireOptionalProperties) { - var properties, _i, properties_4, targetProp, sourceProp; + function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) { + var properties, _i, properties_4, targetProp, sourceProp, targetType, sourceType; return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -43588,24 +44001,34 @@ var ts; _i = 0, properties_4 = properties; _a.label = 1; case 1: - if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + if (!(_i < properties_4.length)) return [3 /*break*/, 6]; targetProp = properties_4[_i]; - if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 5]; sourceProp = getPropertyOfType(source, targetProp.escapedName); if (!!sourceProp) return [3 /*break*/, 3]; return [4 /*yield*/, targetProp]; case 2: _a.sent(); - _a.label = 3; + return [3 /*break*/, 5]; case 3: + if (!matchDiscriminantProperties) return [3 /*break*/, 5]; + targetType = getTypeOfSymbol(targetProp); + if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5]; + sourceType = getTypeOfSymbol(sourceProp); + if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5]; + return [4 /*yield*/, targetProp]; + case 4: + _a.sent(); + _a.label = 5; + case 5: _i++; return [3 /*break*/, 1]; - case 4: return [2 /*return*/]; + case 6: return [2 /*return*/]; } }); } - function getUnmatchedProperty(source, target, requireOptionalProperties) { - return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; + function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next().value; } function tupleTypesDefinitelyUnrelated(source, target) { return target.target.minLength > source.target.minLength || @@ -43615,7 +44038,8 @@ var ts; // Two tuple types with incompatible arities are definitely unrelated. // Two object types that each have a property that is unmatched in the other are definitely unrelated. return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || - !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) && + !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true); } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : @@ -44220,48 +44644,31 @@ var ts; // occurring in an apparent type position with '@' because the control flow type // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { - if (node.kind === 72 /* Identifier */) { - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; - } - if (node.kind === 100 /* ThisKeyword */) { - return "0"; - } - if (node.kind === 189 /* PropertyAccessExpression */) { - var key = getFlowCacheKey(node.expression); - return key && key + "." + ts.idText(node.name); - } - if (node.kind === 186 /* BindingElement */) { - var container = node.parent.parent; - var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); - var text = getBindingElementNameText(node); - var result = key && text && (key + "." + text); - return result; + switch (node.kind) { + case 72 /* Identifier */: + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + case 100 /* ThisKeyword */: + return "0"; + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + return getFlowCacheKey(node.expression); + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + var propName = getAccessedPropertyName(node); + if (propName !== undefined) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + propName; + } } return undefined; } - function getBindingElementNameText(element) { - var parent = element.parent; - if (parent.kind === 184 /* ObjectBindingPattern */) { - var name = element.propertyName || element.name; - switch (name.kind) { - case 72 /* Identifier */: - return ts.idText(name); - case 149 /* ComputedPropertyName */: - return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; - case 10 /* StringLiteral */: - case 8 /* NumericLiteral */: - return name.text; - default: - // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined - ts.Debug.fail("Unexpected name kind for binding element name"); - } - } - else { - return "" + parent.elements.indexOf(element); - } - } function isMatchingReference(source, target) { + switch (target.kind) { + case 195 /* ParenthesizedExpression */: + case 213 /* NonNullExpression */: + return isMatchingReference(source, target.expression); + } switch (source.kind) { case 72 /* Identifier */: return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || @@ -44271,34 +44678,24 @@ var ts; return target.kind === 100 /* ThisKeyword */; case 98 /* SuperKeyword */: return target.kind === 98 /* SuperKeyword */; + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + return isMatchingReference(source.expression, target); case 189 /* PropertyAccessExpression */: case 190 /* ElementAccessExpression */: - return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 186 /* BindingElement */: - if (target.kind !== 189 /* PropertyAccessExpression */) - return false; - var t = target; - if (t.name.escapedText !== getBindingElementNameText(source)) - return false; - if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { - return true; - } - if (source.parent.parent.kind === 237 /* VariableDeclaration */) { - var maybeId = source.parent.parent.initializer; - return !!maybeId && isMatchingReference(maybeId, t.expression); - } } return false; } function getAccessedPropertyName(access) { - return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + return access.kind === 189 /* PropertyAccessExpression */ ? access.name.escapedText : ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : undefined; } function containsMatchingReference(source, target) { - while (source.kind === 189 /* PropertyAccessExpression */) { + while (ts.isAccessExpression(source)) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -44311,42 +44708,37 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 189 /* PropertyAccessExpression */ && + var name; + return ts.isAccessExpression(target) && containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + (name = getAccessedPropertyName(target)) !== undefined && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), name); } function getDeclaredTypeOfReference(expr) { if (expr.kind === 72 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 189 /* PropertyAccessExpression */) { + if (ts.isAccessExpression(expr)) { var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + if (type) { + var propName = getAccessedPropertyName(expr); + return propName !== undefined ? getTypeOfPropertyOfType(type, propName) : undefined; + } } return undefined; } function isDiscriminantType(type) { - if (type.flags & 1048576 /* Union */) { - if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { - return true; - } - var combined = 0; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - combined |= t.flags; - } - if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { - return true; - } - } - return false; + return !!(type.flags & 1048576 /* Union */ && + (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */) || !isGenericIndexType(type))); } function isDiscriminantProperty(type, name) { if (type && type.flags & 1048576 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = + (prop.checkFlags & 96 /* Discriminant */) === 96 /* Discriminant */ && + isDiscriminantType(getTypeOfSymbol(prop)); } return !!prop.isDiscriminantProperty; } @@ -45205,25 +45597,23 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 1048576 /* Union */) || - expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { return false; } - var access = expr; - var name = getAccessedPropertyName(access); - if (!name) { + var name = getAccessedPropertyName(expr); + if (name === undefined) { return false; } - return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); - if (!propName) { + if (propName === undefined) { return type; } var propType = getTypeOfPropertyOfType(type, propName); var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOrIndexSignature(t, propName), narrowedPropType); }); } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { @@ -45568,9 +45958,8 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { - var accessExpression = invokedExpression; - var possibleReference = ts.skipParentheses(accessExpression.expression); + if (ts.isAccessExpression(invokedExpression)) { + var possibleReference = ts.skipParentheses(invokedExpression.expression); if (isMatchingReference(reference, possibleReference)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } @@ -45987,7 +46376,7 @@ var ts; } function checkThisBeforeSuper(node, container, diagnosticMessage) { var containingClassDecl = container.parent; - var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); + var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl); // If a containing class does not have extends clause or the class extends null // skip checking whether super statement is called before "this" accessing. if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { @@ -46308,7 +46697,7 @@ var ts; } // at this point the only legal case for parent is ClassLikeDeclaration var classLikeDeclaration = container.parent; - if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { + if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); return errorType; } @@ -46465,6 +46854,30 @@ var ts; tryGetTypeAtPosition(contextualSignature, index); } } + function getContextualTypeForVariableLikeDeclaration(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + switch (declaration.kind) { + case 151 /* Parameter */: + return getContextuallyTypedParameterType(declaration); + case 186 /* BindingElement */: + return getContextualTypeForBindingElement(declaration); + // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent + } + } + function getContextualTypeForBindingElement(declaration) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + var parentType = getContextualTypeForVariableLikeDeclaration(parentDeclaration); + if (parentType && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text !== undefined) { + return getTypeOfPropertyOfType(parentType, text); + } + } + } // In a variable, parameter or property declaration with a type annotation, // the contextual type of an initializer expression is the type of the variable, parameter or property. // Otherwise, in a parameter declaration of a contextually typed function expression, @@ -46476,32 +46889,13 @@ var ts; function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; if (ts.hasInitializer(declaration) && node === declaration.initializer) { - var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - return getTypeFromTypeNode(typeNode); + var result = getContextualTypeForVariableLikeDeclaration(declaration); + if (result) { + return result; } - if (declaration.kind === 151 /* Parameter */) { - var type = getContextuallyTypedParameterType(declaration); - if (type) { - return type; - } - } - if (ts.isBindingPattern(declaration.name)) { + if (ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } - if (ts.isBindingPattern(declaration.parent)) { - var parentDeclaration = declaration.parent.parent; - var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 186 /* BindingElement */) { - var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); - if (parentTypeNode && !ts.isBindingPattern(name)) { - var text = ts.getTextOfPropertyName(name); - if (text) { - return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); - } - } - } - } } return undefined; } @@ -46754,18 +47148,30 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForChildJsxExpression(node) { + function getContextualTypeForChildJsxExpression(node, child) { var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); - return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { + return undefined; + } + var childIndex = node.children.indexOf(child); + var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName); + return childFieldType && mapType(childFieldType, function (t) { + if (isArrayLikeType(t)) { + return getIndexedAccessType(t, getLiteralType(childIndex)); + } + else { + return t; + } + }, /*noReductions*/ true); } function getContextualTypeForJsxExpression(node) { var exprParent = node.parent; return ts.isJsxAttributeLike(exprParent) ? getContextualType(node) : ts.isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent, node) : undefined; } function getContextualTypeForJsxAttribute(attribute) { @@ -46932,6 +47338,27 @@ var ts; return propsType; } function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + if (sig.unionSignatures) { + // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input + // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature, + // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur + // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input. + // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane. + var results = []; + for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + var instance = getReturnTypeOfSignature(signature); + if (isTypeAny(instance)) { + return instance; + } + var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation); + if (!propType) { + return; + } + results.push(propType); + } + return getIntersectionType(results); + } var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } @@ -47323,7 +47750,7 @@ var ts; var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? computedNameType : undefined; var prop = nameType ? - createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : + createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 2048 /* Late */) : createSymbol(4 /* Property */ | member.flags, member.escapedName); if (nameType) { prop.nameType = nameType; @@ -47923,7 +48350,7 @@ var ts; return true; } } - else if (targetType.flags & 3145728 /* UnionOrIntersection */) { + else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -47931,12 +48358,14 @@ var ts; } } } - else if (targetType.flags & 16777216 /* Conditional */) { - return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || - isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); - } return false; } + function isExcessPropertyCheckTarget(type) { + return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) || + type.flags & 67108864 /* NonPrimitive */ || + type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) || + type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget)); + } function checkJsxExpression(node, checkMode) { if (node.expression) { var type = checkExpression(node.expression, checkMode); @@ -47977,7 +48406,7 @@ var ts; function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; - if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(prop) & 512 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; @@ -48341,7 +48770,7 @@ var ts; } } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (nodeForCheckWriteOnly && isInTypeQuery(nodeForCheckWriteOnly) || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { @@ -48367,7 +48796,7 @@ var ts; } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind === 189 /* PropertyAccessExpression */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -49052,15 +49481,32 @@ var ts; return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { - var min = Infinity; - var max = -Infinity; + var argCount = typeArguments.length; + // No overloads exist + if (signatures.length === 1) { + var sig = signatures[0]; + var min_1 = getMinTypeArgumentCount(sig.typeParameters); + var max = ts.length(sig.typeParameters); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, min_1 < max ? min_1 + "-" + max : min_1, argCount); + } + // Overloads exist + var belowArgCount = -Infinity; + var aboveArgCount = Infinity; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, ts.length(sig.typeParameters)); + var min_2 = getMinTypeArgumentCount(sig.typeParameters); + var max = ts.length(sig.typeParameters); + if (min_2 > argCount) { + aboveArgCount = Math.min(aboveArgCount, min_2); + } + else if (max < argCount) { + belowArgCount = Math.max(belowArgCount, max); + } } - var paramCount = min === max ? min : min + "-" + max; - return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) { + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; @@ -49289,7 +49735,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_7 = function (i) { + var _loop_8 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -49300,7 +49746,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_7(i); + _loop_8(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -49457,7 +49903,7 @@ var ts; */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { @@ -49965,6 +50411,7 @@ var ts; if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.nameType = getLiteralType("default"); newSymbol.target = resolveSymbol(symbol); memberTable.set("default" /* Default */, newSymbol); var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); @@ -50958,20 +51405,18 @@ var ts; if (rightIsThis === void 0) { rightIsThis = false; } if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 149 /* ComputedPropertyName */) { - checkComputedPropertyName(name); - } - if (isComputedNonLiteralName(name)) { - return undefined; - } - var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); - if (type) { - // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); - } - else { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + var text = ts.getTextOfPropertyName(name); + if (text) { + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + } } + var exprType = getLiteralTypeFromPropertyName(name); + var elementType = getIndexedAccessType(objectLiteralType, exprType, name); + var type = getFlowTypeOfDestructuring(property, elementType); + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else if (property.kind === 277 /* SpreadAssignment */) { if (languageVersion < 6 /* ESNext */) { @@ -50991,23 +51436,6 @@ var ts; error(property, ts.Diagnostics.Property_assignment_expected); } } - function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { - if (isTypeAny(objectLiteralType)) { - return objectLiteralType; - } - var type; - var text = ts.getTextOfPropertyName(name); - if (text) { // TODO: GH#26379 - var prop = getPropertyOfType(objectLiteralType, text); - if (prop) { - markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); - type = getTypeOfSymbol(prop); - } - type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); - } - return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); - } function checkArrayLiteralAssignment(node, sourceType, checkMode) { var elements = node.elements; if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { @@ -51027,39 +51455,30 @@ var ts; var element = elements[elementIndex]; if (element.kind !== 210 /* OmittedExpression */) { if (element.kind !== 208 /* SpreadElement */) { - var propName = "" + elementIndex; - var type = isTypeAny(sourceType) ? sourceType : - everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : - elementType; - if (type) { + var indexType = getLiteralType(elementIndex); + if (isArrayLikeType(sourceType)) { + // We create a synthetic expression so that getIndexedAccessType doesn't get confused + // when the element is a SyntaxKind.ElementAccessExpression. + var elementType_2 = getIndexedAccessType(sourceType, indexType, createSyntheticExpression(element, indexType)); + var type = getFlowTypeOfDestructuring(element, elementType_2); return checkDestructuringAssignment(element, type, checkMode); } - // We still need to check element expression here because we may need to set appropriate flag on the expression - // such as NodeCheckFlags.LexicalThis on "this"expression. - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } + return checkDestructuringAssignment(element, elementType, checkMode); + } + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { - if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + var restExpression = element.expression; + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { - var restExpression = element.expression; - if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { - error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - else { - checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = everyType(sourceType, isTupleType) ? - mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : - createArrayType(elementType); - return checkDestructuringAssignment(restExpression, type, checkMode); - } + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); } } } @@ -51580,7 +51999,8 @@ var ts; var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) || - isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + isTypeAssertion(initializer) || + isLiteralOfContextualType(type, getContextualType(initializer)) ? type : getWidenedLiteralType(type); if (ts.isInJSFile(declaration)) { if (widened.flags & 98304 /* Nullable */) { reportImplicitAny(declaration, anyType); @@ -52263,7 +52683,7 @@ var ts; // Constructors of classes with no extends clause may not contain super calls, whereas // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; - if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { + if (ts.getClassExtendsHeritageElement(containingClassDecl)) { captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); @@ -52457,7 +52877,6 @@ var ts; break; } } - checkGrammarForDisallowedTrailingComma(node.elementTypes); ts.forEach(node.elementTypes, checkSourceElement); } function checkUnionOrIntersectionType(node) { @@ -52826,10 +53245,10 @@ var ts; case 248 /* ImportEqualsDeclaration */: case 251 /* NamespaceImport */: case 250 /* ImportClause */: - var result_4 = 0 /* None */; + var result_5 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); - return result_4; + ts.forEach(target.declarations, function (d) { result_5 |= getDeclarationSpaces(d); }); + return result_5; case 237 /* VariableDeclaration */: case 186 /* BindingElement */: case 239 /* FunctionDeclaration */: @@ -53317,7 +53736,12 @@ var ts; return; } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + if (ts.isQualifiedName(node.name)) { + error(node.name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(node.name), ts.entityNameToString(node.name.left)); + } + else { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name)); + } } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && @@ -54855,6 +55279,7 @@ var ts; if (produceDiagnostics) { if (node.default) { seenDefault = true; + checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i); } else if (seenDefault) { error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); @@ -54868,6 +55293,23 @@ var ts; } } } + /** Check that type parameter defaults only reference previously declared type parameters */ + function checkTypeParametersNotReferenced(root, typeParameters, index) { + visit(root); + function visit(node) { + if (node.kind === 164 /* TypeReference */) { + var type = getTypeFromTypeReference(node); + if (type.flags & 262144 /* TypeParameter */) { + for (var i = index; i < typeParameters.length; i++) { + if (type.symbol === getSymbolOfNode(typeParameters[i])) { + error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters); + } + } + } + } + ts.forEachChild(node, visit); + } + } /** Check that type parameter lists are identical across multiple declarations */ function checkTypeParameterListsIdentical(symbol) { if (symbol.declarations.length === 1) { @@ -55058,7 +55500,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_8 = function (member) { + var _loop_9 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -55077,7 +55519,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_8(member); + _loop_9(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -55351,7 +55793,7 @@ var ts; return 0; } else if (isConstEnum) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values); } else if (member.parent.flags & 4194304 /* Ambient */) { error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); @@ -57433,7 +57875,7 @@ var ts; isLateBound: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); var symbol = node && getSymbolOfNode(node); - return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); + return !!(symbol && ts.getCheckFlags(symbol) & 2048 /* Late */); }, getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { @@ -58025,9 +58467,6 @@ var ts; if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070 checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); } - if (ts.isBindingPattern(parameter.name)) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } if (parameter.questionToken) { return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); } @@ -59013,9 +59452,6 @@ var ts; JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; // tslint:enable variable-name })(JsxNames || (JsxNames = {})); - function typeIsLiteralType(type) { - return !!(type.flags & 2944 /* Literal */); - } })(ts || (ts = {})); var ts; (function (ts) { @@ -64579,15 +65015,19 @@ var ts; // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + function getLineInfo(text, lineStarts) { + return { + getLineCount: function () { return lineStarts.length; }, + getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); } + }; + } + ts.getLineInfo = getLineInfo; /** * Tries to find the sourceMappingURL comment at the end of a file. - * @param text The source text of the file. - * @param lineStarts The line starts of the file. */ - function tryGetSourceMappingURL(text, lineStarts) { - if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } - for (var index = lineStarts.length - 1; index >= 0; index--) { - var line = text.substring(lineStarts[index], lineStarts[index + 1]); + function tryGetSourceMappingURL(lineInfo) { + for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) { + var line = lineInfo.getLineText(index); var comment = sourceMapCommentRegExp.exec(line); if (comment) { return comment[1]; @@ -64831,7 +65271,10 @@ var ts; && left.sourcePosition === right.sourcePosition; } function compareSourcePositions(left, right) { - return ts.compareValues(left.sourceIndex, right.sourceIndex); + // Compares sourcePosition without comparing sourceIndex + // since the mappings are grouped by sourceIndex + ts.Debug.assert(left.sourceIndex === right.sourceIndex); + return ts.compareValues(left.sourcePosition, right.sourcePosition); } function compareGeneratedPositions(left, right) { return ts.compareValues(left.generatedPosition, right.generatedPosition); @@ -64846,11 +65289,9 @@ var ts; var mapDirectory = ts.getDirectoryPath(mapPath); var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); - var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); - var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath); var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); - var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); - var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; })); var decodedMappings; var generatedMappings; var sourceMappings; @@ -64860,16 +65301,15 @@ var ts; }; function processMapping(mapping) { var generatedPosition = generatedFile !== undefined - ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true) : -1; var source; var sourcePosition; if (isSourceMapping(mapping)) { - var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; - var sourceFile = host.getSourceFileLike(sourceFilePath); + var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]); source = map.sources[mapping.sourceIndex]; sourcePosition = sourceFile !== undefined - ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true) : -1; } return { @@ -67287,6 +67727,7 @@ var ts; switch (node.literal.kind) { case 10 /* StringLiteral */: return ts.createIdentifier("String"); + case 202 /* PrefixUnaryExpression */: case 8 /* NumericLiteral */: return ts.createIdentifier("Number"); case 9 /* BigIntLiteral */: @@ -71057,7 +71498,7 @@ var ts; if (node.name) { enableSubstitutionsForBlockScopedBindings(); } - var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + var extendsClauseElement = ts.getClassExtendsHeritageElement(node); var classFunction = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -71466,7 +71907,7 @@ var ts; * synthesized call to `super` */ function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; + return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper); } /** * Adds statements to the body of a function-like node if it contains a rest parameter. @@ -71483,10 +71924,10 @@ var ts; return; } // `declarationName` is the name of the local declaration for the parameter. - var declarationName = ts.getMutableClone(parameter.name); + var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined); ts.setEmitFlags(declarationName, 48 /* NoSourceMap */); // `expressionName` is the name of the parameter used in expressions. - var expressionName = ts.getSynthesizedClone(parameter.name); + var expressionName = parameter.name.kind === 72 /* Identifier */ ? ts.getSynthesizedClone(parameter.name) : declarationName; var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; @@ -71510,6 +71951,11 @@ var ts; ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); statements.push(forStatement); + if (parameter.name.kind !== 72 /* Identifier */) { + // do the actual destructuring of the rest parameter if necessary + statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */)); + } } /** * Adds a statement to capture the `this` of a function declaration if it is needed. @@ -79745,6 +80191,7 @@ var ts; case 241 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; + case 166 /* ConstructorType */: case 161 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; @@ -79763,6 +80210,7 @@ var ts; diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; + case 165 /* FunctionType */: case 239 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; @@ -80340,7 +80788,10 @@ var ts; if (!ts.isLateVisibilityPaintedStatement(i)) { return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); } + var priorNeedsDeclare = needsDeclare; + needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + needsDeclare = priorNeedsDeclare; lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); } // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list @@ -80703,7 +81154,8 @@ var ts; var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression - var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 + var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default"; + var newId_1 = ts.createOptimisticUniqueName(oldId + "_base"); getSymbolAccessibilityDiagnostic = function () { return ({ diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: extendsClause_1, @@ -80857,7 +81309,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_9 = function (range) { + var _loop_10 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -80871,7 +81323,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_9(range); + _loop_10(range); } } return prop; @@ -82761,18 +83213,22 @@ var ts; function emitPropertyAccessExpression(node) { var indentBeforeDot = false; var indentAfterDot = false; + var dotRangeFirstCommentStart = ts.skipTrivia(currentSourceFile.text, node.expression.end, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ true); + var dotRangeStart = ts.skipTrivia(currentSourceFile.text, dotRangeFirstCommentStart); + var dotRangeEnd = dotRangeStart + 1; if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { - var dotRangeStart = node.expression.end; - var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; var dotToken = ts.createToken(24 /* DotToken */); - dotToken.pos = dotRangeStart; + dotToken.pos = node.expression.end; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } emitExpression(node.expression); increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + var dotHasCommentTrivia = dotRangeFirstCommentStart !== dotRangeStart; + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression, dotHasCommentTrivia); if (shouldEmitDotDot) { writePunctuation("."); } @@ -82783,13 +83239,15 @@ var ts; } // 1..toString is a valid property access, emit a dot after the literal // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal - function needsDotDotForPropertyAccess(expression) { + function needsDotDotForPropertyAccess(expression, dotHasTrivia) { expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); - return !expression.numericLiteralFlags - && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); + // If he number will be printed verbatim and it doesn't already contain a dot, add one + // if the expression doesn't have any comments that will be emitted. + return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)) && + (!dotHasTrivia || printerOptions.removeComments); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -83540,6 +83998,7 @@ var ts; function emitJsxSelfClosingElement(node) { writePunctuation("<"); emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); writeSpace(); emit(node.attributes); writePunctuation("/>"); @@ -83553,6 +84012,7 @@ var ts; writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } @@ -85158,7 +85618,7 @@ var ts; if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { return; } - var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character; sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, /*nameIndex*/ undefined); } @@ -85567,7 +86027,7 @@ var ts; }, flags); } function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { - return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2); } function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); @@ -85648,7 +86108,7 @@ var ts; var text; try { ts.performance.mark("beforeIORead"); - text = system.readFile(fileName, options.charset); + text = compilerHost.readFile(fileName); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -85674,7 +86134,12 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - system.createDirectory(directoryPath); + if (compilerHost.createDirectory) { + compilerHost.createDirectory(directoryPath); + } + else { + system.createDirectory(directoryPath); + } } } var outputFingerprints; @@ -85726,7 +86191,7 @@ var ts; } var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); var realpath = system.realpath && (function (path) { return system.realpath(path); }); - return { + var compilerHost = { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -85742,10 +86207,112 @@ var ts; getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }, + createDirectory: function (d) { return system.createDirectory(d); } }; + return compilerHost; } ts.createCompilerHostWorker = createCompilerHostWorker; + /*@internal*/ + function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) { + var originalReadFile = host.readFile; + var originalFileExists = host.fileExists; + var originalDirectoryExists = host.directoryExists; + var originalCreateDirectory = host.createDirectory; + var originalWriteFile = host.writeFile; + var readFileCache = ts.createMap(); + var fileExistsCache = ts.createMap(); + var directoryExistsCache = ts.createMap(); + var sourceFileCache = ts.createMap(); + var readFileWithCache = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value || undefined; + return setReadFileCache(key, fileName); + }; + var setReadFileCache = function (key, fileName) { + var newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue || false); + return newValue; + }; + host.readFile = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value; // could be .d.ts from output + if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) { + return originalReadFile.call(host, fileName); + } + return setReadFileCache(key, fileName); + }; + var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { + var key = toPath(fileName); + var value = sourceFileCache.get(key); + if (value) + return value; + var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile); + if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) { + sourceFileCache.set(key, sourceFile); + } + return sourceFile; + } : undefined; + // fileExists for any kind of extension + host.fileExists = function (fileName) { + var key = toPath(fileName); + var value = fileExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + if (originalWriteFile) { + host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) { + var key = toPath(fileName); + fileExistsCache.delete(key); + var value = readFileCache.get(key); + if (value && value !== data) { + readFileCache.delete(key); + sourceFileCache.delete(key); + } + else if (getSourceFileWithCache) { + var sourceFile = sourceFileCache.get(key); + if (sourceFile && sourceFile.text !== data) { + sourceFileCache.delete(key); + } + } + originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles); + }; + } + // directoryExists + if (originalDirectoryExists && originalCreateDirectory) { + host.directoryExists = function (directory) { + var key = toPath(directory); + var value = directoryExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + return { + originalReadFile: originalReadFile, + originalFileExists: originalFileExists, + originalDirectoryExists: originalDirectoryExists, + originalCreateDirectory: originalCreateDirectory, + originalWriteFile: originalWriteFile, + getSourceFileWithCache: getSourceFileWithCache, + readFileWithCache: readFileWithCache + }; + } + ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (ts.getEmitDeclarations(program.getCompilerOptions())) { @@ -86078,7 +86645,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); - var configParsingHost = parseConfigHostFromCompilerHost(host); + var configParsingHost = parseConfigHostFromCompilerHostLike(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); @@ -86124,6 +86691,12 @@ var ts; var sourceFileToPackageName = ts.createMap(); // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. var redirectTargetsMap = ts.createMultiMap(); + /** + * map with + * - SourceFile if present + * - false if sourceFile missing for source of project reference redirect + * - undefined otherwise + */ var filesByName = ts.createMap(); var missingFilePaths; // stores 'filename -> file association' ignoring case @@ -86184,7 +86757,10 @@ var ts; }); } } - missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) { + var path = _a[0], file = _a[1]; + return file === undefined ? path : undefined; + })); files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); processingDefaultLibFiles = undefined; processingOtherFiles = undefined; @@ -86330,13 +86906,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_5 = []; + var result_6 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_5.push(resolvedModule); + result_6.push(resolvedModule); } - return result_5; + return result_6; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -86792,7 +87368,7 @@ var ts; return getSourceFileByPath(toPath(fileName)); } function getSourceFileByPath(path) { - return filesByName.get(path); + return filesByName.get(path) || undefined; } function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { if (sourceFile) { @@ -87270,7 +87846,7 @@ var ts; } /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ function getSourceFileFromReference(referencingFile, ref) { - return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; }); } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { @@ -87376,7 +87952,9 @@ var ts; processReferencedFiles(file_1, isDefaultLib); processTypeReferenceDirectives(file_1); } - processLibReferenceDirectives(file_1); + if (!options.noLib) { + processLibReferenceDirectives(file_1); + } modulesWithElidedImports.set(file_1.path, false); processImportedModules(file_1); } @@ -87387,7 +87965,7 @@ var ts; processImportedModules(file_1); } } - return file_1; + return file_1 || undefined; } var redirectedPath; if (refFile) { @@ -87453,7 +88031,9 @@ var ts; processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } - processLibReferenceDirectives(file); + if (!options.noLib) { + processLibReferenceDirectives(file); + } // always process imported modules to record module name resolutions processImportedModules(file); if (isDefaultLib) { @@ -87466,9 +88046,12 @@ var ts; return file; } function addFileToFilesByName(file, path, redirectedPath) { - filesByName.set(path, file); if (redirectedPath) { filesByName.set(redirectedPath, file); + filesByName.set(path, file || false); + } + else { + filesByName.set(path, file); } } function getProjectReferenceRedirect(fileName) { @@ -88131,21 +88714,22 @@ var ts; } ts.createProgram = createProgram; /* @internal */ - function parseConfigHostFromCompilerHost(host) { + function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) { + if (directoryStructureHost === void 0) { directoryStructureHost = host; } return { - fileExists: function (f) { return host.fileExists(f); }, + fileExists: function (f) { return directoryStructureHost.fileExists(f); }, readDirectory: function (root, extensions, excludes, includes, depth) { - ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(root, extensions, excludes, includes, depth); + ts.Debug.assertDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); }, - readFile: function (f) { return host.readFile(f); }, + readFile: function (f) { return directoryStructureHost.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, - onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }), trace: host.trace ? function (s) { return host.trace(s); } : undefined }; } - ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike; function resolveProjectReferencePath(hostOrRef, ref) { var passedInRef = ref ? ref : hostOrRef; return ts.resolveConfigFileProjectName(passedInRef.path); @@ -88212,6 +88796,10 @@ var ts; } } ts.getFileEmitOutput = getFileEmitOutput; + function cloneMapOrUndefined(map) { + return map ? ts.cloneMap(map) : undefined; + } + ts.cloneMapOrUndefined = cloneMapOrUndefined; })(ts || (ts = {})); /*@internal*/ (function (ts) { @@ -88359,12 +88947,35 @@ var ts; fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, - allFilesExcludingDefaultLibraryFile: undefined, - allFileNames: undefined + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature }; } BuilderState.create = create; + /** + * Releases needed properties + */ + function releaseCache(state) { + state.allFilesExcludingDefaultLibraryFile = undefined; + state.allFileNames = undefined; + } + BuilderState.releaseCache = releaseCache; + /** + * Creates a clone of the state + */ + function clone(state) { + var fileInfos = ts.createMap(); + state.fileInfos.forEach(function (value, key) { + fileInfos.set(key, __assign({}, value)); + }); + // Dont need to backup allFiles info since its cache anyway + return { + fileInfos: fileInfos, + referencedMap: ts.cloneMapOrUndefined(state.referencedMap), + exportedModulesMap: ts.cloneMapOrUndefined(state.exportedModulesMap), + hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature), + }; + } + BuilderState.clone = clone; /** * Gets the files affected by the path from the program */ @@ -88613,7 +89224,7 @@ var ts; var seenFileNamesMap = ts.createMap(); // Start with the paths this file was referenced by seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); - var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath); while (queue.length > 0) { var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { @@ -88621,7 +89232,7 @@ var ts; seenFileNamesMap.set(currentPath, currentSourceFile); if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 queue.push.apply(// TODO: GH#18217 - queue, getReferencedByPaths(state, currentPath)); + queue, getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } } @@ -88645,24 +89256,32 @@ var ts; var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); - if (!compilerOptions.outFile && !compilerOptions.out) { + state.compilerOptions = compilerOptions; + // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them + // With --isolatedModules, emitting changed file doesnt emit dependent files so we cant know of dependent files to retrieve errors so dont cache the errors + if (!compilerOptions.outFile && !compilerOptions.out && !compilerOptions.isolatedModules) { state.semanticDiagnosticsPerFile = ts.createMap(); } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; + var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { - ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + var affectedSignatures = oldState.currentAffectedFilesSignatures; + ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); } if (canCopySemanticDiagnostics) { ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); } // Copy old state's changed files set ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit; + state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; + } } // Update changed files and copy semantic diagnostics if we can var referencedMap = state.referencedMap; @@ -88686,7 +89305,7 @@ var ts; state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { - var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + var sourceFile = newProgram.getSourceFileByPath(sourceFilePath); if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { return; } @@ -88706,6 +89325,36 @@ var ts; }); return state; } + /** + * Releases program and other related not needed properties + */ + function releaseCache(state) { + ts.BuilderState.releaseCache(state); + state.program = undefined; + } + /** + * Creates a clone of the state + */ + function cloneBuilderProgramState(state) { + var newState = ts.BuilderState.clone(state); + newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile); + newState.changedFilesSet = ts.cloneMap(state.changedFilesSet); + newState.affectedFiles = state.affectedFiles; + newState.affectedFilesIndex = state.affectedFilesIndex; + newState.currentChangedFilePath = state.currentChangedFilePath; + newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures); + newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap); + newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles); + newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; + newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState); + newState.program = state.program; + newState.compilerOptions = state.compilerOptions; + newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit; + newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; + newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles); + newState.programEmitComplete = state.programEmitComplete; + return newState; + } /** * Verifies that source file is ok to be used in calls that arent handled by next */ @@ -88752,22 +89401,43 @@ var ts; } // With --out or --outFile all outputs go into single file // so operations are performed directly on program, return program - var compilerOptions = state.program.getCompilerOptions(); + var program = ts.Debug.assertDefined(state.program); + var compilerOptions = program.getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); - return state.program; + return program; } // Get next batch of affected files state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); if (state.exportedModulesMap) { state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); } - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); } } + /** + * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet + */ + function getNextAffectedFilePendingEmit(state) { + var affectedFilesPendingEmit = state.affectedFilesPendingEmit; + if (affectedFilesPendingEmit) { + var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap()); + for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) { + var affectedFile = ts.Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]); + if (affectedFile && !seenEmittedFiles.has(affectedFile.path)) { + // emit this file + state.affectedFilesPendingEmitIndex = i; + return affectedFile; + } + } + state.affectedFilesPendingEmit = undefined; + state.affectedFilesPendingEmitIndex = undefined; + } + return undefined; + } /** * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file */ @@ -88779,9 +89449,10 @@ var ts; // Clean lib file diagnostics if its all files excluding default files to emit if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { state.cleanedDiagnosticsOfLibFiles = true; - var options_2 = state.program.getCompilerOptions(); - if (ts.forEach(state.program.getSourceFiles(), function (f) { - return state.program.isSourceFileDefaultLibrary(f) && + var program_1 = ts.Debug.assertDefined(state.program); + var options_2 = program_1.getCompilerOptions(); + if (ts.forEach(program_1.getSourceFiles(), function (f) { + return program_1.isSourceFileDefaultLibrary(f) && !ts.skipTypeChecking(f, options_2) && removeSemanticDiagnosticsOf(state, f.path); })) { @@ -88842,11 +89513,20 @@ var ts; return true; } // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected - return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(filePath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); - }); + })) { + return true; + } + // Remove diagnostics of files that import this file (without going to exports of referencing files) + return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) { + return referencesInFile.has(filePath) && + !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file + removeSemanticDiagnosticsOf(state, referencingFilePath); + } // Dont add to seen since this is not yet done with the export removal + ); } /** * Removes semantic diagnostics for path and @@ -88864,20 +89544,26 @@ var ts; * This is called after completing operation on the next affected file. * The operations here are postponed to ensure that cancellation during the iteration is handled correctly */ - function doneWithAffectedFile(state, affected) { + function doneWithAffectedFile(state, affected, isPendingEmit) { if (affected === state.program) { state.changedFilesSet.clear(); + state.programEmitComplete = true; } else { state.seenAffectedFiles.set(affected.path, true); - state.affectedFilesIndex++; + if (isPendingEmit) { + state.affectedFilesPendingEmitIndex++; + } + else { + state.affectedFilesIndex++; + } } } /** * Returns the result with affected file */ - function toAffectedFileResult(state, result, affected) { - doneWithAffectedFile(state, affected); + function toAffectedFileResult(state, result, affected, isPendingEmit) { + doneWithAffectedFile(state, affected, isPendingEmit); return { result: result, affected: affected }; } /** @@ -88886,14 +89572,18 @@ var ts; */ function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { var path = sourceFile.path; - var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - return cachedDiagnostics; + if (state.semanticDiagnosticsPerFile) { + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } } // Diagnostics werent cached, get them from program, and cache the result - var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); - state.semanticDiagnosticsPerFile.set(path, diagnostics); + var diagnostics = ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); + if (state.semanticDiagnosticsPerFile) { + state.semanticDiagnosticsPerFile.set(path, diagnostics); + } return diagnostics; } var BuilderProgramKind; @@ -88918,7 +89608,7 @@ var ts; rootNames: newProgramOrRootNames, options: hostOrOptions, host: oldProgramOrHost, - oldProgram: oldProgram && oldProgram.getProgram(), + oldProgram: oldProgram && oldProgram.getProgramOrUndefined(), configFileParsingDiagnostics: configFileParsingDiagnostics, projectReferences: projectReferences }); @@ -88949,26 +89639,29 @@ var ts; /** * Computing hash to for signature verification */ - var computeHash = host.createHash || ts.identity; + var computeHash = host.createHash || ts.generateDjb2Hash; var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + var backupState; // To ensure that we arent storing any references to old program or new program without state newProgram = undefined; // TODO: GH#18217 oldProgram = undefined; oldState = undefined; - var result = { - getState: function () { return state; }, - getProgram: function () { return state.program; }, - getCompilerOptions: function () { return state.program.getCompilerOptions(); }, - getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, - getSourceFiles: function () { return state.program.getSourceFiles(); }, - getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, - getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, - getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, - getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, - getSemanticDiagnostics: getSemanticDiagnostics, - emit: emit, - getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, - getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + var result = createRedirectedBuilderProgram(state, configFileParsingDiagnostics); + result.getState = function () { return state; }; + result.backupState = function () { + ts.Debug.assert(backupState === undefined); + backupState = cloneBuilderProgramState(state); + }; + result.restoreState = function () { + state = ts.Debug.assertDefined(backupState); + backupState = undefined; + }; + result.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.assertDefined(state.program), sourceFile); }; + result.getSemanticDiagnostics = getSemanticDiagnostics; + result.emit = emit; + result.releaseProgram = function () { + releaseCache(state); + backupState = undefined; }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; @@ -88987,14 +89680,33 @@ var ts; */ function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { var affected = getNextAffectedFile(state, cancellationToken, computeHash); + var isPendingEmitFile = false; if (!affected) { - // Done - return undefined; + if (!state.compilerOptions.out && !state.compilerOptions.outFile) { + affected = getNextAffectedFilePendingEmit(state); + if (!affected) { + return undefined; + } + isPendingEmitFile = true; + } + else { + var program = ts.Debug.assertDefined(state.program); + // Check if program uses any prepend project references, if thats the case we cant track of the js files of those, so emit even though there are no changes + if (state.programEmitComplete || !ts.some(program.getProjectReferences(), function (ref) { return !!ref.prepend; })) { + state.programEmitComplete = true; + return undefined; + } + affected = program; + } + } + // Mark seen emitted files if there are pending files to be emitted + if (state.affectedFilesPendingEmit && state.program !== affected) { + (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.path, true); } return toAffectedFileResult(state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file - state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + ts.Debug.assertDefined(state.program).emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected, isPendingEmitFile); } /** * Emits the JavaScript and declaration files. @@ -89031,7 +89743,7 @@ var ts; }; } } - return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return ts.Debug.assertDefined(state.program).emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); } /** * Return the semantic diagnostics for the next affected file or undefined if iteration is complete @@ -89067,25 +89779,38 @@ var ts; */ function getSemanticDiagnostics(sourceFile, cancellationToken) { assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); - var compilerOptions = state.program.getCompilerOptions(); + var compilerOptions = ts.Debug.assertDefined(state.program).getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); // We dont need to cache the diagnostics just return them from program - return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + return ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); } if (sourceFile) { return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); } - if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { - // When semantic builder asks for diagnostics of the whole program, - // ensure that all the affected files are handled - var affected = void 0; - while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { - doneWithAffectedFile(state, affected); + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected; + var affectedFilesPendingEmit; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + if (affected !== state.program && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push(affected.path); + } + doneWithAffectedFile(state, affected); + } + // In case of emit builder, cache the files to be emitted + if (affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, affectedFilesPendingEmit); + // affectedFilesPendingEmitIndex === undefined + // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files + // so start from 0 as array would be affectedFilesPendingEmit + // else, continue to iterate from existing index, the current set is appended to existing files + if (state.affectedFilesPendingEmitIndex === undefined) { + state.affectedFilesPendingEmitIndex = 0; } } var diagnostics; - for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { var sourceFile_2 = _a[_i]; diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); } @@ -89093,6 +89818,32 @@ var ts; } } ts.createBuilderProgram = createBuilderProgram; + function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { + return { + getState: ts.notImplemented, + backupState: ts.noop, + restoreState: ts.noop, + getProgram: getProgram, + getProgramOrUndefined: function () { return state.program; }, + releaseProgram: function () { return state.program = undefined; }, + getCompilerOptions: function () { return state.compilerOptions; }, + getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); }, + getSourceFiles: function () { return getProgram().getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); }, + emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); }, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); } + }; + function getProgram() { + return ts.Debug.assertDefined(state.program); + } + } + ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram; })(ts || (ts = {})); (function (ts) { function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { @@ -89104,23 +89855,8 @@ var ts; } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; - return { - // Only return program, all other methods are not implemented - getProgram: function () { return program; }, - getState: ts.notImplemented, - getCompilerOptions: ts.notImplemented, - getSourceFile: ts.notImplemented, - getSourceFiles: ts.notImplemented, - getOptionsDiagnostics: ts.notImplemented, - getGlobalDiagnostics: ts.notImplemented, - getConfigFileParsingDiagnostics: ts.notImplemented, - getSyntacticDiagnostics: ts.notImplemented, - getSemanticDiagnostics: ts.notImplemented, - emit: ts.notImplemented, - getAllDependencies: ts.notImplemented, - getCurrentDirectory: ts.notImplemented - }; + var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics; + return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics); } ts.createAbstractBuilder = createAbstractBuilder; })(ts || (ts = {})); @@ -89924,7 +90660,7 @@ var ts; if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { return; // Don't want to a package to globally import from itself } - var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); if (target === undefined) return; var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); @@ -90299,37 +91035,103 @@ var ts; var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); return { onWatchStatusChange: onWatchStatusChange, - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + watchFile: ts.maybeBind(system, system.watchFile) || (function () { return noopFileWatcher; }), + watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return noopFileWatcher; }), + setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop, + clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop }; } ts.createWatchHost = createWatchHost; + var WatchType; + (function (WatchType) { + WatchType["ConfigFile"] = "Config file"; + WatchType["SourceFile"] = "Source file"; + WatchType["MissingFile"] = "Missing file"; + WatchType["WildcardDirectory"] = "Wild card directory"; + WatchType["FailedLookupLocations"] = "Failed Lookup Locations"; + WatchType["TypeRoots"] = "Type roots"; + })(WatchType = ts.WatchType || (ts.WatchType = {})); + function createWatchFactory(host, options) { + var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop; + var result = ts.getWatchFactory(watchLogLevel, writeLog); + result.writeLog = writeLog; + return result; + } + ts.createWatchFactory = createWatchFactory; + function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) { + if (directoryStructureHost === void 0) { directoryStructureHost = host; } + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); }); + return { + getSourceFile: function (fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, getCompilerOptions().charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + }, + getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); }, + fileExists: function (f) { return host.fileExists(f); }, + readFile: function (f) { return host.readFile(f); }, + trace: ts.maybeBind(host, host.trace), + directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: ts.maybeBind(host, host.realpath), + getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }), + createHash: ts.maybeBind(host, host.createHash), + readDirectory: ts.maybeBind(host, host.readDirectory), + }; + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + if (host.createDirectory) + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ - function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { - if (system === void 0) { system = ts.sys; } - if (!createProgram) { - createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; - } + function createProgramHost(system, createProgram) { + var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); }); var host = system; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) - var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; - var writeFileName = function (s) { return system.write(s + system.newLine); }; - var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getNewLine: function () { return system.newLine; }, - getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, fileExists: function (path) { return system.fileExists(path); }, @@ -90337,29 +91139,31 @@ var ts; directoryExists: function (path) { return system.directoryExists(path); }, getDirectories: function (path) { return system.getDirectories(path); }, readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, - realpath: system.realpath && (function (path) { return system.realpath(path); }), - getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: watchFile, - watchDirectory: watchDirectory, - setTimeout: setTimeout, - clearTimeout: clearTimeout, - trace: function (s) { return system.write(s); }, - onWatchStatusChange: onWatchStatusChange, + realpath: ts.maybeBind(system, system.realpath), + getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable), + trace: function (s) { return system.write(s + system.newLine); }, createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, - createHash: system.createHash && (function (s) { return system.createHash(s); }), - createProgram: createProgram, - afterProgramCreate: emitFilesAndReportErrorUsingBuilder + createHash: ts.maybeBind(system, system.createHash), + createProgram: createProgram }; - function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); - } - function emitFilesAndReportErrorUsingBuilder(builderProgram) { + } + ts.createProgramHost = createProgramHost; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var writeFileName = function (s) { return system.write(s + system.newLine); }; + var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram); + ts.copyProperties(result, createWatchHost(system, reportWatchStatus)); + result.afterProgramCreate = function (builderProgram) { var compilerOptions = builderProgram.getCompilerOptions(); var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); - } + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); + }; + return result; } /** * Report error and exit @@ -90415,8 +91219,6 @@ var ts; var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); var currentDirectory = host.getCurrentDirectory(); - var getCurrentDirectory = function () { return currentDirectory; }; - var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; @@ -90428,15 +91230,7 @@ var ts; host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } var directoryStructureHost = cachedDirectoryStructureHost || host; - var parseConfigFileHost = { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, - fileExists: function (path) { return host.fileExists(path); }, - readFile: readFile, - getCurrentDirectory: getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, - trace: host.trace ? function (s) { return host.trace(s); } : undefined - }; + var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost); // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); if (configFileName && host.configFileParsingResult) { @@ -90450,52 +91244,40 @@ var ts; parseConfigFile(); newLine = updateNewLine(); } - var trace = host.trace && (function (s) { host.trace(s + newLine); }); - var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : - compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; - var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 - var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; + var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); } - var compilerHost = { - // Members for CompilerHost - getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, - getSourceFileByPath: getVersionedSourceFileByPath, - getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), - getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, - writeFile: writeFile, - getCurrentDirectory: getCurrentDirectory, - useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, - getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return newLine; }, - fileExists: fileExists, - readFile: readFile, - trace: trace, - directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), - getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), - realpath: host.realpath && (function (s) { return host.realpath(s); }), - getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), - onReleaseOldSourceFile: onReleaseOldSourceFile, - createHash: host.createHash && (function (data) { return host.createHash(data); }), - // Members for ResolutionCacheHost - toPath: toPath, - getCompilationSettings: function () { return compilerOptions; }, - watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, - watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, - getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, - onInvalidatedResolution: scheduleProgramUpdate, - onChangedAutomaticTypeDirectiveNames: function () { - hasChangedAutomaticTypeDirectiveNames = true; - scheduleProgramUpdate(); - }, - maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, - getCurrentProgram: getCurrentProgram, - writeLog: writeLog, - readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost); + // Members for CompilerHost + var getNewSourceFile = compilerHost.getSourceFile; + compilerHost.getSourceFile = function (fileName) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return getVersionedSourceFileByPath.apply(void 0, [fileName, toPath(fileName)].concat(args)); }; + compilerHost.getSourceFileByPath = getVersionedSourceFileByPath; + compilerHost.getNewLine = function () { return newLine; }; + compilerHost.fileExists = fileExists; + compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + // Members for ResolutionCacheHost + compilerHost.toPath = toPath; + compilerHost.getCompilationSettings = function () { return compilerOptions; }; + compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations" /* FailedLookupLocations */); }; + compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots" /* TypeRoots */); }; + compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; + compilerHost.onInvalidatedResolution = scheduleProgramUpdate; + compilerHost.onChangedAutomaticTypeDirectiveNames = function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }; + compilerHost.maxNumberOfFilesToIterateForInvalidation = host.maxNumberOfFilesToIterateForInvalidation; + compilerHost.getCurrentProgram = getCurrentProgram; + compilerHost.writeLog = writeLog; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -90548,11 +91330,9 @@ var ts; } function createNewProgram(program, hasInvalidatedResolution) { // Compile the program - if (watchLogLevel !== ts.WatchLogLevel.None) { - writeLog("CreatingProgramWith::"); - writeLog(" roots: " + JSON.stringify(rootFileNames)); - writeLog(" options: " + JSON.stringify(compilerOptions)); - } + writeLog("CreatingProgramWith::"); + writeLog(" roots: " + JSON.stringify(rootFileNames)); + writeLog(" options: " + JSON.stringify(compilerOptions)); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -90615,7 +91395,7 @@ var ts; } // Create new source file if requested or the versions dont match if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { - var sourceFile = getNewSourceFile(); + var sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { if (shouldCreateNewSourceFile) { hostSourceFile.version++; @@ -90625,7 +91405,7 @@ var ts; hostSourceFile.sourceFile = sourceFile; sourceFile.version = hostSourceFile.version.toString(); if (!hostSourceFile.fileWatcher) { - hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); } } else { @@ -90639,7 +91419,7 @@ var ts; else { if (sourceFile) { sourceFile.version = initialVersion.toString(); - var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); } else { @@ -90649,21 +91429,6 @@ var ts; return sourceFile; } return hostSourceFile.sourceFile; - function getNewSourceFile() { - var text; - try { - ts.performance.mark("beforeIORead"); - text = host.readFile(fileName, compilerOptions.charset); - ts.performance.mark("afterIORead"); - ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; - } } function nextSourceFileVersion(path) { var hostSourceFile = sourceFilesCache.get(path); @@ -90790,7 +91555,7 @@ var ts; } } function watchMissingFilePath(missingFilePath) { - return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file"); + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file" /* MissingFile */); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -90834,28 +91599,7 @@ var ts; // Schedule Update the program scheduleProgramUpdate(); } - }, flags, "Wild card directories"); - } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - host.createDirectory(directoryPath); - } - } - function writeFile(fileName, text, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } + }, flags, "Wild card directory" /* WildcardDirectory */); } } ts.createWatchProgram = createWatchProgram; @@ -91024,9 +91768,8 @@ var ts; }; } ts.createBuilderStatusReporter = createBuilderStatusReporter; - function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { - if (system === void 0) { system = ts.sys; } - var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) { + var host = ts.createProgramHost(system, createProgram); host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; @@ -91034,21 +91777,18 @@ var ts; host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); return host; } - function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { if (system === void 0) { system = ts.sys; } - var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus); host.reportErrorSummary = reportErrorSummary; return host; } ts.createSolutionBuilderHost = createSolutionBuilderHost; - function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { - var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus); var watchHost = ts.createWatchHost(system, reportWatchStatus); - host.onWatchStatusChange = watchHost.onWatchStatusChange; - host.watchFile = watchHost.watchFile; - host.watchDirectory = watchHost.watchDirectory; - host.setTimeout = watchHost.setTimeout; - host.clearTimeout = watchHost.clearTimeout; + ts.copyProperties(host, watchHost); return host; } ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; @@ -91063,7 +91803,7 @@ var ts; var hostWithWatch = host; var currentDirectory = host.getCurrentDirectory(); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host); // State of the solution var options = defaultOptions; var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); @@ -91075,7 +91815,14 @@ var ts; var missingRoots = ts.createMap(); var globalDependencyGraph; var writeFileName = function (s) { return host.trace && host.trace(s); }; + var readFileWithCache = function (f) { return host.readFile(f); }; + var projectCompilerOptions = baseCompilerOptions; + var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; }); + var originalGetSourceFile = compilerHost.getSourceFile; + var computeHash = host.createHash || ts.generateDjb2Hash; + updateGetSourceFile(); // Watch state + var builderPrograms = createFileMap(toPath); var diagnostics = createFileMap(toPath); var projectPendingBuild = createFileMap(toPath); var projectErrorsReported = createFileMap(toPath); @@ -91083,6 +91830,7 @@ var ts; var nextProjectToBuild = 0; var timerToBuildInvalidatedProject; var reportFileChangeDetected = false; + var _a = ts.createWatchFactory(host, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; // Watches for the solution var allWatchedWildcardDirectories = createFileMap(toPath); var allWatchedInputFiles = createFileMap(toPath); @@ -91123,6 +91871,30 @@ var ts; ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + builderPrograms.clear(); + updateGetSourceFile(); + } + function updateGetSourceFile() { + if (options.watch) { + if (compilerHost.getSourceFile === originalGetSourceFile) { + compilerHost.getSourceFile = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); + if (result && options.watch) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + } + else { + if (compilerHost.getSourceFile !== originalGetSourceFile) { + compilerHost.getSourceFile = originalGetSourceFile; + } + } } function isParsedCommandLine(entry) { return !!entry.options; @@ -91172,36 +91944,34 @@ var ts; } function watchConfigFile(resolved) { if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { - allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + allWatchedConfigFiles.setValue(resolved, watchFile(hostWithWatch, resolved, function () { invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); - })); + }, ts.PollingInterval.High, "Config file" /* ConfigFile */, resolved)); } } function watchWildCardDirectories(resolved, parsed) { if (!options.watch) return; ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { - return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + return watchDirectory(hostWithWatch, dir, function (fileOrDirectory) { var fileOrDirectoryPath = toPath(fileOrDirectory); if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { - // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory); return; } if (isOutputFile(fileOrDirectory, parsed)) { - // writeLog(`${fileOrDirectory} is output file`); + writeLog(fileOrDirectory + " is output file"); return; } invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); - }, !!(flags & 1 /* Recursive */)); + }, flags, "Wild card directory" /* WildcardDirectory */, resolved); }); } function watchInputFiles(resolved, parsed) { if (!options.watch) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { - createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); - }); }, + createNewValue: function (path, input) { return watchFilePath(hostWithWatch, input, function () { return invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, path, "Source file" /* SourceFile */, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -91521,18 +92291,39 @@ var ts; reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); return; } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes) { + // Fake that files have been built by updating output file stamps + updateOutputTimestamps(proj); + return; + } var buildResult = buildSingleProject(resolved); - var dependencyGraph = getGlobalDependencyGraph(); - var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (buildResult & BuildResultFlags.AnyErrors) + return; + var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue; + var referencingProjects = referencingProjectsMap.getValue(resolved); if (!referencingProjects) return; // Always use build order to queue projects - for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { - var project = _a[_i]; + for (var index = buildQueue.indexOf(resolved) + 1; index < buildQueue.length; index++) { + var project = buildQueue[index]; var prepend = referencingProjects.getValue(project); - // If the project is referenced with prepend, always build downstream projectm, - // otherwise queue it only if declaration output changed - if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + if (prepend !== undefined) { + // If the project is referenced with prepend, always build downstream projects, + // If declaration output is changed, build the project + // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps + var status_1 = projectStatus.getValue(project); + if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { + if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) { + projectStatus.setValue(project, { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: status_1.oldestOutputFileName, + newerProjectName: resolved + }); + } + } + else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) { + status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes; + } addProjToQueue(project); } } @@ -91603,98 +92394,118 @@ var ts; // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } - var programOptions = { - projectReferences: configFile.projectReferences, - host: host, - rootNames: configFile.fileNames, - options: configFile.options, - configFileParsingDiagnostics: configFile.errors - }; - if (host.beforeCreateProgram) { - host.beforeCreateProgram(options); - } - var program = ts.createProgram(programOptions); + // TODO: handle resolve module name to cache result in project reference redirect + projectCompilerOptions = configFile.options; + var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences); + projectCompilerOptions = baseCompilerOptions; // Don't emit anything in the presence of syntactic errors or options diagnostics - var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } - // Don't emit .d.ts if there are decl file errors - if (ts.getEmitDeclarations(program.getCompilerOptions())) { - var declDiagnostics = program.getDeclarationDiagnostics(); - if (declDiagnostics.length) { - return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); - } - } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } + // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly + program.backupState(); var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - var emitDiagnostics; - var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; - ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { + var declDiagnostics; + var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; + var outputFiles = []; + ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }); + // Don't emit .d.ts if there are decl file errors + if (declDiagnostics) { + program.restoreState(); + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); + } + // Actual Emit + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emittedOutputs = createFileMap(toPath); + outputFiles.forEach(function (_a) { + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName)) { + if (!anyDtsChanged && isDeclarationFile(name)) { // Check for unchanged .d.ts files - if (host.fileExists(fileName) && host.readFile(fileName) === content) { - priorChangeTime = host.getModifiedTime(fileName); + if (host.fileExists(name) && readFileWithCache(name) === text) { + priorChangeTime = host.getModifiedTime(name); } else { resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + emittedOutputs.setValue(name, true); + ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(name, priorChangeTime); } }); - if (emitDiagnostics) { + var emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); } + // Update time stamps for rest of the outputs + newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(configFile, newestDeclarationFileContentChangedTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); var status = { type: UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime, + oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile) }; diagnostics.removeKey(proj); projectStatus.setValue(proj, status); - if (host.afterProgramEmitAndDiagnostics) { - host.afterProgramEmitAndDiagnostics(program); - } + afterProgramCreate(proj, program); return resultFlags; function buildErrors(diagnostics, errorFlags, errorType) { resultFlags |= errorFlags; reportAndStoreErrors(proj, diagnostics); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); - if (host.afterProgramEmitAndDiagnostics) { - host.afterProgramEmitAndDiagnostics(program); - } + afterProgramCreate(proj, program); return resultFlags; } } + function afterProgramCreate(proj, program) { + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + if (options.watch) { + program.releaseProgram(); + builderPrograms.setValue(proj, program); + } + } function updateOutputTimestamps(proj) { if (options.dry) { return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (options.verbose) { - reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); - } - var now = new Date(); - var outputs = getAllProjectOutputs(proj); - var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { - var file = outputs_2[_i]; - if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); - } - host.setModifiedTime(file, now); - } + var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } + function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { + var outputs = getAllProjectOutputs(proj); + if (!skipOutputs || outputs.length !== skipOutputs.getSize()) { + if (options.verbose) { + reportStatus(verboseMessage, proj.options.configFilePath); + } + var now = host.now ? host.now() : new Date(); + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; + if (skipOutputs && skipOutputs.hasKey(file)) { + continue; + } + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + } + host.setModifiedTime(file, now); + if (proj.options.listEmittedFiles) { + writeFileName("TSFILE: " + file); + } + } + } + return priorNewestUpdateTime; + } function getFilesToClean() { // Get the same graph for cleaning we'd use for building var graph = getGlobalDependencyGraph(); @@ -91739,11 +92550,24 @@ var ts; if (options.watch) { reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); } + // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api + // Override readFile for json files and output .d.ts to cache the text + var savedReadFileWithCache = readFileWithCache; + var savedGetSourceFile = compilerHost.getSourceFile; + var _a = ts.changeCompilerHostLikeToUseCache(host, toPath, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return savedGetSourceFile.call.apply(savedGetSourceFile, [compilerHost].concat(args)); + }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, newReadFileWithCache = _a.readFileWithCache; + readFileWithCache = newReadFileWithCache; + compilerHost.getSourceFile = getSourceFileWithCache; var graph = getGlobalDependencyGraph(); reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; + for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) { + var next = _b[_i]; var proj = parseConfigFile(next); if (proj === undefined) { reportParseConfigFileDiagnostic(next); @@ -91785,6 +92609,13 @@ var ts; anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } reportErrorSummary(); + host.readFile = originalReadFile; + host.fileExists = originalFileExists; + host.directoryExists = originalDirectoryExists; + host.createDirectory = originalCreateDirectory; + host.writeFile = originalWriteFile; + compilerHost.getSourceFile = savedGetSourceFile; + readFileWithCache = savedReadFileWithCache; return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } function reportParseConfigFileDiagnostic(proj) { @@ -91807,7 +92638,7 @@ var ts; } } function relName(path) { - return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode @@ -91840,6 +92671,19 @@ var ts; } } ts.getAllProjectOutputs = getAllProjectOutputs; + function getFirstProjectOutput(project) { + if (project.options.outFile || project.options.out) { + return ts.first(getOutFileOutputs(project)); + } + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + var outputs = getOutputFileNames(inputFile, project); + if (outputs.length) { + return ts.first(outputs); + } + } + return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output"); + } function formatUpToDateStatus(configFileName, status, relName, formatMessage) { switch (status.type) { case UpToDateStatusType.OutOfDateWithSelf: @@ -91892,17 +92736,17 @@ var ts; } ts.inspectValue = inspectValue; function getRecurser() { - var seen = new Set(); + var seen = []; var nameStack = []; return function (obj, name, cbOk, cbFail) { - if (seen.has(obj) || nameStack.length > 4) { - return cbFail(seen.has(obj), nameStack); + if (seen.indexOf(obj) !== -1 || nameStack.length > 4) { + return cbFail(seen.indexOf(obj) !== -1, nameStack); } - seen.add(obj); + seen.push(obj); nameStack.push(name); var res = cbOk(); nameStack.pop(); - seen.delete(obj); + seen.pop(); return res; }; } @@ -91960,8 +92804,8 @@ var ts; return key === "constructor" ? undefined : getValueInfo(key, value, recurser); }); } - var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); - var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + var ignoredProperties = ["arguments", "caller", "constructor", "eval", "super_"]; + var reservedFunctionProperties = Object.getOwnPropertyNames(ts.noop); function getEntriesOfObject(obj) { var seen = ts.createMap(); var entries = []; @@ -91970,8 +92814,8 @@ var ts; for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { var key = _a[_i]; if (!isJsPrivate(key) && - !ignoredProperties.has(key) && - (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + ignoredProperties.indexOf(key) === -1 && + (typeof obj !== "function" || reservedFunctionProperties.indexOf(key) === -1) && // Don't add property from a higher prototype if it already exists in a lower one ts.addToSeen(seen, key)) { var value = safeGetPropertyOfObject(chain, key); @@ -91999,7 +92843,7 @@ var ts; return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; } function isJsPrivate(name) { - return name.startsWith("_"); + return ts.startsWith(name, "_"); } ts.isJsPrivate = isJsPrivate; function tryRequire(fileNameToRequire) { @@ -95784,7 +96628,7 @@ var ts; getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { - if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { + if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); @@ -95984,7 +96828,8 @@ var ts; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + return origin && originIsExport(origin) && ((origin.isDefaultExport && symbol.escapedName === "default" /* Default */) || + (symbol.escapedName === "export=" /* ExportEquals */)) // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) @@ -96554,14 +97399,11 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // For JS, stay on the safe side. - if (isUncheckedFile) - return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. - return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); + if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) + return true; + // If some file is using ES6 modules, assume that it's OK to add more. + return ts.programContainsEs6Modules(program); } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { @@ -97360,7 +98202,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 121 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); + return kind === 121 /* AsyncKeyword */ || kind === 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -98718,8 +99560,8 @@ var ts; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } - function toRenameLocation(entry, originalNode, checker) { - return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker)); + function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText) { + return __assign({}, entryToDocumentSpan(entry), (providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker))); } FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { @@ -99024,12 +99866,12 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol; + var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol; // Compute the meaning from the location and the symbol it references var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); - var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); if (exportSpecifier) { // When renaming at an export specifier, rename the export and not the thing being exported. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); @@ -99039,7 +99881,7 @@ var ts; searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -99072,9 +99914,9 @@ var ts; } } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, useLocalSymbolForExportSpecifier) { var parent = node.parent; - if (ts.isExportSpecifier(parent) && !isForRename) { + if (ts.isExportSpecifier(parent) && useLocalSymbolForExportSpecifier) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); } // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. @@ -99536,6 +100378,7 @@ var ts; getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { + ts.Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled"); var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); @@ -99564,14 +100407,14 @@ var ts; } } // For `export { foo as bar }`, rename `foo`, but not `bar`. - if (!state.options.isForRename || alwaysGetReferences) { + if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) { var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. - if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) { + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (imported) searchForImportedSymbol(imported, state); @@ -99603,7 +100446,7 @@ var ts; return; var symbol = importOrExport.symbol; if (importOrExport.kind === 0 /* Import */) { - if (!state.options.isForRename) { + if (!(isForRenameWithPrefixAndSuffixText(state.options))) { searchForImportedSymbol(symbol, state); } } @@ -99865,6 +100708,9 @@ var ts; }); return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } + function isParameterName(node) { + return node.kind === 72 /* Identifier */ && node.parent.kind === 151 /* Parameter */ && node.parent.name === node; + } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. @@ -99885,7 +100731,7 @@ var ts; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; case 279 /* SourceFile */: - if (ts.isExternalModule(searchSpaceNode)) { + if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) { return undefined; } // falls through @@ -99917,7 +100763,7 @@ var ts; // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; case 279 /* SourceFile */: - return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container); + return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); @@ -99941,13 +100787,13 @@ var ts; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, providePrefixAndSuffixText, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, !(isForRename && providePrefixAndSuffixText), function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, onlyIncludeBindingElementAtReferenceLocation, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { /* Because in short-hand property assignment, location has two meaning : property name and as value of the property @@ -99994,9 +100840,23 @@ var ts; return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. - // Don't do this when populating search set for a rename -- just rename the local. + // Don't do this when populating search set for a rename when prefix and suffix text will be provided -- just rename the local. if (!isForRenamePopulateSearchSymbolSet) { - var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + var bindingElementPropertySymbol = void 0; + if (onlyIncludeBindingElementAtReferenceLocation) { + bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + } + else { + bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); + } + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + ts.Debug.assert(isForRenamePopulateSearchSymbolSet); + // due to the above assert and the arguments at the uses of this function, + // (onlyIncludeBindingElementAtReferenceLocation <=> !providePrefixAndSuffixTextForRename) holds + var includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation; + if (includeOriginalSymbolOfBindingElement) { + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); } function fromRoot(sym, kind) { @@ -100014,10 +100874,17 @@ var ts; : undefined); }); } + function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { + var bindingElement = ts.getDeclarationOfKind(symbol, 186 /* BindingElement */); + if (bindingElement && ts.isObjectBindingElementWithoutPropertyName(bindingElement)) { + return ts.getPropertySymbolFromBindingElement(checker, bindingElement); + } + } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, + /*onlyIncludeBindingElementAtReferenceLocation*/ !state.options.isForRename || !!state.options.providePrefixAndSuffixTextForRename, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, @@ -100102,6 +100969,9 @@ var ts; }); return res.length === 0 ? undefined : res; } + function isForRenameWithPrefixAndSuffixText(options) { + return options.isForRename && options.providePrefixAndSuffixTextForRename; + } })(Core = FindAllReferences.Core || (FindAllReferences.Core = {})); })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -100236,7 +101106,7 @@ var ts; var toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. // TODO:GH#18217 - ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew) : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) @@ -100266,23 +101136,32 @@ var ts; var resolved = host.resolveModuleNames ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); - return getSourceFileToImportFromResolved(resolved, oldToNew, host); + return getSourceFileToImportFromResolved(resolved, oldToNew); } } - function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + function getSourceFileToImportFromResolved(resolved, oldToNew) { // Search through all locations looking for a moved file, and only then test already existing files. // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. - return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); - function tryEach(cb) { - return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + if (!resolved) + return undefined; + // First try resolved module + if (resolved.resolvedModule) { + var result_2 = tryChange(resolved.resolvedModule.resolvedFileName); + if (result_2) + return result_2; } - function tryGetNewFile(oldFileName) { - var newFileName = oldToNew(oldFileName); - return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + // Then failed lookups except package.json since we dont want to touch them (only included ts/js files) + var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson); + if (result) + return result; + // If nothing changed, then result is resolved module file thats not updated + return resolved.resolvedModule && { newFileName: resolved.resolvedModule.resolvedFileName, updated: false }; + function tryChangeWithIgnoringPackageJson(oldFileName) { + return !ts.endsWith(oldFileName, "/package.json") ? tryChange(oldFileName) : undefined; } - function tryGetOldFile(oldFileName) { + function tryChange(oldFileName) { var newFileName = oldToNew(oldFileName); - return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 + return newFileName && { newFileName: newFileName, updated: true }; } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { @@ -101731,7 +102610,7 @@ var ts; else if (ts.isCallExpression(parent)) { var name = getCalledExpressionName(parent.expression); if (name !== undefined) { - var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteralLike(a) ? a.getText(curSourceFile) : undefined; }).join(", "); return name + "(" + args + ") callback"; } } @@ -101784,10 +102663,12 @@ var ts; organizeImportsWorker(topLevelExportDecls, coalesceExports); for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; - var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217 - var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); + if (!ambientModule.body) { + continue; + } + var ambientModuleImportDecls = ambientModule.body.statements.filter(ts.isImportDeclaration); organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); - var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); organizeImportsWorker(ambientModuleExportDecls, coalesceExports); } return changeTracker.getChanges(); @@ -101827,13 +102708,9 @@ var ts; } } OrganizeImports.organizeImports = organizeImports; - function getModuleBlock(moduleDecl) { - var body = moduleDecl.body; - return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; - } function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); - var jsxNamespace = typeChecker.getJsxNamespace(); + var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { @@ -102093,6 +102970,9 @@ var ts; if (ts.isDeclaration(n)) { addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); } + if (isFunctionExpressionAssignedToVariable(n)) { + addOutliningForLeadingCommentsForNode(n.parent.parent.parent, sourceFile, cancellationToken, out); + } var span = getOutliningSpanForNode(n, sourceFile); if (span) out.push(span); @@ -102110,6 +102990,13 @@ var ts; } depthRemaining++; } + function isFunctionExpressionAssignedToVariable(n) { + if (!ts.isFunctionExpression(n) && !ts.isArrowFunction(n)) { + return false; + } + var ancestor = ts.findAncestor(n, ts.isVariableStatement); + return !!ancestor && ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration(ancestor) === n; + } } function addRegionOutliningSpans(sourceFile, out) { var regions = []; @@ -102225,6 +103112,7 @@ var ts; case 245 /* ModuleBlock */: return spanForNode(n.parent); case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: case 241 /* InterfaceDeclaration */: case 243 /* EnumDeclaration */: case 246 /* CaseBlock */: @@ -102253,10 +103141,10 @@ var ts; } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 18 /* OpenBraceToken */; } - // If the block has no leading keywords and is inside an array literal, + // If the block has no leading keywords and is inside an array literal or call expression, // we only want to collapse the span of the block. // Otherwise, the collapsed section will include the end of the previous line. - return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent), open); + return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent) && !ts.isCallExpression(node.parent), open); } function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { if (autoCollapse === void 0) { autoCollapse = false; } @@ -103080,15 +103968,15 @@ var ts; (function (ts) { var Rename; (function (Rename) { - function getRenameInfo(program, sourceFile, position) { + function getRenameInfo(program, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position); var renameInfo = node && nodeIsEligibleForRename(node) - ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }) + ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options) : undefined; return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) { + function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) return; @@ -103105,7 +103993,7 @@ var ts; return undefined; } if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { - return getRenameInfoForModule(node, sourceFile, symbol); + return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 149 /* ComputedPropertyName */) @@ -103122,7 +104010,7 @@ var ts; var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); if (!moduleSourceFile) return undefined; - var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var withoutIndex = ts.endsWith(node.text, "/index") || ts.endsWith(node.text, "/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; @@ -103702,86 +104590,47 @@ var ts; var ts; (function (ts) { var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; - function getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, getProgram) { - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var sourcemappedFileCache; + function getSourceMapper(host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var currentDirectory = host.getCurrentDirectory(); + var sourceFileLike = ts.createMap(); + var documentPositionMappers = ts.createMap(); return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; function toPath(fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } - function scanForSourcemapURL(fileName) { - var mappedFile = sourcemappedFileCache.get(toPath(fileName)); - if (!mappedFile) { - return; + function getDocumentPositionMapper(generatedFileName, sourceFileName) { + var path = toPath(generatedFileName); + var value = documentPositionMappers.get(path); + if (value) + return value; + var mapper; + if (host.getDocumentPositionMapper) { + mapper = host.getDocumentPositionMapper(generatedFileName, sourceFileName); } - return ts.tryGetSourceMappingURL(mappedFile.text, ts.getLineStarts(mappedFile)); - } - function convertDocumentToSourceMapper(file, contents, mapFileName) { - var map = ts.tryParseRawSourceMap(contents); - if (!map || !map.sources || !map.file || !map.mappings) { - // obviously invalid map - return file.sourceMapper = ts.identitySourceMapConsumer; + else if (host.readFile) { + var file = getSourceFileLike(generatedFileName); + mapper = file && ts.getDocumentPositionMapper({ getSourceFileLike: getSourceFileLike, getCanonicalFileName: getCanonicalFileName, log: function (s) { return host.log(s); } }, generatedFileName, ts.getLineInfo(file.text, ts.getLineStarts(file)), function (f) { return !host.fileExists || host.fileExists(f) ? host.readFile(f) : undefined; }); } - var program = getProgram(); - return file.sourceMapper = ts.createDocumentPositionMapper({ - getSourceFileLike: function (s) { - // Lookup file in program, if provided - var file = program && program.getSourceFileByPath(s); - // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file - if (file === undefined || file.resolvedPath !== s) { - // Otherwise check the cache (which may hit disk) - return sourcemappedFileCache.get(s); - } - return file; - }, - getCanonicalFileName: getCanonicalFileName, - log: log, - }, map, mapFileName); - } - function getSourceMapper(fileName, file) { - if (!host.readFile || !host.fileExists) { - return file.sourceMapper = ts.identitySourceMapConsumer; - } - if (file.sourceMapper) { - return file.sourceMapper; - } - var mapFileName = scanForSourcemapURL(fileName); - if (mapFileName) { - var match = base64UrlRegExp.exec(mapFileName); - if (match) { - if (match[1]) { - var base64Object = match[1]; - return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); - } - // Not a data URL we can parse, skip it - mapFileName = undefined; - } - } - var possibleMapLocations = []; - if (mapFileName) { - possibleMapLocations.push(mapFileName); - } - possibleMapLocations.push(fileName + ".map"); - for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { - var location = possibleMapLocations_1[_i]; - var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); - if (host.fileExists(mapPath)) { - return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 - } - } - return file.sourceMapper = ts.identitySourceMapConsumer; + documentPositionMappers.set(path, mapper || ts.identitySourceMapConsumer); + return mapper || ts.identitySourceMapConsumer; } function tryGetSourcePosition(info) { if (!ts.isDeclarationFileName(info.fileName)) return undefined; - var file = getFile(info.fileName); + var file = getSourceFile(info.fileName); if (!file) return undefined; - var newLoc = getSourceMapper(info.fileName, file).getSourcePosition(info); - return newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; + var newLoc = getDocumentPositionMapper(info.fileName).getSourcePosition(info); + return !newLoc || newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; } function tryGetGeneratedPosition(info) { - var program = getProgram(); + if (ts.isDeclarationFileName(info.fileName)) + return undefined; + var sourceFile = getSourceFile(info.fileName); + if (!sourceFile) + return undefined; + var program = host.getProgram(); var options = program.getCompilerOptions(); var outPath = options.outFile || options.out; var declarationPath = outPath ? @@ -103789,49 +104638,96 @@ var ts; ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); if (declarationPath === undefined) return undefined; - var declarationFile = getFile(declarationPath); - if (!declarationFile) - return undefined; - var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + var newLoc = getDocumentPositionMapper(declarationPath, info.fileName).getGeneratedPosition(info); return newLoc === info ? undefined : newLoc; } - function getFile(fileName) { + function getSourceFile(fileName) { + var program = host.getProgram(); + if (!program) + return undefined; var path = toPath(fileName); - var file = getProgram().getSourceFileByPath(path); - if (file && file.resolvedPath === path) { - return file; + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + var file = program.getSourceFileByPath(path); + return file && file.resolvedPath === path ? file : undefined; + } + function getOrCreateSourceFileLike(fileName) { + var path = toPath(fileName); + var fileFromCache = sourceFileLike.get(path); + if (fileFromCache !== undefined) + return fileFromCache ? fileFromCache : undefined; + if (!host.readFile || host.fileExists && !host.fileExists(path)) { + sourceFileLike.set(path, false); + return undefined; } - return sourcemappedFileCache.get(path); + // And failing that, check the disk + var text = host.readFile(path); + var file = text ? createSourceFileLike(text) : false; + sourceFileLike.set(path, file); + return file ? file : undefined; + } + // This can be called from source mapper in either source program or program that includes generated file + function getSourceFileLike(fileName) { + return !host.getSourceFileLike ? + getSourceFile(fileName) || getOrCreateSourceFileLike(fileName) : + host.getSourceFileLike(fileName); } function toLineColumnOffset(fileName, position) { - var file = getFile(fileName); // TODO: GH#18217 + var file = getSourceFileLike(fileName); // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } function clearCache() { - sourcemappedFileCache = createSourceFileLikeCache(host); + sourceFileLike.clear(); + documentPositionMappers.clear(); } } ts.getSourceMapper = getSourceMapper; - function createSourceFileLikeCache(host) { - var cached = ts.createMap(); - return { - get: function (path) { - if (cached.has(path)) { - return cached.get(path); + function getDocumentPositionMapper(host, generatedFileName, generatedFileLineInfo, readMapFile) { + var mapFileName = ts.tryGetSourceMappingURL(generatedFileLineInfo); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(host, ts.base64decode(ts.sys, base64Object), generatedFileName); } - if (!host.fileExists || !host.readFile || !host.fileExists(path)) - return; - // And failing that, check the disk - var text = host.readFile(path); // TODO: GH#18217 - var file = { - text: text, - lineMap: undefined, - getLineAndCharacterOfPosition: function (pos) { - return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); - } - }; - cached.set(path, file); - return file; + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(generatedFileName + ".map"); + var originalMapFileName = mapFileName && ts.getNormalizedAbsolutePath(mapFileName, ts.getDirectoryPath(generatedFileName)); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapFileName_1 = ts.getNormalizedAbsolutePath(location, ts.getDirectoryPath(generatedFileName)); + var mapFileContents = readMapFile(mapFileName_1, originalMapFileName); + if (ts.isString(mapFileContents)) { + return convertDocumentToSourceMapper(host, mapFileContents, mapFileName_1); + } + if (mapFileContents !== undefined) { + return mapFileContents || undefined; + } + } + return undefined; + } + ts.getDocumentPositionMapper = getDocumentPositionMapper; + function convertDocumentToSourceMapper(host, contents, mapFileName) { + var map = ts.tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { + // obviously invalid map + return undefined; + } + return ts.createDocumentPositionMapper(host, map, mapFileName); + } + function createSourceFileLike(text, lineMap) { + return { + text: text, + lineMap: lineMap, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); } }; } @@ -103839,6 +104735,7 @@ var ts; /* @internal */ var ts; (function (ts) { + var visitedNestedConvertibleFunctions = ts.createMap(); function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; @@ -103849,6 +104746,7 @@ var ts; diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } var isJsFile = ts.isSourceFileJS(sourceFile); + visitedNestedConvertibleFunctions.clear(); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -103946,13 +104844,17 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - if (!ts.isAsyncFunction(node) && + // need to check function before checking map so that deeper levels of nested callbacks are checked + if (isConvertibleFunction(node, checker) && !visitedNestedConvertibleFunctions.has(getKeyFromNode(node))) { + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + } + } + function isConvertibleFunction(node, checker) { + return !ts.isAsyncFunction(node) && node.body && ts.isBlock(node.body) && hasReturnStatementWithPromiseHandler(node.body) && - returnsPromise(node, checker)) { - diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); - } + returnsPromise(node, checker); } function returnsPromise(node, checker) { var functionType = checker.getTypeAtLocation(node); @@ -103993,16 +104895,21 @@ var ts; // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts function isFixablePromiseArgument(arg) { switch (arg.kind) { - case 96 /* NullKeyword */: - case 72 /* Identifier */: // identifier includes undefined case 239 /* FunctionDeclaration */: case 196 /* FunctionExpression */: case 197 /* ArrowFunction */: + visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); + /* falls through */ + case 96 /* NullKeyword */: + case 72 /* Identifier */: // identifier includes undefined return true; default: return false; } } + function getKeyFromNode(exp) { + return exp.pos.toString() + ":" + exp.end.toString(); + } })(ts || (ts = {})); /* @internal */ var ts; @@ -106657,10 +107564,7 @@ var ts; * Trimming will be done for lines after the previous range */ function trimTrailingWhitespacesForRemainingRange() { - if (!previousRange) { - return; - } - var startPosition = previousRange.end; + var startPosition = previousRange ? previousRange.end : originalRange.pos; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); @@ -108961,20 +109865,8 @@ var ts; annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } - function isApplicableFunctionForInference(declaration) { - switch (declaration.kind) { - case 239 /* FunctionDeclaration */: - case 156 /* MethodDeclaration */: - case 157 /* Constructor */: - return true; - case 196 /* FunctionExpression */: - var parent = declaration.parent; - return ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) || !!declaration.name; - } - return false; - } function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { - if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + if (!ts.isIdentifier(parameterDeclaration.name)) { return; } var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || @@ -108987,12 +109879,17 @@ var ts; annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } else { + var needParens = ts.isArrowFunction(containingFunction) && !ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(containingFunction.parameters), ts.createToken(20 /* OpenParenToken */)); for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; if (declaration && !declaration.type && !declaration.initializer) { annotate(changes, sourceFile, declaration, type, program, host); } } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(containingFunction.parameters), ts.createToken(21 /* CloseParenToken */)); } } function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { @@ -109113,6 +110010,7 @@ var ts; case 157 /* Constructor */: searchToken = ts.findChildOfKind(containingFunction, 124 /* ConstructorKeyword */, sourceFile); break; + case 197 /* ArrowFunction */: case 196 /* FunctionExpression */: var parent = containingFunction.parent; searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? @@ -110710,11 +111608,10 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var program = context.program, sourceFile = context.sourceFile, span = context.span; + var sourceFile = context.sourceFile, span = context.span; var classDeclaration = getClass(sourceFile, span.start); - var checker = program.getTypeChecker(); return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); }); }, @@ -110726,7 +111623,7 @@ var ts; if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { var implementedTypeNode = _a[_i]; - addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); + addMissingDeclarations(context, implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); } } }); @@ -110738,7 +111635,8 @@ var ts; function symbolPointsToNonPrivateMember(symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); } - function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + function addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + var checker = context.program.getTypeChecker(); var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. @@ -110752,11 +111650,11 @@ var ts; if (!classType.getStringIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); } - codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, context, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); if (indexInfoOfKind) { - changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)); + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration, /*flags*/ undefined, codefix.getNoopSymbolTrackerWithResolver(context))); } } } @@ -111082,7 +111980,7 @@ var ts; var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) - ? checker.getJsxNamespace() + ? checker.getJsxNamespace(sourceFile) : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */); @@ -111630,7 +112528,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { - var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, typeDecl); var containingMethodDeclaration = ts.getAncestor(callExpression, 156 /* MethodDeclaration */); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); @@ -111767,10 +112665,10 @@ var ts; var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); if (!tsconfigObjectLiteral) return undefined; - var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + var compilerOptionsProperty = codefix.findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); if (!compilerOptionsProperty) { var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); - changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, codefix.createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); return defaultTypesDirectoryName; } var compilerOptions = compilerOptionsProperty.initializer; @@ -111782,10 +112680,10 @@ var ts; } var defaultBaseUrl = "."; function makeDefaultBaseUrl() { - return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + return codefix.createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); } function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { - var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + var baseUrlProp = codefix.findJsonProperty(compilerOptions, "baseUrl"); if (baseUrlProp) { return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; } @@ -111796,13 +112694,13 @@ var ts; } var defaultTypesDirectoryName = "types"; function makeDefaultPathMapping() { - return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + return codefix.createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); } function makeDefaultPaths() { - return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + return codefix.createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); } function getOrAddPathMapping(changes, tsconfig, compilerOptions) { - var paths = findProperty(compilerOptions, "paths"); + var paths = codefix.findJsonProperty(compilerOptions, "paths"); if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); return defaultTypesDirectoryName; @@ -111818,12 +112716,6 @@ var ts; changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); return defaultTypesDirectoryName; } - function createJsonPropertyAssignment(name, initializer) { - return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); - } - function findProperty(obj, name) { - return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); - } function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } @@ -111852,9 +112744,9 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var program = context.program, sourceFile = context.sourceFile, span = context.span; + var sourceFile = context.sourceFile, span = context.span; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { - return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, context, t, context.preferences); }); return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; }, @@ -111864,7 +112756,7 @@ var ts; return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var classDeclaration = getClass(diag.file, diag.start); if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { - addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); + addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences); } }); }, @@ -111875,13 +112767,14 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, pos); return ts.cast(token.parent, ts.isClassLike); } - function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { + function addMissingMembers(classDeclaration, sourceFile, context, changeTracker, preferences) { var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration); + var checker = context.program.getTypeChecker(); var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); - codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, context, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files @@ -111980,6 +112873,32 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "enableExperimentalDecorators"; + var errorCodes = [ + ts.Diagnostics.Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning.code + ]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var configFile = context.program.getCompilerOptions().configFile; + if (configFile === undefined) { + return undefined; + } + var changes = ts.textChanges.ChangeTracker.with(context, function (changeTracker) { return makeChange(changeTracker, configFile); }); + return [codefix.createCodeFixActionNoFixId(fixId, changes, ts.Diagnostics.Enable_the_experimentalDecorators_option_in_your_configuration_file)]; + }, + fixIds: [fixId], + }); + function makeChange(changeTracker, configFile) { + codefix.setJsonCompilerOptionValue(changeTracker, configFile, "experimentalDecorators", ts.createTrue()); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -112623,24 +113542,43 @@ var ts; * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. * @returns Empty string iff there are no member insertions. */ - function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, context, preferences, out) { var classMembers = classDeclaration.symbol.members; for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { var symbol = possiblyMissingSymbols_1[_i]; if (!classMembers.has(symbol.escapedName)) { - addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); + addNewNodeForMemberSymbol(symbol, classDeclaration, context, preferences, out); } } } codefix.createMissingMemberNodes = createMissingMemberNodes; + function getModuleSpecifierResolverHost(context) { + return { + directoryExists: context.host.directoryExists ? function (d) { return context.host.directoryExists(d); } : undefined, + fileExists: context.host.fileExists ? function (f) { return context.host.fileExists(f); } : undefined, + getCurrentDirectory: context.host.getCurrentDirectory ? function () { return context.host.getCurrentDirectory(); } : undefined, + readFile: context.host.readFile ? function (f) { return context.host.readFile(f); } : undefined, + useCaseSensitiveFileNames: context.host.useCaseSensitiveFileNames ? function () { return context.host.useCaseSensitiveFileNames(); } : undefined, + getSourceFiles: function () { return context.program.getSourceFiles(); }, + getCommonSourceDirectory: function () { return context.program.getCommonSourceDirectory(); }, + }; + } + function getNoopSymbolTrackerWithResolver(context) { + return { + trackSymbol: ts.noop, + moduleResolverHost: getModuleSpecifierResolverHost(context), + }; + } + codefix.getNoopSymbolTrackerWithResolver = getNoopSymbolTrackerWithResolver; /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, context, preferences, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; } + var checker = context.program.getTypeChecker(); var declaration = declarations[0]; var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); @@ -112652,7 +113590,7 @@ var ts; case 159 /* SetAccessor */: case 153 /* PropertySignature */: case 154 /* PropertyDeclaration */: - var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); + var typeNode = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); out(ts.createProperty( /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); @@ -112692,13 +113630,14 @@ var ts; break; } function outputMethod(signature, modifiers, name, body) { - var method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + var method = signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body); if (method) out(method); } } - function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + function signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body) { + var program = context.program; + var signatureDeclaration = program.getTypeChecker().signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 1 /* NoTruncation */ | 256 /* SuppressAnyReturnType */, getNoopSymbolTrackerWithResolver(context)); if (!signatureDeclaration) { return undefined; } @@ -112709,19 +113648,21 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, contextNode) { + var body = !ts.isInterfaceDeclaration(contextNode); var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); + var tracker = getNoopSymbolTrackerWithResolver(context); var types = ts.map(args, function (arg) { // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, /*flags*/ undefined, tracker); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); var contextualType = checker.getContextualType(call); - var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(120 /* AnyKeyword */); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker) || ts.createKeywordTypeNode(120 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, @@ -112802,6 +113743,38 @@ var ts; } return undefined; } + function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); + if (compilerOptionsProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral([ + createJsonPropertyAssignment(optionName, optionValue), + ]))); + return; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) { + return; + } + var optionProperty = findJsonProperty(compilerOptions, optionName); + if (optionProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); + } + else { + changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + } + } + codefix.setJsonCompilerOptionValue = setJsonCompilerOptionValue; + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + codefix.createJsonPropertyAssignment = createJsonPropertyAssignment; + function findJsonProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + codefix.findJsonProperty = findJsonProperty; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -114094,32 +115067,30 @@ var ts; case 100 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 233 /* LabeledStatement */: - { - var label = node.label; - (seenLabels || (seenLabels = [])).push(label.escapedText); - ts.forEachChild(node, visit); - seenLabels.pop(); - break; - } + case 233 /* LabeledStatement */: { + var label = node.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + ts.forEachChild(node, visit); + seenLabels.pop(); + break; + } case 229 /* BreakStatement */: - case 228 /* ContinueStatement */: - { - var label = node.label; - if (label) { - if (!ts.contains(seenLabels, label.escapedText)) { - // attempts to jump to label that is not in range to be extracted - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); - } + case 228 /* ContinueStatement */: { + var label = node.label; + if (label) { + if (!ts.contains(seenLabels, label.escapedText)) { + // attempts to jump to label that is not in range to be extracted + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); } - else { - if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { - // attempt to break or continue in a forbidden context - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); - } - } - break; } + else { + if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + // attempt to break or continue in a forbidden context + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } case 201 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; @@ -116602,8 +117573,8 @@ var ts; SourceFileObject.prototype.getLineStarts = function () { return ts.getLineStarts(this); }; - SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) { - return ts.getPositionOfLineAndCharacter(this, line, character); + SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character, allowEdits) { + return ts.computePositionOfLineAndCharacter(ts.getLineStarts(this), line, character, this.text, allowEdits); }; SourceFileObject.prototype.getLineEndOfPosition = function (pos) { var line = this.getLineAndCharacterOfPosition(pos).line; @@ -117053,7 +118024,16 @@ var ts; } var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var sourceMapper = ts.getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, function () { return program; }); + var sourceMapper = ts.getSourceMapper({ + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCurrentDirectory: function () { return currentDirectory; }, + getProgram: getProgram, + fileExists: host.fileExists && (function (f) { return host.fileExists(f); }), + readFile: host.readFile && (function (f, encoding) { return host.readFile(f, encoding); }), + getDocumentPositionMapper: host.getDocumentPositionMapper && (function (generatedFileName, sourceFileName) { return host.getDocumentPositionMapper(generatedFileName, sourceFileName); }), + getSourceFileLike: host.getSourceFileLike && (function (f) { return host.getSourceFileLike(f); }), + log: log + }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -117106,15 +118086,7 @@ var ts; writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, fileExists: fileExists, - readFile: function (fileName) { - // stub missing host functionality - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - if (entry) { - return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); - } - return host.readFile && host.readFile(fileName); - }, + readFile: readFile, realpath: host.realpath && (function (path) { return host.realpath(path); }), directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); @@ -117168,6 +118140,15 @@ var ts; !ts.isString(entry) : (!!host.fileExists && host.fileExists(fileName)); } + function readFile(fileName) { + // stub missing host functionality + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache && hostCache.getEntryByPath(path); + if (entry) { + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); + } + return host.readFile && host.readFile(fileName); + } // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { @@ -117379,7 +118360,7 @@ var ts; var sourceFile = getValidSourceFile(fileName); return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } - function findRenameLocations(fileName, position, findInStrings, findInComments) { + function findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, position); @@ -117390,7 +118371,7 @@ var ts; }); } else { - return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, providePrefixAndSuffixTextForRename: providePrefixAndSuffixTextForRename, isForRename: true }, function (entry, originalNode, checker) { return ts.FindAllReferences.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false); }); } } function getReferencesAtPosition(fileName, position) { @@ -117814,9 +118795,9 @@ var ts; return ts.stringContains(path, "/node_modules/"); } } - function getRenameInfo(fileName, position) { + function getRenameInfo(fileName, position, options) { synchronizeHostData(); - return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options); } function getRefactorContext(file, positionOrRange, preferences, formatOptions) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; @@ -119074,13 +120055,13 @@ var ts; var _this = this; return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); }; - LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position, options); }); }; - LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { + LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { var _this = this; - return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ", " + providePrefixAndSuffixTextForRename + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename); }); }; /// GET BRACE MATCHING LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { @@ -119975,6 +120956,15 @@ var ts; server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +(function (ts) { + var WatchType; + (function (WatchType) { + WatchType["ClosedScriptInfo"] = "Closed Script info"; + WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; + WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; + WatchType["MissingSourceMapFile"] = "Missing source map file"; + })(WatchType = ts.WatchType || (ts.WatchType = {})); +})(ts || (ts = {})); var ts; (function (ts) { var server; @@ -120145,11 +121135,20 @@ var ts; TextStorage.prototype.useScriptVersionCache_TestOnly = function () { this.switchToScriptVersionCache(); }; + TextStorage.prototype.resetSourceMapInfo = function () { + this.info.sourceFileLike = undefined; + this.info.closeSourceMapFileWatcher(); + this.info.sourceMapFilePath = undefined; + this.info.declarationInfoPath = undefined; + this.info.sourceInfos = undefined; + this.info.documentPositionMapper = undefined; + }; TextStorage.prototype.useText = function (newText) { this.svc = undefined; this.text = newText; this.lineMap = undefined; this.fileSize = undefined; + this.resetSourceMapInfo(); this.version.text++; }; TextStorage.prototype.edit = function (start, end, newText) { @@ -120158,6 +121157,7 @@ var ts; this.text = undefined; this.lineMap = undefined; this.fileSize = undefined; + this.resetSourceMapInfo(); }; TextStorage.prototype.reload = function (newText) { ts.Debug.assert(newText !== undefined); @@ -120199,8 +121199,8 @@ var ts; ? this.svc.getSnapshot() : ts.ScriptSnapshot.fromString(this.getOrLoadText()); }; - TextStorage.prototype.getLineInfo = function (line) { - return this.switchToScriptVersionCache().getLineInfo(line); + TextStorage.prototype.getAbsolutePositionAndLineText = function (line) { + return this.switchToScriptVersionCache().getAbsolutePositionAndLineText(line); }; TextStorage.prototype.lineToTextSpan = function (line) { if (!this.useScriptVersionCacheIfValidOrOpen()) { @@ -120211,9 +121211,9 @@ var ts; } return this.svc.lineToTextSpan(line); }; - TextStorage.prototype.lineOffsetToPosition = function (line, offset) { + TextStorage.prototype.lineOffsetToPosition = function (line, offset, allowEdits) { if (!this.useScriptVersionCacheIfValidOrOpen()) { - return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text); + return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text, allowEdits); } return this.svc.lineOffsetToPosition(line, offset); }; @@ -120268,6 +121268,17 @@ var ts; ts.Debug.assert(!this.svc, "ScriptVersionCache should not be set"); return this.lineMap || (this.lineMap = ts.computeLineStarts(this.getOrLoadText())); }; + TextStorage.prototype.getLineInfo = function () { + var _this = this; + if (this.svc) { + return { + getLineCount: function () { return _this.svc.getLineCount(); }, + getLineText: function (line) { return _this.svc.getAbsolutePositionAndLineText(line + 1).lineText; } + }; + } + var lineMap = this.getLineMap(); + return ts.getLineInfo(this.text, lineMap); + }; return TextStorage; }()); server.TextStorage = TextStorage; @@ -120476,8 +121487,8 @@ var ts; } return false; }; - ScriptInfo.prototype.getLineInfo = function (line) { - return this.textStorage.getLineInfo(line); + ScriptInfo.prototype.getAbsolutePositionAndLineText = function (line) { + return this.textStorage.getAbsolutePositionAndLineText(line); }; ScriptInfo.prototype.editContent = function (start, end, newText) { this.textStorage.edit(start, end, newText); @@ -120495,8 +121506,8 @@ var ts; ScriptInfo.prototype.lineToTextSpan = function (line) { return this.textStorage.lineToTextSpan(line); }; - ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { - return this.textStorage.lineOffsetToPosition(line, offset); + ScriptInfo.prototype.lineOffsetToPosition = function (line, offset, allowEdits) { + return this.textStorage.lineOffsetToPosition(line, offset, allowEdits); }; ScriptInfo.prototype.positionToLineOffset = function (position) { return this.textStorage.positionToLineOffset(position); @@ -120504,6 +121515,15 @@ var ts; ScriptInfo.prototype.isJavaScript = function () { return this.scriptKind === 1 || this.scriptKind === 2; }; + ScriptInfo.prototype.getLineInfo = function () { + return this.textStorage.getLineInfo(); + }; + ScriptInfo.prototype.closeSourceMapFileWatcher = function () { + if (this.sourceMapFilePath && !ts.isString(this.sourceMapFilePath)) { + ts.closeFileWatcherOf(this.sourceMapFilePath); + this.sourceMapFilePath = undefined; + } + }; return ScriptInfo; }()); server.ScriptInfo = ScriptInfo; @@ -120887,13 +121907,13 @@ var ts; return ts.toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName); }; Project.prototype.watchDirectoryOfFailedLookupLocation = function (directory, cb, flags) { - return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Directory of Failed lookup locations in module resolution", this); + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Failed Lookup Locations", this); }; Project.prototype.onInvalidatedResolution = function () { this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(this); }; Project.prototype.watchTypeRootsDirectory = function (directory, cb, flags) { - return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type root directory", this); + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type roots", this); }; Project.prototype.onChangedAutomaticTypeDirectiveNames = function () { this.hasChangedAutomaticTypeDirectiveNames = true; @@ -120932,6 +121952,12 @@ var ts; Project.prototype.getSourceMapper = function () { return this.getLanguageService().getSourceMapper(); }; + Project.prototype.getDocumentPositionMapper = function (generatedFileName, sourceFileName) { + return this.projectService.getDocumentPositionMapper(this, generatedFileName, sourceFileName); + }; + Project.prototype.getSourceFileLike = function (fileName) { + return this.projectService.getSourceFileLike(fileName, this); + }; Project.prototype.shouldEmitFile = function (scriptInfo) { return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); }; @@ -121142,7 +122168,12 @@ var ts; return false; }; Project.prototype.containsScriptInfo = function (info) { - return this.isRoot(info) || (!!this.program && this.program.getSourceFileByPath(info.path) !== undefined); + if (this.isRoot(info)) + return true; + if (!this.program) + return false; + var file = this.program.getSourceFileByPath(info.path); + return !!file && file.resolvedPath === info.path; }; Project.prototype.containsFile = function (filename, requireOpen) { var info = this.projectService.getScriptInfoForNormalizedPath(filename); @@ -121295,7 +122326,7 @@ var ts; fileWatcher.close(); _this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(_this); } - }, ts.PollingInterval.Medium, "Missing file from program", this); + }, ts.PollingInterval.Medium, "Missing file", this); return fileWatcher; }; Project.prototype.isWatchedMissingFile = function (path) { @@ -121888,17 +122919,6 @@ var ts; } } } - var WatchType; - (function (WatchType) { - WatchType["ConfigFilePath"] = "Config file for the program"; - WatchType["MissingFilePath"] = "Missing file from program"; - WatchType["WildcardDirectories"] = "Wild card directory"; - WatchType["ClosedScriptInfo"] = "Closed Script info"; - WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; - WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; - WatchType["TypeRoots"] = "Type root directory"; - WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; - })(WatchType = server.WatchType || (server.WatchType = {})); var ConfigFileWatcherStatus; (function (ConfigFileWatcherStatus) { ConfigFileWatcherStatus["ReloadingFiles"] = "Reloading configured projects for files"; @@ -122265,9 +123285,37 @@ var ts; else if (!info.isScriptOpen()) { info.delayReloadNonMixedContentFile(); this.delayUpdateProjectGraphs(info.containingProjects); + this.handleSourceMapProjects(info); } } }; + ProjectService.prototype.handleSourceMapProjects = function (info) { + if (info.sourceMapFilePath) { + if (ts.isString(info.sourceMapFilePath)) { + var sourceMapFileInfo = this.getScriptInfoForPath(info.sourceMapFilePath); + this.delayUpdateSourceInfoProjects(sourceMapFileInfo && sourceMapFileInfo.sourceInfos); + } + else { + this.delayUpdateSourceInfoProjects(info.sourceMapFilePath.sourceInfos); + } + } + this.delayUpdateSourceInfoProjects(info.sourceInfos); + if (info.declarationInfoPath) { + this.delayUpdateProjectsOfScriptInfoPath(info.declarationInfoPath); + } + }; + ProjectService.prototype.delayUpdateSourceInfoProjects = function (sourceInfos) { + var _this = this; + if (sourceInfos) { + sourceInfos.forEach(function (_value, path) { return _this.delayUpdateProjectsOfScriptInfoPath(path); }); + } + }; + ProjectService.prototype.delayUpdateProjectsOfScriptInfoPath = function (path) { + var info = this.getScriptInfoForPath(path); + if (info) { + this.delayUpdateProjectGraphs(info.containingProjects); + } + }; ProjectService.prototype.handleDeletedFile = function (info) { this.stopWatchingScriptInfo(info); if (!info.isScriptOpen()) { @@ -122275,6 +123323,14 @@ var ts; var containingProjects = info.containingProjects.slice(); info.detachAllProjects(); this.delayUpdateProjectGraphs(containingProjects); + this.handleSourceMapProjects(info); + info.closeSourceMapFileWatcher(); + if (info.declarationInfoPath) { + var declarationInfo = this.getScriptInfoForPath(info.declarationInfoPath); + if (declarationInfo) { + declarationInfo.sourceMapFilePath = undefined; + } + } } }; ProjectService.prototype.watchWildcardDirectory = function (directory, flags, project) { @@ -122447,7 +123503,7 @@ var ts; ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) { var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); if (configFileExistenceInfo) { - ts.Debug.assert(configFileExistenceInfo.exists); + configFileExistenceInfo.exists = true; if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { var configFileName = project.getConfigFilePath(); configFileExistenceInfo.configFileWatcherForRootOfInferredProject.close(); @@ -122495,7 +123551,7 @@ var ts; watches.push("Config file for the inferred project root"); } if (this.configuredProjects.has(canonicalConfigFilePath)) { - watches.push("Config file for the program"); + watches.push("Config file"); } this.logger.info("ConfigFilePresence:: Current Watches: " + watches + ":: File: " + configFileName + " Currently impacted open files: RootsOfInferredProjects: " + inferredRoots + " OtherOpenFiles: " + otherFiles + " Status: " + status); }; @@ -122745,7 +123801,7 @@ var ts; var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); this.logger.info("Opened configuration file " + configFileName); var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); - project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program", project); + project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file", project); this.configuredProjects.set(project.canonicalConfigFilePath, project); this.setConfigFileExistenceByNewConfiguredProject(project); return project; @@ -122959,7 +124015,7 @@ var ts; var info = this.getScriptInfoForNormalizedPath(path); if (info) return info; - var configProject = this.configuredProjects.get(uncheckedFileName); + var configProject = this.configuredProjects.get(this.toPath(uncheckedFileName)); return configProject && configProject.getCompilerOptions().configFile; }; ProjectService.prototype.logErrorForScriptInfoNotFound = function (fileName) { @@ -123145,6 +124201,119 @@ var ts; ProjectService.prototype.getScriptInfoForPath = function (fileName) { return this.filenameToScriptInfo.get(fileName); }; + ProjectService.prototype.getDocumentPositionMapper = function (project, generatedFileName, sourceFileName) { + var _this = this; + var declarationInfo = this.getOrCreateScriptInfoNotOpenedByClient(generatedFileName, project.currentDirectory, this.host); + if (!declarationInfo) + return undefined; + declarationInfo.getSnapshot(); + if (ts.isString(declarationInfo.sourceMapFilePath)) { + var sourceMapFileInfo_1 = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath); + if (sourceMapFileInfo_1) { + sourceMapFileInfo_1.getSnapshot(); + if (sourceMapFileInfo_1.documentPositionMapper !== undefined) { + sourceMapFileInfo_1.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo_1.sourceInfos); + return sourceMapFileInfo_1.documentPositionMapper ? sourceMapFileInfo_1.documentPositionMapper : undefined; + } + } + declarationInfo.sourceMapFilePath = undefined; + } + else if (declarationInfo.sourceMapFilePath) { + declarationInfo.sourceMapFilePath.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, declarationInfo.sourceMapFilePath.sourceInfos); + return undefined; + } + else if (declarationInfo.sourceMapFilePath !== undefined) { + return undefined; + } + var sourceMapFileInfo; + var mapFileNameFromDeclarationInfo; + var readMapFile = function (mapFileName, mapFileNameFromDts) { + var mapInfo = _this.getOrCreateScriptInfoNotOpenedByClient(mapFileName, project.currentDirectory, _this.host); + if (!mapInfo) { + mapFileNameFromDeclarationInfo = mapFileNameFromDts; + return undefined; + } + sourceMapFileInfo = mapInfo; + var snap = mapInfo.getSnapshot(); + if (mapInfo.documentPositionMapper !== undefined) + return mapInfo.documentPositionMapper; + return snap.getText(0, snap.getLength()); + }; + var projectName = project.projectName; + var documentPositionMapper = ts.getDocumentPositionMapper({ getCanonicalFileName: this.toCanonicalFileName, log: function (s) { return _this.logger.info(s); }, getSourceFileLike: function (f) { return _this.getSourceFileLike(f, projectName, declarationInfo); } }, declarationInfo.fileName, declarationInfo.getLineInfo(), readMapFile); + readMapFile = undefined; + if (sourceMapFileInfo) { + declarationInfo.sourceMapFilePath = sourceMapFileInfo.path; + sourceMapFileInfo.declarationInfoPath = declarationInfo.path; + sourceMapFileInfo.documentPositionMapper = documentPositionMapper || false; + sourceMapFileInfo.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo.sourceInfos); + } + else if (mapFileNameFromDeclarationInfo) { + declarationInfo.sourceMapFilePath = { + watcher: this.addMissingSourceMapFile(project.currentDirectory === this.currentDirectory ? + mapFileNameFromDeclarationInfo : + ts.getNormalizedAbsolutePath(mapFileNameFromDeclarationInfo, project.currentDirectory), declarationInfo.path), + sourceInfos: this.addSourceInfoToSourceMap(sourceFileName, project) + }; + } + else { + declarationInfo.sourceMapFilePath = false; + } + return documentPositionMapper; + }; + ProjectService.prototype.addSourceInfoToSourceMap = function (sourceFileName, project, sourceInfos) { + if (sourceFileName) { + var sourceInfo = this.getOrCreateScriptInfoNotOpenedByClient(sourceFileName, project.currentDirectory, project.directoryStructureHost); + (sourceInfos || (sourceInfos = ts.createMap())).set(sourceInfo.path, true); + } + return sourceInfos; + }; + ProjectService.prototype.addMissingSourceMapFile = function (mapFileName, declarationInfoPath) { + var _this = this; + var fileWatcher = this.watchFactory.watchFile(this.host, mapFileName, function () { + var declarationInfo = _this.getScriptInfoForPath(declarationInfoPath); + if (declarationInfo && declarationInfo.sourceMapFilePath && !ts.isString(declarationInfo.sourceMapFilePath)) { + _this.delayUpdateProjectGraphs(declarationInfo.containingProjects); + _this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos); + declarationInfo.closeSourceMapFileWatcher(); + } + }, ts.PollingInterval.High, "Missing source map file"); + return fileWatcher; + }; + ProjectService.prototype.getSourceFileLike = function (fileName, projectNameOrProject, declarationInfo) { + var project = projectNameOrProject.projectName ? projectNameOrProject : this.findProject(projectNameOrProject); + if (project) { + var path = project.toPath(fileName); + var sourceFile = project.getSourceFile(path); + if (sourceFile && sourceFile.resolvedPath === path) + return sourceFile; + } + var info = this.getOrCreateScriptInfoNotOpenedByClient(fileName, (project || this).currentDirectory, project ? project.directoryStructureHost : this.host); + if (!info) + return undefined; + if (declarationInfo && ts.isString(declarationInfo.sourceMapFilePath) && info !== declarationInfo) { + var sourceMapInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath); + if (sourceMapInfo) { + (sourceMapInfo.sourceInfos || (sourceMapInfo.sourceInfos = ts.createMap())).set(info.path, true); + } + } + if (info.cacheSourceFile) + return info.cacheSourceFile.sourceFile; + if (!info.sourceFileLike) { + info.sourceFileLike = { + get text() { + ts.Debug.fail("shouldnt need text"); + return ""; + }, + getLineAndCharacterOfPosition: function (pos) { + var lineOffset = info.positionToLineOffset(pos); + return { line: lineOffset.line - 1, character: lineOffset.offset - 1 }; + }, + getPositionOfLineAndCharacter: function (line, character, allowEdits) { return info.lineOffsetToPosition(line + 1, character + 1, allowEdits); } + }; + } + return info.sourceFileLike; + }; ProjectService.prototype.setHostConfiguration = function (args) { var _this = this; if (args.file) { @@ -123286,7 +124455,7 @@ var ts; } }; ProjectService.prototype.fileExists = function (fileName) { - return this.filenameToScriptInfo.has(fileName) || this.host.fileExists(fileName); + return !!this.getScriptInfoForNormalizedPath(fileName) || this.host.fileExists(fileName); }; ProjectService.prototype.findExternalProjectContainingOpenScriptInfo = function (info) { return ts.find(this.externalProjects, function (proj) { @@ -123295,7 +124464,6 @@ var ts; }); }; ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { - var _this = this; var configFileName; var configFileErrors; var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); @@ -123332,12 +124500,7 @@ var ts; this.removeProject(inferredProject); } } - this.filenameToScriptInfo.forEach(function (info) { - if (!info.isScriptOpen() && info.isOrphan()) { - _this.stopWatchingScriptInfo(info); - _this.deleteScriptInfo(info); - } - }); + this.removeOrphanScriptInfos(); this.printProjects(); this.telemetryOnOpenFile(info); return { configFileName: configFileName, configFileErrors: configFileErrors }; @@ -123370,11 +124533,61 @@ var ts; } } }; + ProjectService.prototype.removeOrphanScriptInfos = function () { + var _this = this; + var toRemoveScriptInfos = ts.cloneMap(this.filenameToScriptInfo); + this.filenameToScriptInfo.forEach(function (info) { + if (!info.isScriptOpen() && info.isOrphan()) { + if (!info.sourceMapFilePath) + return; + var sourceInfos = void 0; + if (ts.isString(info.sourceMapFilePath)) { + var sourceMapInfo = _this.getScriptInfoForPath(info.sourceMapFilePath); + sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos; + } + else { + sourceInfos = info.sourceMapFilePath.sourceInfos; + } + if (!sourceInfos) + return; + if (!ts.forEachKey(sourceInfos, function (path) { + var info = _this.getScriptInfoForPath(path); + return !!info && (info.isScriptOpen() || !info.isOrphan()); + })) { + return; + } + } + toRemoveScriptInfos.delete(info.path); + if (info.sourceMapFilePath) { + var sourceInfos = void 0; + if (ts.isString(info.sourceMapFilePath)) { + toRemoveScriptInfos.delete(info.sourceMapFilePath); + var sourceMapInfo = _this.getScriptInfoForPath(info.sourceMapFilePath); + sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos; + } + else { + sourceInfos = info.sourceMapFilePath.sourceInfos; + } + if (sourceInfos) { + sourceInfos.forEach(function (_value, path) { return toRemoveScriptInfos.delete(path); }); + } + } + }); + toRemoveScriptInfos.forEach(function (info) { + _this.stopWatchingScriptInfo(info); + _this.deleteScriptInfo(info); + info.closeSourceMapFileWatcher(); + }); + }; ProjectService.prototype.telemetryOnOpenFile = function (scriptInfo) { if (this.syntaxOnly || !this.eventHandler || !scriptInfo.isJavaScript() || !ts.addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) { return; } - var info = { checkJs: !!scriptInfo.getDefaultProject().getSourceFile(scriptInfo.path).checkJsDirective }; + var project = scriptInfo.getDefaultProject(); + if (!project.languageServiceEnabled) { + return; + } + var info = { checkJs: !!project.getSourceFile(scriptInfo.path).checkJsDirective }; this.eventHandler({ eventName: server.OpenFileInfoTelemetryEvent, data: { info: info } }); }; ProjectService.prototype.closeClientFile = function (uncheckedFileName) { @@ -123920,11 +125133,11 @@ var ts; }, undefined); return outputs; } - function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments) { + function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments, hostPreferences) { var outputs = []; combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, tryAddToTodo) { var project = _a.project, location = _a.location; - for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments) || server.emptyArray; _i < _b.length; _i++) { + for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments, hostPreferences.providePrefixAndSuffixTextForRename) || server.emptyArray; _i < _b.length; _i++) { var output = _b[_i]; if (!ts.contains(outputs, output, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { outputs.push(output); @@ -124895,7 +126108,8 @@ var ts; Session.prototype.getRenameInfo = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); - return project.getLanguageService().getRenameInfo(file, position); + var preferences = this.getHostPreferences(); + return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: preferences.allowRenameOfImportPath }); }; Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) { var projects; @@ -124940,11 +126154,11 @@ var ts; var file = server.toNormalizedPath(args.file); var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); - var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments); + var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getHostPreferences()); if (!simplifiedResult) return locations; var defaultProject = this.getDefaultProject(args); - var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getHostPreferences().allowRenameOfImportPath }), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); return { info: renameInfo, locs: this.toSpanGroups(locations) }; }; Session.prototype.mapRenameInfo = function (info, scriptInfo) { @@ -125142,7 +126356,7 @@ var ts; var formatOptions = this.getFormatOptions(file); var edits = languageService.getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { - var _b = scriptInfo.getLineInfo(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition; + var _b = scriptInfo.getAbsolutePositionAndLineText(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition; if (lineText && lineText.search("\\S") < 0) { var preferredIndent = languageService.getIndentationAtPosition(file, position, formatOptions); var hasIndent = 0; @@ -126031,8 +127245,8 @@ var ts; ScriptVersionCache.prototype.getSnapshotVersion = function () { return this._getSnapshot().version; }; - ScriptVersionCache.prototype.getLineInfo = function (line) { - return this._getSnapshot().index.lineNumberToInfo(line); + ScriptVersionCache.prototype.getAbsolutePositionAndLineText = function (oneBasedLine) { + return this._getSnapshot().index.lineNumberToInfo(oneBasedLine); }; ScriptVersionCache.prototype.lineOffsetToPosition = function (line, column) { return this._getSnapshot().index.absolutePositionOfStartOfLine(line) + (column - 1); @@ -126067,6 +127281,9 @@ var ts; return ts.unchangedTextChangeRange; } }; + ScriptVersionCache.prototype.getLineCount = function () { + return this._getSnapshot().index.getLineCount(); + }; ScriptVersionCache.fromString = function (script) { var svc = new ScriptVersionCache(); var snap = new LineIndexSnapshot(0, svc, new LineIndex()); @@ -126121,8 +127338,11 @@ var ts; LineIndex.prototype.positionToColumnAndLineText = function (position) { return this.root.charOffsetToLineInfo(1, position); }; + LineIndex.prototype.getLineCount = function () { + return this.root.lineCount(); + }; LineIndex.prototype.lineNumberToInfo = function (oneBasedLine) { - var lineCount = this.root.lineCount(); + var lineCount = this.getLineCount(); if (oneBasedLine <= lineCount) { var _a = this.root.lineNumberToInfo(oneBasedLine, 0), position = _a.position, leaf = _a.leaf; return { absolutePosition: position, lineText: leaf && leaf.text }; @@ -126780,76 +128000,71 @@ var ts; this.inspectValuePromise.resolve(response.result); this.inspectValuePromise = undefined; break; - case server.EventInitializationFailed: - { - var body = { - message: response.message - }; - var eventName = "typesInstallerInitializationFailed"; - this.event(body, eventName); - break; - } - case server.EventBeginInstallTypes: - { - var body = { - eventId: response.eventId, - packages: response.packagesToInstall, - }; - var eventName = "beginInstallTypes"; - this.event(body, eventName); - break; - } - case server.EventEndInstallTypes: - { - if (this.telemetryEnabled) { - var body_1 = { - telemetryEventName: "typingsInstalled", - payload: { - installedPackages: response.packagesToInstall.join(","), - installSuccess: response.installSuccess, - typingsInstallerVersion: response.typingsInstallerVersion - } - }; - var eventName_1 = "telemetry"; - this.event(body_1, eventName_1); - } - var body = { - eventId: response.eventId, - packages: response.packagesToInstall, - success: response.installSuccess, - }; - var eventName = "endInstallTypes"; - this.event(body, eventName); - break; - } - case server.ActionInvalidate: - { - this.projectService.updateTypingsForProject(response); - break; - } - case server.ActionSet: - { - if (this.activeRequestCount > 0) { - this.activeRequestCount--; - } - else { - ts.Debug.fail("Received too many responses"); - } - while (this.requestQueue.length > 0) { - var queuedRequest = this.requestQueue.shift(); - if (this.requestMap.get(queuedRequest.operationId) === queuedRequest) { - this.requestMap.delete(queuedRequest.operationId); - this.scheduleRequest(queuedRequest); - break; + case server.EventInitializationFailed: { + var body = { + message: response.message + }; + var eventName = "typesInstallerInitializationFailed"; + this.event(body, eventName); + break; + } + case server.EventBeginInstallTypes: { + var body = { + eventId: response.eventId, + packages: response.packagesToInstall, + }; + var eventName = "beginInstallTypes"; + this.event(body, eventName); + break; + } + case server.EventEndInstallTypes: { + if (this.telemetryEnabled) { + var body_1 = { + telemetryEventName: "typingsInstalled", + payload: { + installedPackages: response.packagesToInstall.join(","), + installSuccess: response.installSuccess, + typingsInstallerVersion: response.typingsInstallerVersion } - if (this.logger.hasLevel(server.LogLevel.verbose)) { - this.logger.info("Skipping defunct request for: " + queuedRequest.operationId); - } - } - this.projectService.updateTypingsForProject(response); - this.event(response, "setTypings"); - break; + }; + var eventName_1 = "telemetry"; + this.event(body_1, eventName_1); } + var body = { + eventId: response.eventId, + packages: response.packagesToInstall, + success: response.installSuccess, + }; + var eventName = "endInstallTypes"; + this.event(body, eventName); + break; + } + case server.ActionInvalidate: { + this.projectService.updateTypingsForProject(response); + break; + } + case server.ActionSet: { + if (this.activeRequestCount > 0) { + this.activeRequestCount--; + } + else { + ts.Debug.fail("Received too many responses"); + } + while (this.requestQueue.length > 0) { + var queuedRequest = this.requestQueue.shift(); + if (this.requestMap.get(queuedRequest.operationId) === queuedRequest) { + this.requestMap.delete(queuedRequest.operationId); + this.scheduleRequest(queuedRequest); + break; + } + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Skipping defunct request for: " + queuedRequest.operationId); + } + } + this.projectService.updateTypingsForProject(response); + this.event(response, "setTypings"); + break; + } default: ts.assertType(response); } diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 2b78178587e..383ca7536f4 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -1778,7 +1778,7 @@ declare namespace ts { type ResolvedConfigFileName = string & { _isResolvedConfigFileName: never; }; - type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles?: ReadonlyArray) => void; + type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: ReadonlyArray) => void; class OperationCanceledException { } interface CancellationToken { @@ -2689,7 +2689,6 @@ declare namespace ts { getDefaultLibLocation?(): string; writeFile: WriteFileCallback; getCurrentDirectory(): string; - getDirectories(path: string): string[]; getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; @@ -3013,6 +3012,7 @@ declare namespace ts { /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; readonly allowTextChangesInNewFiles?: boolean; + readonly providePrefixAndSuffixTextForRename?: boolean; } /** Represents a bigint literal value without requiring bigint support */ interface PseudoBigInt { @@ -4278,6 +4278,10 @@ declare namespace ts { * Get the syntax diagnostics, for all source files if source file is not supplied */ getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the declaration diagnostics, for all source files if source file is not supplied + */ + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; /** * Get all the dependencies of the file */ @@ -4364,13 +4368,11 @@ declare namespace ts { /** If provided, will be used to reset existing delayed compilation */ clearTimeout?(timeoutId: any): void; } - interface WatchCompilerHost extends WatchHost { + interface ProgramHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; - /** If provided, callback to invoke after every new program creation */ - afterProgramCreate?(program: T): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4404,6 +4406,10 @@ declare namespace ts { /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; } + interface WatchCompilerHost extends ProgramHost, WatchHost { + /** If provided, callback to invoke after every new program creation */ + afterProgramCreate?(program: T): void; + } /** * Host to create watch with root files and options */ @@ -4706,8 +4712,8 @@ declare namespace ts { getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; - getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReadonlyArray | undefined; + getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): RenameInfo; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): ReadonlyArray | undefined; getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; @@ -5150,6 +5156,9 @@ declare namespace ts { canRename: false; localizedErrorMessage: string; } + interface RenameInfoOptions { + readonly allowRenameOfImportPath?: boolean; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; @@ -7923,6 +7932,8 @@ declare namespace ts.server.protocol { readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; readonly lazyConfiguredProjectsFromExternalProject?: boolean; + readonly allowRenameOfImportPath?: boolean; + readonly providePrefixAndSuffixTextForRename?: boolean; } interface CompilerOptions { allowJs?: boolean; @@ -8497,10 +8508,6 @@ declare namespace ts.server { syntaxOnly?: boolean; } class ProjectService { - /** - * Container of all known scripts - */ - private readonly filenameToScriptInfo; private readonly scriptInfoInNodeModulesWatchers; /** * Contains all the deleted script info's version information so that @@ -8599,6 +8606,9 @@ declare namespace ts.server { getHostFormatCodeOptions(): FormatCodeSettings; getHostPreferences(): protocol.UserPreferences; private onSourceFileChanged; + private handleSourceMapProjects; + private delayUpdateSourceInfoProjects; + private delayUpdateProjectsOfScriptInfoPath; private handleDeletedFile; private onConfigChangedForConfiguredProject; /** @@ -8689,6 +8699,8 @@ declare namespace ts.server { */ getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo | undefined; getScriptInfoForPath(fileName: Path): ScriptInfo | undefined; + private addSourceInfoToSourceMap; + private addMissingSourceMapFile; setHostConfiguration(args: protocol.ConfigureRequestArguments): void; closeLog(): void; /** @@ -8726,6 +8738,7 @@ declare namespace ts.server { private findExternalProjectContainingOpenScriptInfo; openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; private removeOrphanConfiguredProjects; + private removeOrphanScriptInfos; private telemetryOnOpenFile; /** * Close file whose contents is managed by the client diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index d89c5621ef6..24e254e580c 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -84,7 +84,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = ts.versionMajorMinor + ".0-rc"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -1276,6 +1276,18 @@ var ts; return result; } ts.extend = extend; + function copyProperties(first, second) { + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + first[id] = second[id]; + } + } + } + ts.copyProperties = copyProperties; + function maybeBind(obj, fn) { + return fn ? fn.bind(obj) : undefined; + } + ts.maybeBind = maybeBind; function createMultiMap() { var map = createMap(); map.add = multiMapAdd; @@ -1994,7 +2006,11 @@ var ts; } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; function fill(length, cb) { - return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + var result = Array(length); + for (var i = 0; i < length; i++) { + result[i] = cb(i); + } + return result; } ts.fill = fill; })(ts || (ts = {})); @@ -3251,15 +3267,17 @@ var ts; CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; - CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; - CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; - CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; - CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; - CheckFlags[CheckFlags["Late"] = 1024] = "Late"; - CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter"; - CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter"; + CheckFlags[CheckFlags["HasLiteralType"] = 64] = "HasLiteralType"; + CheckFlags[CheckFlags["ContainsPublic"] = 128] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 256] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 512] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 1024] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 2048] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 4096] = "ReverseMapped"; + CheckFlags[CheckFlags["OptionalParameter"] = 8192] = "OptionalParameter"; + CheckFlags[CheckFlags["RestParameter"] = 16384] = "RestParameter"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + CheckFlags[CheckFlags["Discriminant"] = 96] = "Discriminant"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; (function (InternalSymbolName) { @@ -4011,6 +4029,16 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + /* @internal */ + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + ts.generateDjb2Hash = generateDjb2Hash; /** * Set a high stack trace limit to provide more information in case of an error. * Called for command-line and server use cases. @@ -4887,14 +4915,6 @@ var ts; return; } } - /** - * djb2 hashing algorithm - * http://www.cse.yorku.ca/~oz/hash.html - */ - function generateDjb2Hash(data) { - var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); - return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); - } function createMD5HashUsingNativeCrypto(data) { var hash = _crypto.createHash("md5"); hash.update(data); @@ -5248,6 +5268,9 @@ var ts; Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), + An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."), + A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."), + A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5403,8 +5426,6 @@ var ts; Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), - Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), - Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), @@ -5418,7 +5439,7 @@ var ts; A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), - In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values: diag(2474, ts.DiagnosticCategory.Error, "const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values_2474", "const enum member initializers can only contain literal values and other computed enum values."), 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: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'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."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), @@ -5434,11 +5455,11 @@ var ts; The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), - Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Tuple_type_0_of_length_1_has_no_element_at_index_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493", "Tuple type '{0}' of length '{1}' has no element at index '{2}'."), Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), - Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export: diag(2497, ts.DiagnosticCategory.Error, "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497", "This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export."), Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), @@ -5627,6 +5648,11 @@ var ts; Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), + No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments: diag(2743, ts.DiagnosticCategory.Error, "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743", "No overload expects {0} type arguments, but overloads do exist that expect either {1} or {2} type arguments."), + Type_parameter_defaults_can_only_reference_previously_declared_type_parameters: diag(2744, ts.DiagnosticCategory.Error, "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744", "Type parameter defaults can only reference previously declared type parameters."), + This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."), + This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."), + _0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5976,6 +6002,7 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -6054,6 +6081,7 @@ var ts; JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), + Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -6190,6 +6218,7 @@ var ts; Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), + Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"), }; })(ts || (ts = {})); var ts; @@ -6414,16 +6443,13 @@ var ts; return result; } ts.computeLineStarts = computeLineStarts; - function getPositionOfLineAndCharacter(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); + function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) { + return sourceFile.getPositionOfLineAndCharacter ? + sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) : + computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; /* @internal */ - function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); - } - ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; - /* @internal */ function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { if (line < 0 || line >= lineStarts.length) { if (allowEdits) { @@ -6999,6 +7025,7 @@ var ts; result = text.substring(start, end); // No need to use all the fragments; no _ removal needed } if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */)); return { type: 8 /* NumericLiteral */, value: "" + +result // if value is not an integer, it can be safely coerced to a number @@ -7007,9 +7034,29 @@ var ts; else { tokenValue = result; var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + checkForIdentifierStartAfterNumericLiteral(start); return { type: type, value: tokenValue }; } } + function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { + if (!isIdentifierStart(text.charCodeAt(pos), languageVersion)) { + return; + } + var identifierStart = pos; + var length = scanIdentifierParts().length; + if (length === 1 && text[identifierStart] === "n") { + if (isScientific) { + error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1); + } + else { + error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1); + } + } + else { + error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length); + pos = identifierStart; + } + } function scanOctalDigits() { var start = pos; while (isOctalDigit(text.charCodeAt(pos))) { @@ -8918,7 +8965,7 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, node.pos); } var isMissing = nodeIsMissing(errorNode); - var pos = isMissing + var pos = isMissing || ts.isJsxText(node) ? errorNode.pos : ts.skipTrivia(sourceFile.text, errorNode.pos); // These asserts should all be satisfied for a properly constructed `errorNode`. @@ -10113,6 +10160,7 @@ var ts; return node.initializer; } } + ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration; function getSingleVariableOfVariableStatement(node) { return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } @@ -12151,10 +12199,10 @@ var ts; } if (getCheckFlags(s) & 6 /* Synthetic */) { var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : - checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + var accessModifier = checkFlags & 512 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 128 /* ContainsPublic */ ? 4 /* Public */ : 16 /* Protected */; - var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + var staticModifier = checkFlags & 1024 /* ContainsStatic */ ? 32 /* Static */ : 0; return accessModifier | staticModifier; } if (s.flags & 4194304 /* Prototype */) { @@ -12401,6 +12449,10 @@ var ts; || kind === 290 /* JSDocVariadicType */; } ts.isTypeNodeKind = isTypeNodeKind; + function isAccessExpression(node) { + return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */; + } + ts.isAccessExpression = isAccessExpression; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -15279,6 +15331,8 @@ var ts; return path; } ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; function comparePathsWorker(a, b, componentComparer) { if (a === b) return 0 /* EqualTo */; @@ -15286,14 +15340,30 @@ var ts; return -1 /* LessThan */; if (b === undefined) return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, ts.getRootLength(a)); + var bRoot = b.substring(0, ts.getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var 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. var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 0; i < sharedLength; i++) { - var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; - var result = stringComparer(aComponents[i], bComponents[i]); - if (result !== 0 /* EqualTo */) { - return result; + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; } } return ts.compareValues(aComponents.length, bComponents.length); @@ -16785,15 +16855,15 @@ var ts; if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6 /* JSON */) { - var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); - result_1.referencedFiles = ts.emptyArray; - result_1.typeReferenceDirectives = ts.emptyArray; - result_1.libReferenceDirectives = ts.emptyArray; - result_1.amdDependencies = ts.emptyArray; - result_1.hasNoDefaultLib = false; - result_1.pragmas = ts.emptyMap; - return result_1; + var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_2.referencedFiles = ts.emptyArray; + result_2.typeReferenceDirectives = ts.emptyArray; + result_2.libReferenceDirectives = ts.emptyArray; + result_2.amdDependencies = ts.emptyArray; + result_2.hasNoDefaultLib = false; + result_2.pragmas = ts.emptyMap; + return result_2; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); @@ -17672,6 +17742,8 @@ var ts; return parseElement(); } function currentNode(parsingContext) { + // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse. + // // If there is an outstanding parse error that we've encountered, but not attached to // some node, then we cannot get a node from the old source tree. This is because we // want to mark the next node we encounter as being unusable. @@ -17679,25 +17751,15 @@ var ts; // Note: This may be too conservative. Perhaps we could reuse the node and set the bit // on it (or its leftmost child) as having the error. For now though, being conservative // is nice and likely won't ever affect perf. - if (parseErrorBeforeNextFinishedNode) { - return undefined; - } - if (!syntaxCursor) { - // if we don't have a cursor, we could never return a node from the old tree. + if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } var node = syntaxCursor.currentNode(scanner.getStartPos()); // Can't reuse a missing node. - if (ts.nodeIsMissing(node)) { - return undefined; - } // Can't reuse a node that intersected the change range. - if (node.intersectsChange) { - return undefined; - } // Can't reuse a node that contains a parse error. This is necessary so that we // produce the same set of errors again. - if (ts.containsParseError(node)) { + if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) { return undefined; } // We can only reuse a node if it was parsed under the same strict mode that we're @@ -17732,6 +17794,22 @@ var ts; nextToken(); return node; } + function isReusableParsingContext(parsingContext) { + switch (parsingContext) { + case 5 /* ClassMembers */: + case 2 /* SwitchClauses */: + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + case 6 /* EnumMembers */: + case 4 /* TypeMembers */: + case 8 /* VariableDeclarations */: + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + return true; + } + return false; + } function canReuseNode(node, parsingContext) { switch (parsingContext) { case 5 /* ClassMembers */: @@ -17751,22 +17829,20 @@ var ts; case 17 /* JSDocParameters */: case 16 /* Parameters */: return isReusableParameter(node); - case 18 /* RestProperties */: - return false; // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the // parser reached while looking ahead might be in the edited range (see the example // in canReuseVariableDeclaratorNode for a good case of this). - case 22 /* HeritageClauses */: + // case ParsingContext.HeritageClauses: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 19 /* TypeParameters */: + // case ParsingContext.TypeParameters: // This would probably be safe to reuse. There is no speculative parsing with // type parameters. Note that that's because type *parameters* only occur in // unambiguous *type* contexts. While type *arguments* occur in very ambiguous // *expression* contexts. - case 21 /* TupleElementTypes */: + // case ParsingContext.TupleElementTypes: // This would probably be safe to reuse. There is no speculative parsing with // tuple types. // Technically, type argument list types are probably safe to reuse. While @@ -17774,24 +17850,24 @@ var ts; // produced from speculative parsing a < as a type argument list), we only have // the types because speculative parsing succeeded. Thus, the lookahead never // went past the end of the list and rewound. - case 20 /* TypeArguments */: + // case ParsingContext.TypeArguments: // Note: these are almost certainly not safe to ever reuse. Expressions commonly // need a large amount of lookahead, and we should not reuse them as they may // have actually intersected the edit. - case 11 /* ArgumentExpressions */: + // case ParsingContext.ArgumentExpressions: // This is not safe to reuse for the same reason as the 'AssignmentExpression' // cases. i.e. a property assignment may end with an expression, and thus might // have lookahead far beyond it's old node. - case 12 /* ObjectLiteralMembers */: + // case ParsingContext.ObjectLiteralMembers: // This is probably not safe to reuse. There can be speculative parsing with // type names in a heritage clause. There can be generic names in the type // name list, and there can be left hand side expressions (which can have type // arguments.) - case 7 /* HeritageClauseElement */: + // case ParsingContext.HeritageClauseElement: // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes // on any given element. Same for children. - case 13 /* JsxAttributes */: - case 14 /* JsxChildren */: + // case ParsingContext.JsxAttributes: + // case ParsingContext.JsxChildren: } return false; } @@ -23021,17 +23097,18 @@ var ts; var libReferenceDirectives_1 = context.libReferenceDirectives; ts.forEach(ts.toArray(entryOrList), function (arg) { // TODO: GH#18217 + var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path; if (arg.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; } - else if (arg.arguments.types) { - typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + else if (types) { + typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value }); } - else if (arg.arguments.lib) { - libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + else if (lib) { + libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value }); } - else if (arg.arguments.path) { - referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + else if (path) { + referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value }); } else { reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); @@ -24703,12 +24780,12 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, !configParseResult.configFileSpecs ? function (_) { return false; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); - }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), exclude: configParseResult.configFileSpecs.validatedExcludeSpecs } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); @@ -24726,23 +24803,23 @@ var ts; } function matchesSpecs(path, includeSpecs, excludeSpecs) { if (!includeSpecs) - return function (_) { return false; }; + return function (_) { return true; }; var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { - return function (path) { return includeRe.test(path) && !excludeRe.test(path); }; + return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; } - return function (path) { return includeRe.test(path); }; + return function (path) { return !includeRe.test(path); }; } if (excludeRe) { - return function (path) { return !excludeRe.test(path); }; + return function (path) { return excludeRe.test(path); }; } - return function (_) { return false; }; + return function (_) { return true; }; } function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") { // this is of a type CommandLineOptionOfPrimitiveType return undefined; } @@ -24899,7 +24976,7 @@ var ts; result.push(tab + "}"); } result.push("}"); - return result.join(newLine); + return result.join(newLine) + newLine; } } ts.generateTSConfig = generateTSConfig; @@ -27184,6 +27261,10 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } + // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate) + if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) { + symbol.constEnumOnlyModule = false; + } if (symbolFlags & 67220415 /* Value */) { setValueDeclaration(symbol, node); } @@ -27672,7 +27753,7 @@ var ts; } function isNarrowableReference(expr) { return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || - ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || ts.isElementAccessExpression(expr) && expr.argumentExpression && (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && isNarrowableReference(expr.expression); @@ -31116,10 +31197,10 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(262144 /* TypeParameter */); - var markerSubType = createType(262144 /* TypeParameter */); + var markerSuperType = createTypeParameter(); + var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(262144 /* TypeParameter */); + var markerOtherType = createTypeParameter(); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); @@ -31309,7 +31390,6 @@ var ts; var _jsxFactoryEntity; var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); - var definitelyAssignableRelation = ts.createMap(); var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); @@ -32027,13 +32107,18 @@ var ts; } } break; + case 197 /* ArrowFunction */: + // when targeting ES6 or higher there is no 'arguments' in an arrow function + // for lower compile targets the resolved symbol is used to emit an error + if (compilerOptions.target >= 2 /* ES2015 */) { + break; + } + // falls through case 156 /* MethodDeclaration */: - case 155 /* MethodSignature */: case 157 /* Constructor */: case 158 /* GetAccessor */: case 159 /* SetAccessor */: case 239 /* FunctionDeclaration */: - case 197 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -32089,7 +32174,7 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol) && !isInTypeQuery(originalLocation)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { result.isReferenced |= meaning; } if (!result) { @@ -32167,7 +32252,8 @@ var ts; } // If we're in an external module, we can't reference value symbols created from UMD export declarations if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { - if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { + var merged = getMergedSymbol(result); + if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } @@ -32927,7 +33013,10 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { - error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 + ? "allowSyntheticDefaultImports" + : "esModuleInterop"; + error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); return symbol; } if (compilerOptions.esModuleInterop) { @@ -33222,6 +33311,12 @@ var ts; function createTypeofType() { return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); } + function createTypeParameter(symbol) { + var type = createType(262144 /* TypeParameter */); + if (symbol) + type.symbol = symbol; + return type; + } // A reserved member name starts with two underscores, but the third character cannot be an underscore // or the @ symbol. A third underscore indicates an escaped form of an identifer that started // with at least two underscores. The @ character indicates that the name is denoted by a well known ES @@ -34175,12 +34270,12 @@ var ts; return ts.createKeywordTypeNode(120 /* AnyKeyword */); } function addPropertyToElementList(propertySymbol, context, typeElements) { - var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 4096 /* ReverseMapped */); var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 2048 /* Late */) { var decl = ts.first(propertySymbol.declarations); if (hasLateBindableName(decl)) { trackComputedName(decl.name, saveEnclosingDeclaration, context); @@ -34353,7 +34448,7 @@ var ts; } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; - var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* RestParameter */; var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -34362,7 +34457,7 @@ var ts; cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); - var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* OptionalParameter */; var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, @@ -34758,6 +34853,21 @@ var ts; function isDefaultBindingContext(location) { return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); } + function getNameOfSymbolFromNameType(symbol, context) { + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 384 /* StringOrNumberLiteral */) { + var name = "" + nameType.value; + if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { + return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\""; + } + return name; + } + if (nameType.flags & 8192 /* UniqueESSymbol */) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; + } + } + } /** * Gets a human-readable name for a symbol. * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. @@ -34777,12 +34887,19 @@ var ts; } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - var name = ts.getNameOfDeclaration(declaration); - if (name) { + var name_2 = ts.getNameOfDeclaration(declaration); + if (name_2) { if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { return ts.symbolName(symbol); } - return ts.declarationNameToString(name); + if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 2048 /* Late */) && symbol.nameType && symbol.nameType.flags & 384 /* StringOrNumberLiteral */) { + // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name + var result = getNameOfSymbolFromNameType(symbol, context); + if (result !== undefined) { + return result; + } + } + return ts.declarationNameToString(name_2); } if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -34797,16 +34914,8 @@ var ts; return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } - var nameType = symbol.nameType; - if (nameType) { - if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { - return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; - } - if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { - return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; - } - } - return ts.symbolName(symbol); + var name = getNameOfSymbolFromNameType(symbol, context); + return name !== undefined ? name : ts.symbolName(symbol); } function isDeclarationVisible(node) { if (node) { @@ -35026,6 +35135,9 @@ var ts; var prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } + function getTypeOfPropertyOrIndexSignature(type, name) { + return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType; + } function isTypeAny(type) { return type && (type.flags & 1 /* Any */) !== 0; } @@ -35072,6 +35184,64 @@ var ts; var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); } + // Determine the control flow type associated with a destructuring declaration or assignment. The following + // forms of destructuring are possible: + // let { x } = obj; // BindingElement + // let [ x ] = obj; // BindingElement + // { x } = obj; // ShorthandPropertyAssignment + // { x: v } = obj; // PropertyAssignment + // [ x ] = obj; // Expression + // We construct a synthetic element access expression corresponding to 'obj.x' such that the control + // flow analyzer doesn't have to handle all the different syntactic forms. + function getFlowTypeOfDestructuring(node, declaredType) { + var reference = getSyntheticElementAccess(node); + return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType; + } + function getSyntheticElementAccess(node) { + var parentAccess = getParentElementAccess(node); + if (parentAccess && parentAccess.flowNode) { + var propName = getDestructuringPropertyName(node); + if (propName) { + var result = ts.createNode(190 /* ElementAccessExpression */, node.pos, node.end); + result.parent = node; + result.expression = parentAccess; + var literal = ts.createNode(10 /* StringLiteral */, node.pos, node.end); + literal.parent = result; + literal.text = propName; + result.argumentExpression = literal; + result.flowNode = parentAccess.flowNode; + return result; + } + } + } + function getParentElementAccess(node) { + var ancestor = node.parent.parent; + switch (ancestor.kind) { + case 186 /* BindingElement */: + case 275 /* PropertyAssignment */: + return getSyntheticElementAccess(ancestor); + case 187 /* ArrayLiteralExpression */: + return getSyntheticElementAccess(node.parent); + case 237 /* VariableDeclaration */: + return ancestor.initializer; + case 204 /* BinaryExpression */: + return ancestor.right; + } + } + function getDestructuringPropertyName(node) { + var parent = node.parent; + if (node.kind === 186 /* BindingElement */ && parent.kind === 184 /* ObjectBindingPattern */) { + return getLiteralPropertyNameText(node.propertyName || node.name); + } + if (node.kind === 275 /* PropertyAssignment */ || node.kind === 276 /* ShorthandPropertyAssignment */) { + return getLiteralPropertyNameText(node.name); + } + return "" + parent.elements.indexOf(node); + } + function getLiteralPropertyNameText(name) { + var type = getLiteralTypeFromPropertyName(name); + return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined; + } /** Return the inferred type for a binding element */ function getTypeForBindingElement(declaration) { var pattern = declaration.parent; @@ -35112,9 +35282,9 @@ var ts; else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; - var exprType = getLiteralTypeFromPropertyName(name); - var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); - type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); + var indexType = getLiteralTypeFromPropertyName(name); + var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); } } else { @@ -35131,21 +35301,13 @@ var ts; mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } + else if (isArrayLikeType(parentType)) { + var indexType = getLiteralType(index_1); + var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, declaration.name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); + } else { - // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_2 = pattern.elements.indexOf(declaration); - type = everyType(parentType, isTupleLikeType) ? - getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : - elementType; - if (!type) { - if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); - } - else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); - } - return errorType; - } + type = elementType; } } // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -35596,12 +35758,11 @@ var ts; return anyType; } // Handle export default expressions - if (ts.isSourceFile(declaration)) { - var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - if (!jsonSourceFile.statements.length) { + if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) { + if (!declaration.statements.length) { return emptyObjectType; } - var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + var type_1 = getWidenedLiteralType(checkExpression(declaration.statements[0].expression)); if (type_1.flags & 524288 /* Object */) { return getRegularTypeOfObjectLiteral(type_1); } @@ -35612,6 +35773,10 @@ var ts; } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & 512 /* ValueModule */) { + return getTypeOfFuncClassEnumModule(symbol); + } return errorType; } var type; @@ -35625,7 +35790,8 @@ var ts; || ts.isClassDeclaration(declaration) || ts.isFunctionDeclaration(declaration) || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { + || ts.isMethodSignature(declaration) + || ts.isSourceFile(declaration)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { return getTypeOfFuncClassEnumModule(symbol); @@ -35665,6 +35831,10 @@ var ts; return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } if (!popTypeResolution()) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & 512 /* ValueModule */) { + return getTypeOfFuncClassEnumModule(symbol); + } type = reportCircularityError(symbol); } return type; @@ -35858,7 +36028,7 @@ var ts; if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } - if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) { + if (ts.getCheckFlags(symbol) & 4096 /* ReverseMapped */) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -36237,9 +36407,8 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(262144 /* TypeParameter */); + type.thisType = createTypeParameter(symbol); type.thisType.isThisType = true; - type.thisType.symbol = symbol; type.thisType.constraint = type; } } @@ -36375,19 +36544,11 @@ var ts; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var type = createType(262144 /* TypeParameter */); - type.symbol = symbol; - links.declaredType = type; - } - return links.declaredType; + return links.declaredType || (links.declaredType = createTypeParameter(symbol)); } function getDeclaredTypeOfAlias(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); - } - return links.declaredType; + return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol))); } function getDeclaredTypeOfSymbol(symbol) { return tryGetDeclaredTypeOfSymbol(symbol) || errorType; @@ -36584,7 +36745,7 @@ var ts; * members. */ function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { - ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol."); + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 2048 /* Late */), "Expected a late-bound symbol."); symbol.flags |= symbolFlags; getSymbolLinks(member.symbol).lateSymbol = symbol; if (!symbol.declarations) { @@ -36641,7 +36802,7 @@ var ts; // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations. var lateSymbol = lateSymbols.get(memberName); if (!lateSymbol) - lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */)); + lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 2048 /* Late */)); // Report an error if a late-bound member has the same name as an early-bound member, // or if we have another early-bound symbol declaration with the same name and // conflicting flags. @@ -36650,10 +36811,10 @@ var ts; // If we have an existing early-bound member, combine its declarations so that we can // report an error at each declaration. var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_2 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); - lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); + var name_3 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + lateSymbol = createSymbol(0 /* None */, memberName, 2048 /* Late */); } lateSymbol.nameType = type; addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); @@ -36829,8 +36990,8 @@ var ts; var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; var restParams = ts.map(elementTypes, function (t, i) { var name = getParameterNameAtPosition(sig, restIndex_1 + i); - var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ : - i >= minLength_1 ? 4096 /* OptionalParameter */ : 0; + var checkFlags = i === tupleRestIndex_1 ? 16384 /* RestParameter */ : + i >= minLength_1 ? 8192 /* OptionalParameter */ : 0; var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; return symbol; @@ -36903,7 +37064,13 @@ var ts; // type is the union of the constituent return types. function getUnionSignatures(signatureLists) { var result; + var indexWithLengthOverOne; for (var i = 0; i < signatureLists.length; i++) { + if (signatureLists[i].length === 0) + return ts.emptyArray; + if (signatureLists[i].length > 1) { + indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets + } for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { var signature = _a[_i]; // Only process signatures with parameter lists that aren't already in the result list @@ -36928,8 +37095,82 @@ var ts; } } } + if (!ts.length(result) && indexWithLengthOverOne !== -1) { + // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single + // signature that handles all over them. We only do this when there are overloads in only one constituent. + // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of + // signatures from the type, whose ordering would be non-obvious) + var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; + var results = masterList.slice(); + var _loop_5 = function (signatures) { + if (signatures !== masterList) { + var signature_1 = signatures[0]; + ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); + results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); + if (!results) { + return "break"; + } + } + }; + for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) { + var signatures = signatureLists_1[_b]; + var state_2 = _loop_5(signatures); + if (state_2 === "break") + break; + } + result = results; + } return result || ts.emptyArray; } + function combineUnionThisParam(left, right) { + if (!left || !right) { + return left || right; + } + // A signature `this` type might be a read or a write position... It's very possible that it should be invariant + // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be + // permissive when calling, for now, we'll union the `this` types just like the overlapping-union-signature check does + var thisType = getUnionType([getTypeOfSymbol(left), getTypeOfSymbol(right)], 2 /* Subtype */); + return createSymbolWithType(left, thisType); + } + function combineUnionParameters(left, right) { + var longest = getParameterCount(left) >= getParameterCount(right) ? left : right; + var shorter = longest === left ? right : left; + var longestCount = getParameterCount(longest); + var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (var i = 0; i < longestCount; i++) { + var longestParamType = tryGetTypeAtPosition(longest, i); + var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + var unionParamType = getIntersectionType([longestParamType, shorterParamType]); + var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + var leftName = getParameterNameAtPosition(left, i); + var rightName = getParameterNameAtPosition(right, i); + var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), leftName === rightName ? leftName : "arg" + i); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args"); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfUnionMembers(left, right) { + var declaration = left.declaration; + var params = combineUnionParameters(left, right); + var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); + var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + var hasRestParam = left.hasRestParameter || right.hasRestParameter; + var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; + var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); + return result; + } function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; @@ -36947,7 +37188,7 @@ var ts; function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union // type use getPropertiesOfType (only the language service uses this). - var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); })); var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); @@ -36983,7 +37224,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_5 = function (i) { + var _loop_6 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -37006,7 +37247,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_5(i); + _loop_6(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -37082,7 +37323,7 @@ var ts; var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { var prop = _a[_i]; - var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + var checkFlags = 4096 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); inferredProp.declarations = prop.declarations; inferredProp.nameType = prop.nameType; @@ -37093,6 +37334,37 @@ var ts; } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); } + // Return the lower bound of the key type in a mapped type. Intuitively, the lower + // bound includes those keys that are known to always be present, for example because + // because of constraints on type parameters (e.g. 'keyof T' for a constrained T). + function getLowerBoundOfKeyType(type) { + if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) { + return type; + } + if (type.flags & 4194304 /* Index */) { + return getIndexType(getApparentType(type.type)); + } + if (type.flags & 16777216 /* Conditional */) { + return getLowerBoundOfConditionalType(type); + } + if (type.flags & 1048576 /* Union */) { + return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); + } + if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); + } + return neverType; + } + function getLowerBoundOfConditionalType(type) { + if (type.root.isDistributive) { + var constraint = getLowerBoundOfKeyType(type.checkType); + if (constraint !== type.checkType) { + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** Resolve the members of a mapped type { [P in K]: T } */ function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); @@ -37122,10 +37394,7 @@ var ts; } } else { - // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Then iterate over the constituents of the key type. - var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; - forEachType(iterationType, addMemberForKeyType); + forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); function addMemberForKeyType(t) { @@ -37309,7 +37578,7 @@ var ts; return list.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); }); } function getAllPossiblePropertiesOfTypes(types) { @@ -37373,7 +37642,7 @@ var ts; if (type.root.isDistributive) { var simplified = getSimplifiedType(type.checkType); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; - if (constraint) { + if (constraint && constraint !== type.checkType) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); if (!(instantiated.flags & 131072 /* Never */)) { @@ -37618,10 +37887,10 @@ var ts; commonFlags &= prop.flags; props = ts.appendIfUnique(props, prop); checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | - (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | - (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | - (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | - (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 512 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 1024 /* ContainsStatic */ : 0); if (!isPrototypeProperty(prop)) { syntheticFlag = 2 /* SyntheticProperty */; } @@ -37645,39 +37914,38 @@ var ts; return props[0]; } var declarations; - var commonType; + var firstType; var nameType; var propTypes = []; - var first = true; - var commonValueDeclaration; + var firstValueDeclaration; var hasNonUniformValueDeclaration = false; for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { var prop = props_1[_b]; - if (!commonValueDeclaration) { - commonValueDeclaration = prop.valueDeclaration; + if (!firstValueDeclaration) { + firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== commonValueDeclaration) { + else if (prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = ts.addRange(declarations, prop.declarations); var type = getTypeOfSymbol(prop); - if (first) { - commonType = type; + if (!firstType) { + firstType = type; nameType = prop.nameType; - first = false; } - else { - if (type !== commonType) { - checkFlags |= 32 /* HasNonUniformType */; - } + else if (type !== firstType) { + checkFlags |= 32 /* HasNonUniformType */; + } + if (isLiteralType(type)) { + checkFlags |= 64 /* HasLiteralType */; } propTypes.push(type); } ts.addRange(propTypes, indexTypes); var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; - if (!hasNonUniformValueDeclaration && commonValueDeclaration) { - result.valueDeclaration = commonValueDeclaration; + if (!hasNonUniformValueDeclaration && firstValueDeclaration) { + result.valueDeclaration = firstValueDeclaration; } result.declarations = declarations; result.nameType = nameType; @@ -37877,21 +38145,17 @@ var ts; var numTypeArguments = ts.length(typeArguments); if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { var result = typeArguments ? typeArguments.slice() : []; - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + // Map invalid forward references in default types to the error type for (var i = numTypeArguments; i < numTypeParameters; i++) { - result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + result[i] = errorType; } + var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny); for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, result); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { defaultType = anyType; } - result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType; } result.length = typeParameters.length; return result; @@ -37980,7 +38244,7 @@ var ts; var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); - var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */); + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 16384 /* RestParameter */); syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; if (lastParamVariadicType) { // Replace the last parameter with a rest parameter. @@ -38851,7 +39115,7 @@ var ts; if (arity) { typeParameters = new Array(arity); for (var i = 0; i < arity; i++) { - var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); + var typeParameter = typeParameters[i] = createTypeParameter(); if (i < maxLength) { var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); property.type = typeParameter; @@ -38873,7 +39137,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(262144 /* TypeParameter */); + type.thisType = createTypeParameter(); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -39374,8 +39638,13 @@ var ts; if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { - var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + if (prop.escapedName === "default" /* Default */) { + type = getLiteralType("default"); + } + else { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + } } if (type && type.flags & include) { return type; @@ -39465,14 +39734,14 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = isTypeUsableAsLateBoundName(indexType) - ? getLateBoundNameFromType(indexType) - : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) - ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) - : accessNode && ts.isPropertyName(accessNode) + var propName = isTypeUsableAsLateBoundName(indexType) ? + getLateBoundNameFromType(indexType) : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? + ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : + accessNode && ts.isPropertyName(accessNode) ? // late bound names are handled in the first branch, so here we only need to handle normal names - ? ts.getPropertyNameForPropertyNameNode(accessNode) - : undefined; + ts.getPropertyNameForPropertyNameNode(accessNode) : + undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { @@ -39494,7 +39763,12 @@ var ts; if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { var indexNode = getIndexNodeForAccessExpression(accessNode); - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + if (isTupleType(objectType)) { + error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName)); + } + else { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } } return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } @@ -39619,24 +39893,14 @@ var ts; // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we - // construct the type Box. We do not further simplify the result because mapped types can be recursive - // and we might never terminate. + // construct the type Box. if (isGenericMappedType(objectType)) { - return type.simplified = substituteIndexedMappedType(objectType, type); - } - if (objectType.flags & 262144 /* TypeParameter */) { - var constraint = getConstraintOfTypeParameter(objectType); - if (constraint && isGenericMappedType(constraint)) { - return type.simplified = substituteIndexedMappedType(constraint, type); - } + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var templateMapper = combineTypeMappers(objectType.mapper, mapper); + return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType); } return type.simplified = type; } - function substituteIndexedMappedType(objectType, type) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); - } function getIndexedAccessType(objectType, indexType, accessNode, missingType) { if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { @@ -39724,14 +39988,11 @@ var ts; if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } - // If this is a distributive conditional type and the check type is generic we need to defer - // resolution of the conditional type such that a later instantiation will properly distribute - // over union types. - var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); + var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */); var combinedMapper; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); - if (!isDeferred) { + if (!checkTypeInstantiable) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. @@ -39739,28 +40000,30 @@ var ts; } combinedMapper = combineTypeMappers(mapper, context); } - if (!isDeferred) { - if (extendsType.flags & 3 /* AnyOrUnknown */) { + // Instantiate the extends type including inferences for 'infer T' type parameters + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // We attempt to resolve the conditional type only when the check and extends types are non-generic + if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */)) { + if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) { return instantiateType(root.trueType, mapper); } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & 1 /* Any */) { return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); } - // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; // Return falseType for a definitely false extends check. We check an instantations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instatiations will be and we can just return the false branch type. - if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { return instantiateType(root.falseType, mapper); } - // Return trueType for a definitely true extends check. The definitely assignable relation excludes - // type variable constraints from consideration. Without the definitely assignable relation, the type + // Return trueType for a definitely true extends check. We check instantiations of the two + // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter + // that has no constraint. This ensures that, for example, the type // type Foo = T extends { x: string } ? string : number - // would immediately resolve to 'string' instead of being deferred. - if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + // doesn't immediately resolve to 'string' instead of being deferred. + if (isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) { return instantiateType(root.trueType, combinedMapper || mapper); } } @@ -40309,12 +40572,17 @@ var ts; function createReplacementMapper(source, target, baseMapper) { return function (t) { return t === source ? target : baseMapper(t); }; } - function wildcardMapper(type) { + function permissiveMapper(type) { return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; } + function getRestrictiveTypeParameter(tp) { + return !tp.constraint ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol)); + } + function restrictiveMapper(type) { + return type.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(type) : type; + } function cloneTypeParameter(typeParameter) { - var result = createType(262144 /* TypeParameter */); - result.symbol = typeParameter.symbol; + var result = createTypeParameter(typeParameter.symbol); result.target = typeParameter; return result; } @@ -40373,7 +40641,7 @@ var ts; } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */)); + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */)); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -40645,9 +40913,13 @@ var ts; } return type; } - function getWildcardInstantiation(type) { + function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : - type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); + type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); + } + function getRestrictiveInstantiation(type) { + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : + type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); @@ -40711,8 +40983,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - var body = node.body; - return body.kind === 218 /* Block */ ? false : isContextSensitive(body); + return !!node.body && node.body.kind !== 218 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -40829,7 +41100,7 @@ var ts; case 187 /* ArrayLiteralExpression */: return elaborateArrayLiteral(node, source, target, relation); case 268 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target, relation); + return elaborateJsxComponents(node, source, target, relation); case 197 /* ArrowFunction */: return elaborateArrowFunction(node, source, target, relation); } @@ -40970,8 +41241,117 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target, relation) { - return elaborateElementwise(generateJsxAttributes(node), source, target, relation); + function generateJsxChildren(node, getInvalidTextDiagnostic) { + var memberOffset, i, child, nameType, elem; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!ts.length(node.children)) + return [2 /*return*/]; + memberOffset = 0; + i = 0; + _a.label = 1; + case 1: + if (!(i < node.children.length)) return [3 /*break*/, 5]; + child = node.children[i]; + nameType = getLiteralType(i - memberOffset); + elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic); + if (!elem) return [3 /*break*/, 3]; + return [4 /*yield*/, elem]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + memberOffset++; + _a.label = 4; + case 4: + i++; + return [3 /*break*/, 1]; + case 5: return [2 /*return*/]; + } + }); + } + function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { + switch (child.kind) { + case 270 /* JsxExpression */: + // child is of the type of the expression + return { errorNode: child, innerExpression: child.expression, nameType: nameType }; + case 11 /* JsxText */: + if (child.containsOnlyWhiteSpaces) { + break; // Whitespace only jsx text isn't real jsx text + } + // child is a string + return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + // child is of type JSX.Element + return { errorNode: child, innerExpression: child, nameType: nameType }; + default: + return ts.Debug.assertNever(child, "Found invalid jsx child"); + } + } + function elaborateJsxComponents(node, source, target, relation) { + var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation); + var invalidTextDiagnostic; + if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) { + var containingElement = node.parent.parent; + var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName); + var childrenNameType = getLiteralType(childrenPropName); + var childrenTargetType = getIndexedAccessType(target, childrenNameType); + var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; }); + if (!ts.length(validChildren)) { + return result; + } + var moreThanOneRealChildren = ts.length(validChildren) > 1; + var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType); + var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); }); + if (moreThanOneRealChildren) { + if (arrayLikeTargetParts !== neverType) { + var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */)); + result = elaborateElementwise(generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic), realSource, arrayLikeTargetParts, relation) || result; + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + // arity mismatch + result = true; + error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, typeToString(childrenTargetType)); + } + } + else { + if (nonArrayLikeTargetParts !== neverType) { + var child = validChildren[0]; + var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic); + if (elem_1) { + result = elaborateElementwise((function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, elem_1]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); })(), source, target, relation) || result; + } + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + // arity mismatch + result = true; + error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, typeToString(childrenTargetType)); + } + } + } + return result; + function getInvalidTextualChildDiagnostic() { + if (!invalidTextDiagnostic) { + var tagNameText = ts.getTextOfNode(node.parent.tagName); + var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName); + var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName)); + var diagnostic = ts.Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2; + invalidTextDiagnostic = __assign({}, diagnostic, { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) }); + } + return invalidTextDiagnostic; + } } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -41224,7 +41604,7 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & 67108864 /* NonPrimitive */ ? true : type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : @@ -41307,9 +41687,7 @@ var ts; return true; if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) return true; - if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) - return false; - if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { + if (relation === assignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) return true; // Type number or any numeric literal type is assignable to any numeric enum type or any @@ -41479,7 +41857,7 @@ var ts; target = target.regularType; } if (source.flags & 33554432 /* Substitution */) { - source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; + source = source.substitute; } if (target.flags & 33554432 /* Substitution */) { target = target.typeVariable; @@ -41654,9 +42032,9 @@ var ts; if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + if (isExcessPropertyCheckTarget(target)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && + if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } @@ -41664,9 +42042,12 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_6 = function (prop) { + var _loop_7 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { + // Report error in terms of object types in the target as those are the only ones + // we check in isKnownProperty. + var errorTarget = filterType(target, isExcessPropertyCheckTarget); // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. @@ -41676,7 +42057,7 @@ var ts; // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) - reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget)); } else { // use the property's value declaration if the property is assigned inside the literal itself @@ -41688,14 +42069,14 @@ var ts; errorNode = propDeclaration; var name = propDeclaration.name; if (ts.isIdentifier(name)) { - suggestion = getSuggestionForNonexistentProperty(name, target); + suggestion = getSuggestionForNonexistentProperty(name, errorTarget); } } if (suggestion !== undefined) { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion); } else { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget)); } } } @@ -41704,9 +42085,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_6(prop); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_7(prop); + if (typeof state_3 === "object") + return state_3.value; } } return false; @@ -41743,7 +42124,8 @@ var ts; var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || - findBestTypeForInvokable(source, target); + findBestTypeForInvokable(source, target) || + findMostOverlappyType(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -41778,6 +42160,34 @@ var ts; return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); } } + function findMostOverlappyType(source, unionTarget) { + var bestMatch; + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target_1 = _a[_i]; + var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]); + if (overlap.flags & 4194304 /* Index */) { + // perfect overlap of keys + bestMatch = target_1; + matchingCount = Infinity; + } + else if (overlap.flags & 1048576 /* Union */) { + // We only want to account for literal types otherwise. + // If we have a union of index types, it seems likely that we + // needed to elaborate between two generic mapped types anyway. + var len = ts.length(ts.filter(overlap.types, isUnitType)); + if (len >= matchingCount) { + bestMatch = target_1; + matchingCount = len; + } + } + else if (isUnitType(overlap) && 1 >= matchingCount) { + bestMatch = target_1; + matchingCount = 1; + } + } + return bestMatch; + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { if (target.flags & 1048576 /* Union */) { @@ -41951,30 +42361,27 @@ var ts; } return result; } - function getConstraintForRelation(type) { - return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); - } function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { var flags = source.flags & target.flags; if (relation === identityRelation && !(flags & 524288 /* Object */)) { if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_2 = 0 /* False */; + var result_3 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_2; + if (result_3 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_3; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_2; + if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_3; } } } @@ -42023,24 +42430,23 @@ var ts; } // A type S is assignable to keyof T if S is assignable to keyof C, where C is the // simplified form of T or, if T doesn't simplify, the constraint of T. - if (relation !== definitelyAssignableRelation) { - var simplified = getSimplifiedType(target.type); - var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); - if (constraint) { - // We require Ternary.True here such that circular constraints don't cause - // false positives. For example, given 'T extends { [K in keyof T]: string }', - // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when - // related to other types. - if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { - return -1 /* True */; - } + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } else if (target.flags & 8388608 /* IndexedAccess */) { // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, // where C is the base constraint of T[K] - if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + if (relation !== identityRelation && + !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { var constraint = getBaseConstraintOfType(target); if (constraint && constraint !== target) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -42081,8 +42487,8 @@ var ts; return result; } } - var constraint = getConstraintForRelation(source); - if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + var constraint = getConstraintOfType(source); + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { errorInfo = saveErrorInfo; @@ -42122,7 +42528,7 @@ var ts; } } } - else if (relation !== definitelyAssignableRelation) { + else { var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { @@ -42141,7 +42547,7 @@ var ts; } else { // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + if (isPartialMappedType(target) && isEmptyObjectType(source)) { return -1 /* True */; } if (isGenericMappedType(target)) { @@ -42153,9 +42559,6 @@ var ts; } return 0 /* False */; } - if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { - return 0 /* False */; - } var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); if (relation !== identityRelation) { source = getApparentType(source); @@ -42235,10 +42638,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_3; - if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_4; + if (result_4 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_4 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -42248,10 +42651,10 @@ var ts; return propertiesIdenticalTo(source, target); } var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); - var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false); if (unmatchedProperty) { if (reportErrors) { - var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false)); if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it @@ -42327,7 +42730,7 @@ var ts; var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; - if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */ && hasDifferingDeclarations) { + if (ts.getCheckFlags(sourceProp) & 512 /* ContainsPrivate */ && hasDifferingDeclarations) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -43003,6 +43406,9 @@ var ts; function isTupleLikeType(type) { return isTupleType(type) || !!getPropertyOfType(type, "0"); } + function isArrayOrTupleLikeType(type) { + return isArrayLikeType(type) || isTupleLikeType(type); + } function getTupleElementType(type, index) { var propType = getTypeOfPropertyOfType(type, "" + index); if (propType) { @@ -43292,6 +43698,9 @@ var ts; // union includes empty object types (e.g. reducing {} | string to just {}). return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); } + if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.sameMap(type.types, getWidenedType)); + } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); } @@ -43378,6 +43787,10 @@ var ts; break; case 186 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + if (!noImplicitAny) { + // Don't issue a suggestion for binding elements since the codefix doesn't yet support them. + return; + } break; case 289 /* JSDocFunctionType */: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); @@ -43575,8 +43988,8 @@ var ts; inferTypes([inference], sourceType, templateType); return getTypeFromInference(inference); } - function getUnmatchedProperties(source, target, requireOptionalProperties) { - var properties, _i, properties_4, targetProp, sourceProp; + function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) { + var properties, _i, properties_4, targetProp, sourceProp, targetType, sourceType; return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -43584,24 +43997,34 @@ var ts; _i = 0, properties_4 = properties; _a.label = 1; case 1: - if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + if (!(_i < properties_4.length)) return [3 /*break*/, 6]; targetProp = properties_4[_i]; - if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 5]; sourceProp = getPropertyOfType(source, targetProp.escapedName); if (!!sourceProp) return [3 /*break*/, 3]; return [4 /*yield*/, targetProp]; case 2: _a.sent(); - _a.label = 3; + return [3 /*break*/, 5]; case 3: + if (!matchDiscriminantProperties) return [3 /*break*/, 5]; + targetType = getTypeOfSymbol(targetProp); + if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5]; + sourceType = getTypeOfSymbol(sourceProp); + if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5]; + return [4 /*yield*/, targetProp]; + case 4: + _a.sent(); + _a.label = 5; + case 5: _i++; return [3 /*break*/, 1]; - case 4: return [2 /*return*/]; + case 6: return [2 /*return*/]; } }); } - function getUnmatchedProperty(source, target, requireOptionalProperties) { - return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; + function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next().value; } function tupleTypesDefinitelyUnrelated(source, target) { return target.target.minLength > source.target.minLength || @@ -43611,7 +44034,8 @@ var ts; // Two tuple types with incompatible arities are definitely unrelated. // Two object types that each have a property that is unmatched in the other are definitely unrelated. return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || - !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) && + !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true); } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : @@ -44216,48 +44640,31 @@ var ts; // occurring in an apparent type position with '@' because the control flow type // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { - if (node.kind === 72 /* Identifier */) { - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; - } - if (node.kind === 100 /* ThisKeyword */) { - return "0"; - } - if (node.kind === 189 /* PropertyAccessExpression */) { - var key = getFlowCacheKey(node.expression); - return key && key + "." + ts.idText(node.name); - } - if (node.kind === 186 /* BindingElement */) { - var container = node.parent.parent; - var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); - var text = getBindingElementNameText(node); - var result = key && text && (key + "." + text); - return result; + switch (node.kind) { + case 72 /* Identifier */: + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + case 100 /* ThisKeyword */: + return "0"; + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + return getFlowCacheKey(node.expression); + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + var propName = getAccessedPropertyName(node); + if (propName !== undefined) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + propName; + } } return undefined; } - function getBindingElementNameText(element) { - var parent = element.parent; - if (parent.kind === 184 /* ObjectBindingPattern */) { - var name = element.propertyName || element.name; - switch (name.kind) { - case 72 /* Identifier */: - return ts.idText(name); - case 149 /* ComputedPropertyName */: - return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; - case 10 /* StringLiteral */: - case 8 /* NumericLiteral */: - return name.text; - default: - // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined - ts.Debug.fail("Unexpected name kind for binding element name"); - } - } - else { - return "" + parent.elements.indexOf(element); - } - } function isMatchingReference(source, target) { + switch (target.kind) { + case 195 /* ParenthesizedExpression */: + case 213 /* NonNullExpression */: + return isMatchingReference(source, target.expression); + } switch (source.kind) { case 72 /* Identifier */: return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || @@ -44267,34 +44674,24 @@ var ts; return target.kind === 100 /* ThisKeyword */; case 98 /* SuperKeyword */: return target.kind === 98 /* SuperKeyword */; + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + return isMatchingReference(source.expression, target); case 189 /* PropertyAccessExpression */: case 190 /* ElementAccessExpression */: - return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 186 /* BindingElement */: - if (target.kind !== 189 /* PropertyAccessExpression */) - return false; - var t = target; - if (t.name.escapedText !== getBindingElementNameText(source)) - return false; - if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { - return true; - } - if (source.parent.parent.kind === 237 /* VariableDeclaration */) { - var maybeId = source.parent.parent.initializer; - return !!maybeId && isMatchingReference(maybeId, t.expression); - } } return false; } function getAccessedPropertyName(access) { - return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + return access.kind === 189 /* PropertyAccessExpression */ ? access.name.escapedText : ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : undefined; } function containsMatchingReference(source, target) { - while (source.kind === 189 /* PropertyAccessExpression */) { + while (ts.isAccessExpression(source)) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -44307,42 +44704,37 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 189 /* PropertyAccessExpression */ && + var name; + return ts.isAccessExpression(target) && containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + (name = getAccessedPropertyName(target)) !== undefined && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), name); } function getDeclaredTypeOfReference(expr) { if (expr.kind === 72 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 189 /* PropertyAccessExpression */) { + if (ts.isAccessExpression(expr)) { var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + if (type) { + var propName = getAccessedPropertyName(expr); + return propName !== undefined ? getTypeOfPropertyOfType(type, propName) : undefined; + } } return undefined; } function isDiscriminantType(type) { - if (type.flags & 1048576 /* Union */) { - if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { - return true; - } - var combined = 0; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - combined |= t.flags; - } - if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { - return true; - } - } - return false; + return !!(type.flags & 1048576 /* Union */ && + (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */) || !isGenericIndexType(type))); } function isDiscriminantProperty(type, name) { if (type && type.flags & 1048576 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = + (prop.checkFlags & 96 /* Discriminant */) === 96 /* Discriminant */ && + isDiscriminantType(getTypeOfSymbol(prop)); } return !!prop.isDiscriminantProperty; } @@ -45201,25 +45593,23 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 1048576 /* Union */) || - expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { return false; } - var access = expr; - var name = getAccessedPropertyName(access); - if (!name) { + var name = getAccessedPropertyName(expr); + if (name === undefined) { return false; } - return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); - if (!propName) { + if (propName === undefined) { return type; } var propType = getTypeOfPropertyOfType(type, propName); var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOrIndexSignature(t, propName), narrowedPropType); }); } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { @@ -45564,9 +45954,8 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { - var accessExpression = invokedExpression; - var possibleReference = ts.skipParentheses(accessExpression.expression); + if (ts.isAccessExpression(invokedExpression)) { + var possibleReference = ts.skipParentheses(invokedExpression.expression); if (isMatchingReference(reference, possibleReference)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } @@ -45983,7 +46372,7 @@ var ts; } function checkThisBeforeSuper(node, container, diagnosticMessage) { var containingClassDecl = container.parent; - var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); + var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl); // If a containing class does not have extends clause or the class extends null // skip checking whether super statement is called before "this" accessing. if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { @@ -46304,7 +46693,7 @@ var ts; } // at this point the only legal case for parent is ClassLikeDeclaration var classLikeDeclaration = container.parent; - if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { + if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); return errorType; } @@ -46461,6 +46850,30 @@ var ts; tryGetTypeAtPosition(contextualSignature, index); } } + function getContextualTypeForVariableLikeDeclaration(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + switch (declaration.kind) { + case 151 /* Parameter */: + return getContextuallyTypedParameterType(declaration); + case 186 /* BindingElement */: + return getContextualTypeForBindingElement(declaration); + // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent + } + } + function getContextualTypeForBindingElement(declaration) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + var parentType = getContextualTypeForVariableLikeDeclaration(parentDeclaration); + if (parentType && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text !== undefined) { + return getTypeOfPropertyOfType(parentType, text); + } + } + } // In a variable, parameter or property declaration with a type annotation, // the contextual type of an initializer expression is the type of the variable, parameter or property. // Otherwise, in a parameter declaration of a contextually typed function expression, @@ -46472,32 +46885,13 @@ var ts; function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; if (ts.hasInitializer(declaration) && node === declaration.initializer) { - var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - return getTypeFromTypeNode(typeNode); + var result = getContextualTypeForVariableLikeDeclaration(declaration); + if (result) { + return result; } - if (declaration.kind === 151 /* Parameter */) { - var type = getContextuallyTypedParameterType(declaration); - if (type) { - return type; - } - } - if (ts.isBindingPattern(declaration.name)) { + if (ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } - if (ts.isBindingPattern(declaration.parent)) { - var parentDeclaration = declaration.parent.parent; - var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 186 /* BindingElement */) { - var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); - if (parentTypeNode && !ts.isBindingPattern(name)) { - var text = ts.getTextOfPropertyName(name); - if (text) { - return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); - } - } - } - } } return undefined; } @@ -46750,18 +47144,30 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForChildJsxExpression(node) { + function getContextualTypeForChildJsxExpression(node, child) { var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); - return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { + return undefined; + } + var childIndex = node.children.indexOf(child); + var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName); + return childFieldType && mapType(childFieldType, function (t) { + if (isArrayLikeType(t)) { + return getIndexedAccessType(t, getLiteralType(childIndex)); + } + else { + return t; + } + }, /*noReductions*/ true); } function getContextualTypeForJsxExpression(node) { var exprParent = node.parent; return ts.isJsxAttributeLike(exprParent) ? getContextualType(node) : ts.isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent, node) : undefined; } function getContextualTypeForJsxAttribute(attribute) { @@ -46928,6 +47334,27 @@ var ts; return propsType; } function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + if (sig.unionSignatures) { + // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input + // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature, + // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur + // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input. + // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane. + var results = []; + for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + var instance = getReturnTypeOfSignature(signature); + if (isTypeAny(instance)) { + return instance; + } + var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation); + if (!propType) { + return; + } + results.push(propType); + } + return getIntersectionType(results); + } var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } @@ -47319,7 +47746,7 @@ var ts; var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? computedNameType : undefined; var prop = nameType ? - createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : + createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 2048 /* Late */) : createSymbol(4 /* Property */ | member.flags, member.escapedName); if (nameType) { prop.nameType = nameType; @@ -47919,7 +48346,7 @@ var ts; return true; } } - else if (targetType.flags & 3145728 /* UnionOrIntersection */) { + else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -47927,12 +48354,14 @@ var ts; } } } - else if (targetType.flags & 16777216 /* Conditional */) { - return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || - isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); - } return false; } + function isExcessPropertyCheckTarget(type) { + return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) || + type.flags & 67108864 /* NonPrimitive */ || + type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) || + type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget)); + } function checkJsxExpression(node, checkMode) { if (node.expression) { var type = checkExpression(node.expression, checkMode); @@ -47973,7 +48402,7 @@ var ts; function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; - if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(prop) & 512 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; @@ -48337,7 +48766,7 @@ var ts; } } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (nodeForCheckWriteOnly && isInTypeQuery(nodeForCheckWriteOnly) || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { @@ -48363,7 +48792,7 @@ var ts; } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind === 189 /* PropertyAccessExpression */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -49048,15 +49477,32 @@ var ts; return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { - var min = Infinity; - var max = -Infinity; + var argCount = typeArguments.length; + // No overloads exist + if (signatures.length === 1) { + var sig = signatures[0]; + var min_1 = getMinTypeArgumentCount(sig.typeParameters); + var max = ts.length(sig.typeParameters); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, min_1 < max ? min_1 + "-" + max : min_1, argCount); + } + // Overloads exist + var belowArgCount = -Infinity; + var aboveArgCount = Infinity; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, ts.length(sig.typeParameters)); + var min_2 = getMinTypeArgumentCount(sig.typeParameters); + var max = ts.length(sig.typeParameters); + if (min_2 > argCount) { + aboveArgCount = Math.min(aboveArgCount, min_2); + } + else if (max < argCount) { + belowArgCount = Math.max(belowArgCount, max); + } } - var paramCount = min === max ? min : min + "-" + max; - return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) { + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; @@ -49285,7 +49731,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_7 = function (i) { + var _loop_8 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -49296,7 +49742,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_7(i); + _loop_8(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -49453,7 +49899,7 @@ var ts; */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { @@ -49961,6 +50407,7 @@ var ts; if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.nameType = getLiteralType("default"); newSymbol.target = resolveSymbol(symbol); memberTable.set("default" /* Default */, newSymbol); var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); @@ -50954,20 +51401,18 @@ var ts; if (rightIsThis === void 0) { rightIsThis = false; } if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 149 /* ComputedPropertyName */) { - checkComputedPropertyName(name); - } - if (isComputedNonLiteralName(name)) { - return undefined; - } - var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); - if (type) { - // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); - } - else { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + var text = ts.getTextOfPropertyName(name); + if (text) { + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + } } + var exprType = getLiteralTypeFromPropertyName(name); + var elementType = getIndexedAccessType(objectLiteralType, exprType, name); + var type = getFlowTypeOfDestructuring(property, elementType); + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else if (property.kind === 277 /* SpreadAssignment */) { if (languageVersion < 6 /* ESNext */) { @@ -50987,23 +51432,6 @@ var ts; error(property, ts.Diagnostics.Property_assignment_expected); } } - function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { - if (isTypeAny(objectLiteralType)) { - return objectLiteralType; - } - var type; - var text = ts.getTextOfPropertyName(name); - if (text) { // TODO: GH#26379 - var prop = getPropertyOfType(objectLiteralType, text); - if (prop) { - markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); - type = getTypeOfSymbol(prop); - } - type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); - } - return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); - } function checkArrayLiteralAssignment(node, sourceType, checkMode) { var elements = node.elements; if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { @@ -51023,39 +51451,30 @@ var ts; var element = elements[elementIndex]; if (element.kind !== 210 /* OmittedExpression */) { if (element.kind !== 208 /* SpreadElement */) { - var propName = "" + elementIndex; - var type = isTypeAny(sourceType) ? sourceType : - everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : - elementType; - if (type) { + var indexType = getLiteralType(elementIndex); + if (isArrayLikeType(sourceType)) { + // We create a synthetic expression so that getIndexedAccessType doesn't get confused + // when the element is a SyntaxKind.ElementAccessExpression. + var elementType_2 = getIndexedAccessType(sourceType, indexType, createSyntheticExpression(element, indexType)); + var type = getFlowTypeOfDestructuring(element, elementType_2); return checkDestructuringAssignment(element, type, checkMode); } - // We still need to check element expression here because we may need to set appropriate flag on the expression - // such as NodeCheckFlags.LexicalThis on "this"expression. - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } + return checkDestructuringAssignment(element, elementType, checkMode); + } + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { - if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + var restExpression = element.expression; + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { - var restExpression = element.expression; - if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { - error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - else { - checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = everyType(sourceType, isTupleType) ? - mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : - createArrayType(elementType); - return checkDestructuringAssignment(restExpression, type, checkMode); - } + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); } } } @@ -51576,7 +51995,8 @@ var ts; var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) || - isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + isTypeAssertion(initializer) || + isLiteralOfContextualType(type, getContextualType(initializer)) ? type : getWidenedLiteralType(type); if (ts.isInJSFile(declaration)) { if (widened.flags & 98304 /* Nullable */) { reportImplicitAny(declaration, anyType); @@ -52259,7 +52679,7 @@ var ts; // Constructors of classes with no extends clause may not contain super calls, whereas // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; - if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { + if (ts.getClassExtendsHeritageElement(containingClassDecl)) { captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); @@ -52453,7 +52873,6 @@ var ts; break; } } - checkGrammarForDisallowedTrailingComma(node.elementTypes); ts.forEach(node.elementTypes, checkSourceElement); } function checkUnionOrIntersectionType(node) { @@ -52822,10 +53241,10 @@ var ts; case 248 /* ImportEqualsDeclaration */: case 251 /* NamespaceImport */: case 250 /* ImportClause */: - var result_4 = 0 /* None */; + var result_5 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); - return result_4; + ts.forEach(target.declarations, function (d) { result_5 |= getDeclarationSpaces(d); }); + return result_5; case 237 /* VariableDeclaration */: case 186 /* BindingElement */: case 239 /* FunctionDeclaration */: @@ -53313,7 +53732,12 @@ var ts; return; } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + if (ts.isQualifiedName(node.name)) { + error(node.name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(node.name), ts.entityNameToString(node.name.left)); + } + else { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name)); + } } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && @@ -54851,6 +55275,7 @@ var ts; if (produceDiagnostics) { if (node.default) { seenDefault = true; + checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i); } else if (seenDefault) { error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); @@ -54864,6 +55289,23 @@ var ts; } } } + /** Check that type parameter defaults only reference previously declared type parameters */ + function checkTypeParametersNotReferenced(root, typeParameters, index) { + visit(root); + function visit(node) { + if (node.kind === 164 /* TypeReference */) { + var type = getTypeFromTypeReference(node); + if (type.flags & 262144 /* TypeParameter */) { + for (var i = index; i < typeParameters.length; i++) { + if (type.symbol === getSymbolOfNode(typeParameters[i])) { + error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters); + } + } + } + } + ts.forEachChild(node, visit); + } + } /** Check that type parameter lists are identical across multiple declarations */ function checkTypeParameterListsIdentical(symbol) { if (symbol.declarations.length === 1) { @@ -55054,7 +55496,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_8 = function (member) { + var _loop_9 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -55073,7 +55515,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_8(member); + _loop_9(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -55347,7 +55789,7 @@ var ts; return 0; } else if (isConstEnum) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values); } else if (member.parent.flags & 4194304 /* Ambient */) { error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); @@ -57429,7 +57871,7 @@ var ts; isLateBound: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); var symbol = node && getSymbolOfNode(node); - return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); + return !!(symbol && ts.getCheckFlags(symbol) & 2048 /* Late */); }, getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { @@ -58021,9 +58463,6 @@ var ts; if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070 checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); } - if (ts.isBindingPattern(parameter.name)) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } if (parameter.questionToken) { return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); } @@ -59009,9 +59448,6 @@ var ts; JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; // tslint:enable variable-name })(JsxNames || (JsxNames = {})); - function typeIsLiteralType(type) { - return !!(type.flags & 2944 /* Literal */); - } })(ts || (ts = {})); var ts; (function (ts) { @@ -64575,15 +65011,19 @@ var ts; // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + function getLineInfo(text, lineStarts) { + return { + getLineCount: function () { return lineStarts.length; }, + getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); } + }; + } + ts.getLineInfo = getLineInfo; /** * Tries to find the sourceMappingURL comment at the end of a file. - * @param text The source text of the file. - * @param lineStarts The line starts of the file. */ - function tryGetSourceMappingURL(text, lineStarts) { - if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } - for (var index = lineStarts.length - 1; index >= 0; index--) { - var line = text.substring(lineStarts[index], lineStarts[index + 1]); + function tryGetSourceMappingURL(lineInfo) { + for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) { + var line = lineInfo.getLineText(index); var comment = sourceMapCommentRegExp.exec(line); if (comment) { return comment[1]; @@ -64827,7 +65267,10 @@ var ts; && left.sourcePosition === right.sourcePosition; } function compareSourcePositions(left, right) { - return ts.compareValues(left.sourceIndex, right.sourceIndex); + // Compares sourcePosition without comparing sourceIndex + // since the mappings are grouped by sourceIndex + ts.Debug.assert(left.sourceIndex === right.sourceIndex); + return ts.compareValues(left.sourcePosition, right.sourcePosition); } function compareGeneratedPositions(left, right) { return ts.compareValues(left.generatedPosition, right.generatedPosition); @@ -64842,11 +65285,9 @@ var ts; var mapDirectory = ts.getDirectoryPath(mapPath); var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); - var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); - var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath); var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); - var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); - var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; })); var decodedMappings; var generatedMappings; var sourceMappings; @@ -64856,16 +65297,15 @@ var ts; }; function processMapping(mapping) { var generatedPosition = generatedFile !== undefined - ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true) : -1; var source; var sourcePosition; if (isSourceMapping(mapping)) { - var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; - var sourceFile = host.getSourceFileLike(sourceFilePath); + var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]); source = map.sources[mapping.sourceIndex]; sourcePosition = sourceFile !== undefined - ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true) : -1; } return { @@ -67283,6 +67723,7 @@ var ts; switch (node.literal.kind) { case 10 /* StringLiteral */: return ts.createIdentifier("String"); + case 202 /* PrefixUnaryExpression */: case 8 /* NumericLiteral */: return ts.createIdentifier("Number"); case 9 /* BigIntLiteral */: @@ -71053,7 +71494,7 @@ var ts; if (node.name) { enableSubstitutionsForBlockScopedBindings(); } - var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + var extendsClauseElement = ts.getClassExtendsHeritageElement(node); var classFunction = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -71462,7 +71903,7 @@ var ts; * synthesized call to `super` */ function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; + return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper); } /** * Adds statements to the body of a function-like node if it contains a rest parameter. @@ -71479,10 +71920,10 @@ var ts; return; } // `declarationName` is the name of the local declaration for the parameter. - var declarationName = ts.getMutableClone(parameter.name); + var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined); ts.setEmitFlags(declarationName, 48 /* NoSourceMap */); // `expressionName` is the name of the parameter used in expressions. - var expressionName = ts.getSynthesizedClone(parameter.name); + var expressionName = parameter.name.kind === 72 /* Identifier */ ? ts.getSynthesizedClone(parameter.name) : declarationName; var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; @@ -71506,6 +71947,11 @@ var ts; ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); statements.push(forStatement); + if (parameter.name.kind !== 72 /* Identifier */) { + // do the actual destructuring of the rest parameter if necessary + statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */)); + } } /** * Adds a statement to capture the `this` of a function declaration if it is needed. @@ -79741,6 +80187,7 @@ var ts; case 241 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; + case 166 /* ConstructorType */: case 161 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; @@ -79759,6 +80206,7 @@ var ts; diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; + case 165 /* FunctionType */: case 239 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; @@ -80336,7 +80784,10 @@ var ts; if (!ts.isLateVisibilityPaintedStatement(i)) { return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); } + var priorNeedsDeclare = needsDeclare; + needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + needsDeclare = priorNeedsDeclare; lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); } // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list @@ -80699,7 +81150,8 @@ var ts; var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression - var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 + var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default"; + var newId_1 = ts.createOptimisticUniqueName(oldId + "_base"); getSymbolAccessibilityDiagnostic = function () { return ({ diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: extendsClause_1, @@ -80853,7 +81305,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_9 = function (range) { + var _loop_10 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -80867,7 +81319,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_9(range); + _loop_10(range); } } return prop; @@ -82757,18 +83209,22 @@ var ts; function emitPropertyAccessExpression(node) { var indentBeforeDot = false; var indentAfterDot = false; + var dotRangeFirstCommentStart = ts.skipTrivia(currentSourceFile.text, node.expression.end, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ true); + var dotRangeStart = ts.skipTrivia(currentSourceFile.text, dotRangeFirstCommentStart); + var dotRangeEnd = dotRangeStart + 1; if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { - var dotRangeStart = node.expression.end; - var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; var dotToken = ts.createToken(24 /* DotToken */); - dotToken.pos = dotRangeStart; + dotToken.pos = node.expression.end; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } emitExpression(node.expression); increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + var dotHasCommentTrivia = dotRangeFirstCommentStart !== dotRangeStart; + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression, dotHasCommentTrivia); if (shouldEmitDotDot) { writePunctuation("."); } @@ -82779,13 +83235,15 @@ var ts; } // 1..toString is a valid property access, emit a dot after the literal // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal - function needsDotDotForPropertyAccess(expression) { + function needsDotDotForPropertyAccess(expression, dotHasTrivia) { expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); - return !expression.numericLiteralFlags - && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); + // If he number will be printed verbatim and it doesn't already contain a dot, add one + // if the expression doesn't have any comments that will be emitted. + return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)) && + (!dotHasTrivia || printerOptions.removeComments); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -83536,6 +83994,7 @@ var ts; function emitJsxSelfClosingElement(node) { writePunctuation("<"); emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); writeSpace(); emit(node.attributes); writePunctuation("/>"); @@ -83549,6 +84008,7 @@ var ts; writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } @@ -85154,7 +85614,7 @@ var ts; if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { return; } - var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character; sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, /*nameIndex*/ undefined); } @@ -85563,7 +86023,7 @@ var ts; }, flags); } function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { - return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2); } function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); @@ -85644,7 +86104,7 @@ var ts; var text; try { ts.performance.mark("beforeIORead"); - text = system.readFile(fileName, options.charset); + text = compilerHost.readFile(fileName); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -85670,7 +86130,12 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - system.createDirectory(directoryPath); + if (compilerHost.createDirectory) { + compilerHost.createDirectory(directoryPath); + } + else { + system.createDirectory(directoryPath); + } } } var outputFingerprints; @@ -85722,7 +86187,7 @@ var ts; } var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); var realpath = system.realpath && (function (path) { return system.realpath(path); }); - return { + var compilerHost = { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -85738,10 +86203,112 @@ var ts; getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }, + createDirectory: function (d) { return system.createDirectory(d); } }; + return compilerHost; } ts.createCompilerHostWorker = createCompilerHostWorker; + /*@internal*/ + function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) { + var originalReadFile = host.readFile; + var originalFileExists = host.fileExists; + var originalDirectoryExists = host.directoryExists; + var originalCreateDirectory = host.createDirectory; + var originalWriteFile = host.writeFile; + var readFileCache = ts.createMap(); + var fileExistsCache = ts.createMap(); + var directoryExistsCache = ts.createMap(); + var sourceFileCache = ts.createMap(); + var readFileWithCache = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value || undefined; + return setReadFileCache(key, fileName); + }; + var setReadFileCache = function (key, fileName) { + var newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue || false); + return newValue; + }; + host.readFile = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value; // could be .d.ts from output + if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) { + return originalReadFile.call(host, fileName); + } + return setReadFileCache(key, fileName); + }; + var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { + var key = toPath(fileName); + var value = sourceFileCache.get(key); + if (value) + return value; + var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile); + if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) { + sourceFileCache.set(key, sourceFile); + } + return sourceFile; + } : undefined; + // fileExists for any kind of extension + host.fileExists = function (fileName) { + var key = toPath(fileName); + var value = fileExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + if (originalWriteFile) { + host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) { + var key = toPath(fileName); + fileExistsCache.delete(key); + var value = readFileCache.get(key); + if (value && value !== data) { + readFileCache.delete(key); + sourceFileCache.delete(key); + } + else if (getSourceFileWithCache) { + var sourceFile = sourceFileCache.get(key); + if (sourceFile && sourceFile.text !== data) { + sourceFileCache.delete(key); + } + } + originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles); + }; + } + // directoryExists + if (originalDirectoryExists && originalCreateDirectory) { + host.directoryExists = function (directory) { + var key = toPath(directory); + var value = directoryExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + return { + originalReadFile: originalReadFile, + originalFileExists: originalFileExists, + originalDirectoryExists: originalDirectoryExists, + originalCreateDirectory: originalCreateDirectory, + originalWriteFile: originalWriteFile, + getSourceFileWithCache: getSourceFileWithCache, + readFileWithCache: readFileWithCache + }; + } + ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (ts.getEmitDeclarations(program.getCompilerOptions())) { @@ -86074,7 +86641,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); - var configParsingHost = parseConfigHostFromCompilerHost(host); + var configParsingHost = parseConfigHostFromCompilerHostLike(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); @@ -86120,6 +86687,12 @@ var ts; var sourceFileToPackageName = ts.createMap(); // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. var redirectTargetsMap = ts.createMultiMap(); + /** + * map with + * - SourceFile if present + * - false if sourceFile missing for source of project reference redirect + * - undefined otherwise + */ var filesByName = ts.createMap(); var missingFilePaths; // stores 'filename -> file association' ignoring case @@ -86180,7 +86753,10 @@ var ts; }); } } - missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) { + var path = _a[0], file = _a[1]; + return file === undefined ? path : undefined; + })); files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); processingDefaultLibFiles = undefined; processingOtherFiles = undefined; @@ -86326,13 +86902,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_5 = []; + var result_6 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_5.push(resolvedModule); + result_6.push(resolvedModule); } - return result_5; + return result_6; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -86788,7 +87364,7 @@ var ts; return getSourceFileByPath(toPath(fileName)); } function getSourceFileByPath(path) { - return filesByName.get(path); + return filesByName.get(path) || undefined; } function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { if (sourceFile) { @@ -87266,7 +87842,7 @@ var ts; } /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ function getSourceFileFromReference(referencingFile, ref) { - return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; }); } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { @@ -87372,7 +87948,9 @@ var ts; processReferencedFiles(file_1, isDefaultLib); processTypeReferenceDirectives(file_1); } - processLibReferenceDirectives(file_1); + if (!options.noLib) { + processLibReferenceDirectives(file_1); + } modulesWithElidedImports.set(file_1.path, false); processImportedModules(file_1); } @@ -87383,7 +87961,7 @@ var ts; processImportedModules(file_1); } } - return file_1; + return file_1 || undefined; } var redirectedPath; if (refFile) { @@ -87449,7 +88027,9 @@ var ts; processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } - processLibReferenceDirectives(file); + if (!options.noLib) { + processLibReferenceDirectives(file); + } // always process imported modules to record module name resolutions processImportedModules(file); if (isDefaultLib) { @@ -87462,9 +88042,12 @@ var ts; return file; } function addFileToFilesByName(file, path, redirectedPath) { - filesByName.set(path, file); if (redirectedPath) { filesByName.set(redirectedPath, file); + filesByName.set(path, file || false); + } + else { + filesByName.set(path, file); } } function getProjectReferenceRedirect(fileName) { @@ -88127,21 +88710,22 @@ var ts; } ts.createProgram = createProgram; /* @internal */ - function parseConfigHostFromCompilerHost(host) { + function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) { + if (directoryStructureHost === void 0) { directoryStructureHost = host; } return { - fileExists: function (f) { return host.fileExists(f); }, + fileExists: function (f) { return directoryStructureHost.fileExists(f); }, readDirectory: function (root, extensions, excludes, includes, depth) { - ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(root, extensions, excludes, includes, depth); + ts.Debug.assertDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); }, - readFile: function (f) { return host.readFile(f); }, + readFile: function (f) { return directoryStructureHost.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, - onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }), trace: host.trace ? function (s) { return host.trace(s); } : undefined }; } - ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike; function resolveProjectReferencePath(hostOrRef, ref) { var passedInRef = ref ? ref : hostOrRef; return ts.resolveConfigFileProjectName(passedInRef.path); @@ -88208,6 +88792,10 @@ var ts; } } ts.getFileEmitOutput = getFileEmitOutput; + function cloneMapOrUndefined(map) { + return map ? ts.cloneMap(map) : undefined; + } + ts.cloneMapOrUndefined = cloneMapOrUndefined; })(ts || (ts = {})); /*@internal*/ (function (ts) { @@ -88355,12 +88943,35 @@ var ts; fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, - allFilesExcludingDefaultLibraryFile: undefined, - allFileNames: undefined + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature }; } BuilderState.create = create; + /** + * Releases needed properties + */ + function releaseCache(state) { + state.allFilesExcludingDefaultLibraryFile = undefined; + state.allFileNames = undefined; + } + BuilderState.releaseCache = releaseCache; + /** + * Creates a clone of the state + */ + function clone(state) { + var fileInfos = ts.createMap(); + state.fileInfos.forEach(function (value, key) { + fileInfos.set(key, __assign({}, value)); + }); + // Dont need to backup allFiles info since its cache anyway + return { + fileInfos: fileInfos, + referencedMap: ts.cloneMapOrUndefined(state.referencedMap), + exportedModulesMap: ts.cloneMapOrUndefined(state.exportedModulesMap), + hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature), + }; + } + BuilderState.clone = clone; /** * Gets the files affected by the path from the program */ @@ -88609,7 +89220,7 @@ var ts; var seenFileNamesMap = ts.createMap(); // Start with the paths this file was referenced by seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); - var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath); while (queue.length > 0) { var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { @@ -88617,7 +89228,7 @@ var ts; seenFileNamesMap.set(currentPath, currentSourceFile); if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 queue.push.apply(// TODO: GH#18217 - queue, getReferencedByPaths(state, currentPath)); + queue, getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } } @@ -88641,24 +89252,32 @@ var ts; var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); - if (!compilerOptions.outFile && !compilerOptions.out) { + state.compilerOptions = compilerOptions; + // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them + // With --isolatedModules, emitting changed file doesnt emit dependent files so we cant know of dependent files to retrieve errors so dont cache the errors + if (!compilerOptions.outFile && !compilerOptions.out && !compilerOptions.isolatedModules) { state.semanticDiagnosticsPerFile = ts.createMap(); } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; + var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { - ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + var affectedSignatures = oldState.currentAffectedFilesSignatures; + ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); } if (canCopySemanticDiagnostics) { ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); } // Copy old state's changed files set ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit; + state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; + } } // Update changed files and copy semantic diagnostics if we can var referencedMap = state.referencedMap; @@ -88682,7 +89301,7 @@ var ts; state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { - var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + var sourceFile = newProgram.getSourceFileByPath(sourceFilePath); if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { return; } @@ -88702,6 +89321,36 @@ var ts; }); return state; } + /** + * Releases program and other related not needed properties + */ + function releaseCache(state) { + ts.BuilderState.releaseCache(state); + state.program = undefined; + } + /** + * Creates a clone of the state + */ + function cloneBuilderProgramState(state) { + var newState = ts.BuilderState.clone(state); + newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile); + newState.changedFilesSet = ts.cloneMap(state.changedFilesSet); + newState.affectedFiles = state.affectedFiles; + newState.affectedFilesIndex = state.affectedFilesIndex; + newState.currentChangedFilePath = state.currentChangedFilePath; + newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures); + newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap); + newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles); + newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; + newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState); + newState.program = state.program; + newState.compilerOptions = state.compilerOptions; + newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit; + newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; + newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles); + newState.programEmitComplete = state.programEmitComplete; + return newState; + } /** * Verifies that source file is ok to be used in calls that arent handled by next */ @@ -88748,22 +89397,43 @@ var ts; } // With --out or --outFile all outputs go into single file // so operations are performed directly on program, return program - var compilerOptions = state.program.getCompilerOptions(); + var program = ts.Debug.assertDefined(state.program); + var compilerOptions = program.getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); - return state.program; + return program; } // Get next batch of affected files state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); if (state.exportedModulesMap) { state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); } - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); } } + /** + * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet + */ + function getNextAffectedFilePendingEmit(state) { + var affectedFilesPendingEmit = state.affectedFilesPendingEmit; + if (affectedFilesPendingEmit) { + var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap()); + for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) { + var affectedFile = ts.Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]); + if (affectedFile && !seenEmittedFiles.has(affectedFile.path)) { + // emit this file + state.affectedFilesPendingEmitIndex = i; + return affectedFile; + } + } + state.affectedFilesPendingEmit = undefined; + state.affectedFilesPendingEmitIndex = undefined; + } + return undefined; + } /** * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file */ @@ -88775,9 +89445,10 @@ var ts; // Clean lib file diagnostics if its all files excluding default files to emit if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { state.cleanedDiagnosticsOfLibFiles = true; - var options_2 = state.program.getCompilerOptions(); - if (ts.forEach(state.program.getSourceFiles(), function (f) { - return state.program.isSourceFileDefaultLibrary(f) && + var program_1 = ts.Debug.assertDefined(state.program); + var options_2 = program_1.getCompilerOptions(); + if (ts.forEach(program_1.getSourceFiles(), function (f) { + return program_1.isSourceFileDefaultLibrary(f) && !ts.skipTypeChecking(f, options_2) && removeSemanticDiagnosticsOf(state, f.path); })) { @@ -88838,11 +89509,20 @@ var ts; return true; } // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected - return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(filePath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); - }); + })) { + return true; + } + // Remove diagnostics of files that import this file (without going to exports of referencing files) + return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) { + return referencesInFile.has(filePath) && + !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file + removeSemanticDiagnosticsOf(state, referencingFilePath); + } // Dont add to seen since this is not yet done with the export removal + ); } /** * Removes semantic diagnostics for path and @@ -88860,20 +89540,26 @@ var ts; * This is called after completing operation on the next affected file. * The operations here are postponed to ensure that cancellation during the iteration is handled correctly */ - function doneWithAffectedFile(state, affected) { + function doneWithAffectedFile(state, affected, isPendingEmit) { if (affected === state.program) { state.changedFilesSet.clear(); + state.programEmitComplete = true; } else { state.seenAffectedFiles.set(affected.path, true); - state.affectedFilesIndex++; + if (isPendingEmit) { + state.affectedFilesPendingEmitIndex++; + } + else { + state.affectedFilesIndex++; + } } } /** * Returns the result with affected file */ - function toAffectedFileResult(state, result, affected) { - doneWithAffectedFile(state, affected); + function toAffectedFileResult(state, result, affected, isPendingEmit) { + doneWithAffectedFile(state, affected, isPendingEmit); return { result: result, affected: affected }; } /** @@ -88882,14 +89568,18 @@ var ts; */ function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { var path = sourceFile.path; - var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - return cachedDiagnostics; + if (state.semanticDiagnosticsPerFile) { + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } } // Diagnostics werent cached, get them from program, and cache the result - var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); - state.semanticDiagnosticsPerFile.set(path, diagnostics); + var diagnostics = ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); + if (state.semanticDiagnosticsPerFile) { + state.semanticDiagnosticsPerFile.set(path, diagnostics); + } return diagnostics; } var BuilderProgramKind; @@ -88914,7 +89604,7 @@ var ts; rootNames: newProgramOrRootNames, options: hostOrOptions, host: oldProgramOrHost, - oldProgram: oldProgram && oldProgram.getProgram(), + oldProgram: oldProgram && oldProgram.getProgramOrUndefined(), configFileParsingDiagnostics: configFileParsingDiagnostics, projectReferences: projectReferences }); @@ -88945,26 +89635,29 @@ var ts; /** * Computing hash to for signature verification */ - var computeHash = host.createHash || ts.identity; + var computeHash = host.createHash || ts.generateDjb2Hash; var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + var backupState; // To ensure that we arent storing any references to old program or new program without state newProgram = undefined; // TODO: GH#18217 oldProgram = undefined; oldState = undefined; - var result = { - getState: function () { return state; }, - getProgram: function () { return state.program; }, - getCompilerOptions: function () { return state.program.getCompilerOptions(); }, - getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, - getSourceFiles: function () { return state.program.getSourceFiles(); }, - getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, - getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, - getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, - getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, - getSemanticDiagnostics: getSemanticDiagnostics, - emit: emit, - getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, - getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + var result = createRedirectedBuilderProgram(state, configFileParsingDiagnostics); + result.getState = function () { return state; }; + result.backupState = function () { + ts.Debug.assert(backupState === undefined); + backupState = cloneBuilderProgramState(state); + }; + result.restoreState = function () { + state = ts.Debug.assertDefined(backupState); + backupState = undefined; + }; + result.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.assertDefined(state.program), sourceFile); }; + result.getSemanticDiagnostics = getSemanticDiagnostics; + result.emit = emit; + result.releaseProgram = function () { + releaseCache(state); + backupState = undefined; }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; @@ -88983,14 +89676,33 @@ var ts; */ function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { var affected = getNextAffectedFile(state, cancellationToken, computeHash); + var isPendingEmitFile = false; if (!affected) { - // Done - return undefined; + if (!state.compilerOptions.out && !state.compilerOptions.outFile) { + affected = getNextAffectedFilePendingEmit(state); + if (!affected) { + return undefined; + } + isPendingEmitFile = true; + } + else { + var program = ts.Debug.assertDefined(state.program); + // Check if program uses any prepend project references, if thats the case we cant track of the js files of those, so emit even though there are no changes + if (state.programEmitComplete || !ts.some(program.getProjectReferences(), function (ref) { return !!ref.prepend; })) { + state.programEmitComplete = true; + return undefined; + } + affected = program; + } + } + // Mark seen emitted files if there are pending files to be emitted + if (state.affectedFilesPendingEmit && state.program !== affected) { + (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.path, true); } return toAffectedFileResult(state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file - state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + ts.Debug.assertDefined(state.program).emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected, isPendingEmitFile); } /** * Emits the JavaScript and declaration files. @@ -89027,7 +89739,7 @@ var ts; }; } } - return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return ts.Debug.assertDefined(state.program).emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); } /** * Return the semantic diagnostics for the next affected file or undefined if iteration is complete @@ -89063,25 +89775,38 @@ var ts; */ function getSemanticDiagnostics(sourceFile, cancellationToken) { assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); - var compilerOptions = state.program.getCompilerOptions(); + var compilerOptions = ts.Debug.assertDefined(state.program).getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); // We dont need to cache the diagnostics just return them from program - return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + return ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); } if (sourceFile) { return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); } - if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { - // When semantic builder asks for diagnostics of the whole program, - // ensure that all the affected files are handled - var affected = void 0; - while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { - doneWithAffectedFile(state, affected); + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected; + var affectedFilesPendingEmit; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + if (affected !== state.program && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push(affected.path); + } + doneWithAffectedFile(state, affected); + } + // In case of emit builder, cache the files to be emitted + if (affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, affectedFilesPendingEmit); + // affectedFilesPendingEmitIndex === undefined + // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files + // so start from 0 as array would be affectedFilesPendingEmit + // else, continue to iterate from existing index, the current set is appended to existing files + if (state.affectedFilesPendingEmitIndex === undefined) { + state.affectedFilesPendingEmitIndex = 0; } } var diagnostics; - for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { var sourceFile_2 = _a[_i]; diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); } @@ -89089,6 +89814,32 @@ var ts; } } ts.createBuilderProgram = createBuilderProgram; + function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { + return { + getState: ts.notImplemented, + backupState: ts.noop, + restoreState: ts.noop, + getProgram: getProgram, + getProgramOrUndefined: function () { return state.program; }, + releaseProgram: function () { return state.program = undefined; }, + getCompilerOptions: function () { return state.compilerOptions; }, + getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); }, + getSourceFiles: function () { return getProgram().getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); }, + emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); }, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); } + }; + function getProgram() { + return ts.Debug.assertDefined(state.program); + } + } + ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram; })(ts || (ts = {})); (function (ts) { function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { @@ -89100,23 +89851,8 @@ var ts; } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; - return { - // Only return program, all other methods are not implemented - getProgram: function () { return program; }, - getState: ts.notImplemented, - getCompilerOptions: ts.notImplemented, - getSourceFile: ts.notImplemented, - getSourceFiles: ts.notImplemented, - getOptionsDiagnostics: ts.notImplemented, - getGlobalDiagnostics: ts.notImplemented, - getConfigFileParsingDiagnostics: ts.notImplemented, - getSyntacticDiagnostics: ts.notImplemented, - getSemanticDiagnostics: ts.notImplemented, - emit: ts.notImplemented, - getAllDependencies: ts.notImplemented, - getCurrentDirectory: ts.notImplemented - }; + var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics; + return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics); } ts.createAbstractBuilder = createAbstractBuilder; })(ts || (ts = {})); @@ -89920,7 +90656,7 @@ var ts; if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { return; // Don't want to a package to globally import from itself } - var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); if (target === undefined) return; var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); @@ -90295,37 +91031,103 @@ var ts; var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); return { onWatchStatusChange: onWatchStatusChange, - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + watchFile: ts.maybeBind(system, system.watchFile) || (function () { return noopFileWatcher; }), + watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return noopFileWatcher; }), + setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop, + clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop }; } ts.createWatchHost = createWatchHost; + var WatchType; + (function (WatchType) { + WatchType["ConfigFile"] = "Config file"; + WatchType["SourceFile"] = "Source file"; + WatchType["MissingFile"] = "Missing file"; + WatchType["WildcardDirectory"] = "Wild card directory"; + WatchType["FailedLookupLocations"] = "Failed Lookup Locations"; + WatchType["TypeRoots"] = "Type roots"; + })(WatchType = ts.WatchType || (ts.WatchType = {})); + function createWatchFactory(host, options) { + var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop; + var result = ts.getWatchFactory(watchLogLevel, writeLog); + result.writeLog = writeLog; + return result; + } + ts.createWatchFactory = createWatchFactory; + function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) { + if (directoryStructureHost === void 0) { directoryStructureHost = host; } + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); }); + return { + getSourceFile: function (fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, getCompilerOptions().charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + }, + getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); }, + fileExists: function (f) { return host.fileExists(f); }, + readFile: function (f) { return host.readFile(f); }, + trace: ts.maybeBind(host, host.trace), + directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: ts.maybeBind(host, host.realpath), + getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }), + createHash: ts.maybeBind(host, host.createHash), + readDirectory: ts.maybeBind(host, host.readDirectory), + }; + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + if (host.createDirectory) + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ - function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { - if (system === void 0) { system = ts.sys; } - if (!createProgram) { - createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; - } + function createProgramHost(system, createProgram) { + var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); }); var host = system; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) - var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; - var writeFileName = function (s) { return system.write(s + system.newLine); }; - var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getNewLine: function () { return system.newLine; }, - getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, fileExists: function (path) { return system.fileExists(path); }, @@ -90333,29 +91135,31 @@ var ts; directoryExists: function (path) { return system.directoryExists(path); }, getDirectories: function (path) { return system.getDirectories(path); }, readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, - realpath: system.realpath && (function (path) { return system.realpath(path); }), - getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: watchFile, - watchDirectory: watchDirectory, - setTimeout: setTimeout, - clearTimeout: clearTimeout, - trace: function (s) { return system.write(s); }, - onWatchStatusChange: onWatchStatusChange, + realpath: ts.maybeBind(system, system.realpath), + getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable), + trace: function (s) { return system.write(s + system.newLine); }, createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, - createHash: system.createHash && (function (s) { return system.createHash(s); }), - createProgram: createProgram, - afterProgramCreate: emitFilesAndReportErrorUsingBuilder + createHash: ts.maybeBind(system, system.createHash), + createProgram: createProgram }; - function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); - } - function emitFilesAndReportErrorUsingBuilder(builderProgram) { + } + ts.createProgramHost = createProgramHost; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var writeFileName = function (s) { return system.write(s + system.newLine); }; + var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram); + ts.copyProperties(result, createWatchHost(system, reportWatchStatus)); + result.afterProgramCreate = function (builderProgram) { var compilerOptions = builderProgram.getCompilerOptions(); var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); - } + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); + }; + return result; } /** * Report error and exit @@ -90411,8 +91215,6 @@ var ts; var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); var currentDirectory = host.getCurrentDirectory(); - var getCurrentDirectory = function () { return currentDirectory; }; - var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; @@ -90424,15 +91226,7 @@ var ts; host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } var directoryStructureHost = cachedDirectoryStructureHost || host; - var parseConfigFileHost = { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, - fileExists: function (path) { return host.fileExists(path); }, - readFile: readFile, - getCurrentDirectory: getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, - trace: host.trace ? function (s) { return host.trace(s); } : undefined - }; + var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost); // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); if (configFileName && host.configFileParsingResult) { @@ -90446,52 +91240,40 @@ var ts; parseConfigFile(); newLine = updateNewLine(); } - var trace = host.trace && (function (s) { host.trace(s + newLine); }); - var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : - compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; - var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 - var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; + var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); } - var compilerHost = { - // Members for CompilerHost - getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, - getSourceFileByPath: getVersionedSourceFileByPath, - getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), - getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, - writeFile: writeFile, - getCurrentDirectory: getCurrentDirectory, - useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, - getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return newLine; }, - fileExists: fileExists, - readFile: readFile, - trace: trace, - directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), - getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), - realpath: host.realpath && (function (s) { return host.realpath(s); }), - getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), - onReleaseOldSourceFile: onReleaseOldSourceFile, - createHash: host.createHash && (function (data) { return host.createHash(data); }), - // Members for ResolutionCacheHost - toPath: toPath, - getCompilationSettings: function () { return compilerOptions; }, - watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, - watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, - getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, - onInvalidatedResolution: scheduleProgramUpdate, - onChangedAutomaticTypeDirectiveNames: function () { - hasChangedAutomaticTypeDirectiveNames = true; - scheduleProgramUpdate(); - }, - maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, - getCurrentProgram: getCurrentProgram, - writeLog: writeLog, - readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost); + // Members for CompilerHost + var getNewSourceFile = compilerHost.getSourceFile; + compilerHost.getSourceFile = function (fileName) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return getVersionedSourceFileByPath.apply(void 0, [fileName, toPath(fileName)].concat(args)); }; + compilerHost.getSourceFileByPath = getVersionedSourceFileByPath; + compilerHost.getNewLine = function () { return newLine; }; + compilerHost.fileExists = fileExists; + compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + // Members for ResolutionCacheHost + compilerHost.toPath = toPath; + compilerHost.getCompilationSettings = function () { return compilerOptions; }; + compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations" /* FailedLookupLocations */); }; + compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots" /* TypeRoots */); }; + compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; + compilerHost.onInvalidatedResolution = scheduleProgramUpdate; + compilerHost.onChangedAutomaticTypeDirectiveNames = function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }; + compilerHost.maxNumberOfFilesToIterateForInvalidation = host.maxNumberOfFilesToIterateForInvalidation; + compilerHost.getCurrentProgram = getCurrentProgram; + compilerHost.writeLog = writeLog; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -90544,11 +91326,9 @@ var ts; } function createNewProgram(program, hasInvalidatedResolution) { // Compile the program - if (watchLogLevel !== ts.WatchLogLevel.None) { - writeLog("CreatingProgramWith::"); - writeLog(" roots: " + JSON.stringify(rootFileNames)); - writeLog(" options: " + JSON.stringify(compilerOptions)); - } + writeLog("CreatingProgramWith::"); + writeLog(" roots: " + JSON.stringify(rootFileNames)); + writeLog(" options: " + JSON.stringify(compilerOptions)); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -90611,7 +91391,7 @@ var ts; } // Create new source file if requested or the versions dont match if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { - var sourceFile = getNewSourceFile(); + var sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { if (shouldCreateNewSourceFile) { hostSourceFile.version++; @@ -90621,7 +91401,7 @@ var ts; hostSourceFile.sourceFile = sourceFile; sourceFile.version = hostSourceFile.version.toString(); if (!hostSourceFile.fileWatcher) { - hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); } } else { @@ -90635,7 +91415,7 @@ var ts; else { if (sourceFile) { sourceFile.version = initialVersion.toString(); - var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); } else { @@ -90645,21 +91425,6 @@ var ts; return sourceFile; } return hostSourceFile.sourceFile; - function getNewSourceFile() { - var text; - try { - ts.performance.mark("beforeIORead"); - text = host.readFile(fileName, compilerOptions.charset); - ts.performance.mark("afterIORead"); - ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; - } } function nextSourceFileVersion(path) { var hostSourceFile = sourceFilesCache.get(path); @@ -90786,7 +91551,7 @@ var ts; } } function watchMissingFilePath(missingFilePath) { - return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file"); + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file" /* MissingFile */); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -90830,28 +91595,7 @@ var ts; // Schedule Update the program scheduleProgramUpdate(); } - }, flags, "Wild card directories"); - } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - host.createDirectory(directoryPath); - } - } - function writeFile(fileName, text, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } + }, flags, "Wild card directory" /* WildcardDirectory */); } } ts.createWatchProgram = createWatchProgram; @@ -91020,9 +91764,8 @@ var ts; }; } ts.createBuilderStatusReporter = createBuilderStatusReporter; - function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { - if (system === void 0) { system = ts.sys; } - var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) { + var host = ts.createProgramHost(system, createProgram); host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; @@ -91030,21 +91773,18 @@ var ts; host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); return host; } - function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { if (system === void 0) { system = ts.sys; } - var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus); host.reportErrorSummary = reportErrorSummary; return host; } ts.createSolutionBuilderHost = createSolutionBuilderHost; - function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { - var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus); var watchHost = ts.createWatchHost(system, reportWatchStatus); - host.onWatchStatusChange = watchHost.onWatchStatusChange; - host.watchFile = watchHost.watchFile; - host.watchDirectory = watchHost.watchDirectory; - host.setTimeout = watchHost.setTimeout; - host.clearTimeout = watchHost.clearTimeout; + ts.copyProperties(host, watchHost); return host; } ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; @@ -91059,7 +91799,7 @@ var ts; var hostWithWatch = host; var currentDirectory = host.getCurrentDirectory(); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host); // State of the solution var options = defaultOptions; var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); @@ -91071,7 +91811,14 @@ var ts; var missingRoots = ts.createMap(); var globalDependencyGraph; var writeFileName = function (s) { return host.trace && host.trace(s); }; + var readFileWithCache = function (f) { return host.readFile(f); }; + var projectCompilerOptions = baseCompilerOptions; + var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; }); + var originalGetSourceFile = compilerHost.getSourceFile; + var computeHash = host.createHash || ts.generateDjb2Hash; + updateGetSourceFile(); // Watch state + var builderPrograms = createFileMap(toPath); var diagnostics = createFileMap(toPath); var projectPendingBuild = createFileMap(toPath); var projectErrorsReported = createFileMap(toPath); @@ -91079,6 +91826,7 @@ var ts; var nextProjectToBuild = 0; var timerToBuildInvalidatedProject; var reportFileChangeDetected = false; + var _a = ts.createWatchFactory(host, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; // Watches for the solution var allWatchedWildcardDirectories = createFileMap(toPath); var allWatchedInputFiles = createFileMap(toPath); @@ -91119,6 +91867,30 @@ var ts; ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + builderPrograms.clear(); + updateGetSourceFile(); + } + function updateGetSourceFile() { + if (options.watch) { + if (compilerHost.getSourceFile === originalGetSourceFile) { + compilerHost.getSourceFile = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); + if (result && options.watch) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + } + else { + if (compilerHost.getSourceFile !== originalGetSourceFile) { + compilerHost.getSourceFile = originalGetSourceFile; + } + } } function isParsedCommandLine(entry) { return !!entry.options; @@ -91168,36 +91940,34 @@ var ts; } function watchConfigFile(resolved) { if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { - allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + allWatchedConfigFiles.setValue(resolved, watchFile(hostWithWatch, resolved, function () { invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); - })); + }, ts.PollingInterval.High, "Config file" /* ConfigFile */, resolved)); } } function watchWildCardDirectories(resolved, parsed) { if (!options.watch) return; ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { - return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + return watchDirectory(hostWithWatch, dir, function (fileOrDirectory) { var fileOrDirectoryPath = toPath(fileOrDirectory); if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { - // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory); return; } if (isOutputFile(fileOrDirectory, parsed)) { - // writeLog(`${fileOrDirectory} is output file`); + writeLog(fileOrDirectory + " is output file"); return; } invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); - }, !!(flags & 1 /* Recursive */)); + }, flags, "Wild card directory" /* WildcardDirectory */, resolved); }); } function watchInputFiles(resolved, parsed) { if (!options.watch) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { - createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); - }); }, + createNewValue: function (path, input) { return watchFilePath(hostWithWatch, input, function () { return invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, path, "Source file" /* SourceFile */, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -91517,18 +92287,39 @@ var ts; reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); return; } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes) { + // Fake that files have been built by updating output file stamps + updateOutputTimestamps(proj); + return; + } var buildResult = buildSingleProject(resolved); - var dependencyGraph = getGlobalDependencyGraph(); - var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (buildResult & BuildResultFlags.AnyErrors) + return; + var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue; + var referencingProjects = referencingProjectsMap.getValue(resolved); if (!referencingProjects) return; // Always use build order to queue projects - for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { - var project = _a[_i]; + for (var index = buildQueue.indexOf(resolved) + 1; index < buildQueue.length; index++) { + var project = buildQueue[index]; var prepend = referencingProjects.getValue(project); - // If the project is referenced with prepend, always build downstream projectm, - // otherwise queue it only if declaration output changed - if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + if (prepend !== undefined) { + // If the project is referenced with prepend, always build downstream projects, + // If declaration output is changed, build the project + // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps + var status_1 = projectStatus.getValue(project); + if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { + if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) { + projectStatus.setValue(project, { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: status_1.oldestOutputFileName, + newerProjectName: resolved + }); + } + } + else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) { + status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes; + } addProjToQueue(project); } } @@ -91599,98 +92390,118 @@ var ts; // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } - var programOptions = { - projectReferences: configFile.projectReferences, - host: host, - rootNames: configFile.fileNames, - options: configFile.options, - configFileParsingDiagnostics: configFile.errors - }; - if (host.beforeCreateProgram) { - host.beforeCreateProgram(options); - } - var program = ts.createProgram(programOptions); + // TODO: handle resolve module name to cache result in project reference redirect + projectCompilerOptions = configFile.options; + var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences); + projectCompilerOptions = baseCompilerOptions; // Don't emit anything in the presence of syntactic errors or options diagnostics - var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } - // Don't emit .d.ts if there are decl file errors - if (ts.getEmitDeclarations(program.getCompilerOptions())) { - var declDiagnostics = program.getDeclarationDiagnostics(); - if (declDiagnostics.length) { - return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); - } - } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } + // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly + program.backupState(); var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - var emitDiagnostics; - var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; - ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { + var declDiagnostics; + var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; + var outputFiles = []; + ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }); + // Don't emit .d.ts if there are decl file errors + if (declDiagnostics) { + program.restoreState(); + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); + } + // Actual Emit + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emittedOutputs = createFileMap(toPath); + outputFiles.forEach(function (_a) { + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName)) { + if (!anyDtsChanged && isDeclarationFile(name)) { // Check for unchanged .d.ts files - if (host.fileExists(fileName) && host.readFile(fileName) === content) { - priorChangeTime = host.getModifiedTime(fileName); + if (host.fileExists(name) && readFileWithCache(name) === text) { + priorChangeTime = host.getModifiedTime(name); } else { resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + emittedOutputs.setValue(name, true); + ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(name, priorChangeTime); } }); - if (emitDiagnostics) { + var emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); } + // Update time stamps for rest of the outputs + newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(configFile, newestDeclarationFileContentChangedTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); var status = { type: UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime, + oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile) }; diagnostics.removeKey(proj); projectStatus.setValue(proj, status); - if (host.afterProgramEmitAndDiagnostics) { - host.afterProgramEmitAndDiagnostics(program); - } + afterProgramCreate(proj, program); return resultFlags; function buildErrors(diagnostics, errorFlags, errorType) { resultFlags |= errorFlags; reportAndStoreErrors(proj, diagnostics); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); - if (host.afterProgramEmitAndDiagnostics) { - host.afterProgramEmitAndDiagnostics(program); - } + afterProgramCreate(proj, program); return resultFlags; } } + function afterProgramCreate(proj, program) { + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + if (options.watch) { + program.releaseProgram(); + builderPrograms.setValue(proj, program); + } + } function updateOutputTimestamps(proj) { if (options.dry) { return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (options.verbose) { - reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); - } - var now = new Date(); - var outputs = getAllProjectOutputs(proj); - var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { - var file = outputs_2[_i]; - if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); - } - host.setModifiedTime(file, now); - } + var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } + function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { + var outputs = getAllProjectOutputs(proj); + if (!skipOutputs || outputs.length !== skipOutputs.getSize()) { + if (options.verbose) { + reportStatus(verboseMessage, proj.options.configFilePath); + } + var now = host.now ? host.now() : new Date(); + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; + if (skipOutputs && skipOutputs.hasKey(file)) { + continue; + } + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + } + host.setModifiedTime(file, now); + if (proj.options.listEmittedFiles) { + writeFileName("TSFILE: " + file); + } + } + } + return priorNewestUpdateTime; + } function getFilesToClean() { // Get the same graph for cleaning we'd use for building var graph = getGlobalDependencyGraph(); @@ -91735,11 +92546,24 @@ var ts; if (options.watch) { reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); } + // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api + // Override readFile for json files and output .d.ts to cache the text + var savedReadFileWithCache = readFileWithCache; + var savedGetSourceFile = compilerHost.getSourceFile; + var _a = ts.changeCompilerHostLikeToUseCache(host, toPath, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return savedGetSourceFile.call.apply(savedGetSourceFile, [compilerHost].concat(args)); + }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, newReadFileWithCache = _a.readFileWithCache; + readFileWithCache = newReadFileWithCache; + compilerHost.getSourceFile = getSourceFileWithCache; var graph = getGlobalDependencyGraph(); reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; + for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) { + var next = _b[_i]; var proj = parseConfigFile(next); if (proj === undefined) { reportParseConfigFileDiagnostic(next); @@ -91781,6 +92605,13 @@ var ts; anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } reportErrorSummary(); + host.readFile = originalReadFile; + host.fileExists = originalFileExists; + host.directoryExists = originalDirectoryExists; + host.createDirectory = originalCreateDirectory; + host.writeFile = originalWriteFile; + compilerHost.getSourceFile = savedGetSourceFile; + readFileWithCache = savedReadFileWithCache; return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } function reportParseConfigFileDiagnostic(proj) { @@ -91803,7 +92634,7 @@ var ts; } } function relName(path) { - return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode @@ -91836,6 +92667,19 @@ var ts; } } ts.getAllProjectOutputs = getAllProjectOutputs; + function getFirstProjectOutput(project) { + if (project.options.outFile || project.options.out) { + return ts.first(getOutFileOutputs(project)); + } + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + var outputs = getOutputFileNames(inputFile, project); + if (outputs.length) { + return ts.first(outputs); + } + } + return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output"); + } function formatUpToDateStatus(configFileName, status, relName, formatMessage) { switch (status.type) { case UpToDateStatusType.OutOfDateWithSelf: @@ -91888,17 +92732,17 @@ var ts; } ts.inspectValue = inspectValue; function getRecurser() { - var seen = new Set(); + var seen = []; var nameStack = []; return function (obj, name, cbOk, cbFail) { - if (seen.has(obj) || nameStack.length > 4) { - return cbFail(seen.has(obj), nameStack); + if (seen.indexOf(obj) !== -1 || nameStack.length > 4) { + return cbFail(seen.indexOf(obj) !== -1, nameStack); } - seen.add(obj); + seen.push(obj); nameStack.push(name); var res = cbOk(); nameStack.pop(); - seen.delete(obj); + seen.pop(); return res; }; } @@ -91956,8 +92800,8 @@ var ts; return key === "constructor" ? undefined : getValueInfo(key, value, recurser); }); } - var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); - var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + var ignoredProperties = ["arguments", "caller", "constructor", "eval", "super_"]; + var reservedFunctionProperties = Object.getOwnPropertyNames(ts.noop); function getEntriesOfObject(obj) { var seen = ts.createMap(); var entries = []; @@ -91966,8 +92810,8 @@ var ts; for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { var key = _a[_i]; if (!isJsPrivate(key) && - !ignoredProperties.has(key) && - (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + ignoredProperties.indexOf(key) === -1 && + (typeof obj !== "function" || reservedFunctionProperties.indexOf(key) === -1) && // Don't add property from a higher prototype if it already exists in a lower one ts.addToSeen(seen, key)) { var value = safeGetPropertyOfObject(chain, key); @@ -91995,7 +92839,7 @@ var ts; return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; } function isJsPrivate(name) { - return name.startsWith("_"); + return ts.startsWith(name, "_"); } ts.isJsPrivate = isJsPrivate; function tryRequire(fileNameToRequire) { @@ -92256,8 +93100,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_6.config; + var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_7.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -95689,7 +96533,7 @@ var ts; continue; var patterns = paths[path]; if (patterns) { - var _loop_10 = function (name, kind, extension) { + var _loop_11 = function (name, kind, extension) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind, extension)); @@ -95697,7 +96541,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_10(name, kind, extension); + _loop_11(name, kind, extension); } } } @@ -95732,7 +96576,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_11 = function (moduleName) { + var _loop_12 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); @@ -95740,7 +96584,7 @@ var ts; }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_11(moduleName); + _loop_12(moduleName); } } if (!foundGlobal) { @@ -96094,7 +96938,7 @@ var ts; getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { - if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { + if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); @@ -96294,7 +97138,8 @@ var ts; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + return origin && originIsExport(origin) && ((origin.isDefaultExport && symbol.escapedName === "default" /* Default */) || + (symbol.escapedName === "export=" /* ExportEquals */)) // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) @@ -96864,14 +97709,11 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // For JS, stay on the safe side. - if (isUncheckedFile) - return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. - return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); + if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) + return true; + // If some file is using ES6 modules, assume that it's OK to add more. + return ts.programContainsEs6Modules(program); } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { @@ -97670,7 +98512,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 121 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); + return kind === 121 /* AsyncKeyword */ || kind === 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -98958,9 +99800,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { - var result_7 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); - return result_7; + var result_8 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_8.push(nodeEntry(node)); }); + return result_8; } else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -98992,8 +99834,8 @@ var ts; case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; + var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case 1 /* Label */: { var node_3 = def.node; @@ -99001,8 +99843,8 @@ var ts; } case 2 /* Keyword */: { var node_4 = def.node; - var name_4 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; + var name_5 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; } case 3 /* This */: { var node_5 = def.node; @@ -99028,8 +99870,8 @@ var ts; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } - function toRenameLocation(entry, originalNode, checker) { - return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker)); + function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText) { + return __assign({}, entryToDocumentSpan(entry), (providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker))); } FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { @@ -99334,12 +100176,12 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol; + var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol; // Compute the meaning from the location and the symbol it references var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); - var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); if (exportSpecifier) { // When renaming at an export specifier, rename the export and not the thing being exported. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); @@ -99349,7 +100191,7 @@ var ts; searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -99382,9 +100224,9 @@ var ts; } } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, useLocalSymbolForExportSpecifier) { var parent = node.parent; - if (ts.isExportSpecifier(parent) && !isForRename) { + if (ts.isExportSpecifier(parent) && useLocalSymbolForExportSpecifier) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); } // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. @@ -99846,6 +100688,7 @@ var ts; getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { + ts.Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled"); var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); @@ -99874,14 +100717,14 @@ var ts; } } // For `export { foo as bar }`, rename `foo`, but not `bar`. - if (!state.options.isForRename || alwaysGetReferences) { + if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) { var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. - if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) { + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (imported) searchForImportedSymbol(imported, state); @@ -99913,7 +100756,7 @@ var ts; return; var symbol = importOrExport.symbol; if (importOrExport.kind === 0 /* Import */) { - if (!state.options.isForRename) { + if (!(isForRenameWithPrefixAndSuffixText(state.options))) { searchForImportedSymbol(symbol, state); } } @@ -100175,6 +101018,9 @@ var ts; }); return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } + function isParameterName(node) { + return node.kind === 72 /* Identifier */ && node.parent.kind === 151 /* Parameter */ && node.parent.name === node; + } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. @@ -100195,7 +101041,7 @@ var ts; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; case 279 /* SourceFile */: - if (ts.isExternalModule(searchSpaceNode)) { + if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) { return undefined; } // falls through @@ -100227,7 +101073,7 @@ var ts; // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; case 279 /* SourceFile */: - return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container); + return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); @@ -100251,13 +101097,13 @@ var ts; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, providePrefixAndSuffixText, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, !(isForRename && providePrefixAndSuffixText), function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, onlyIncludeBindingElementAtReferenceLocation, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { /* Because in short-hand property assignment, location has two meaning : property name and as value of the property @@ -100304,9 +101150,23 @@ var ts; return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. - // Don't do this when populating search set for a rename -- just rename the local. + // Don't do this when populating search set for a rename when prefix and suffix text will be provided -- just rename the local. if (!isForRenamePopulateSearchSymbolSet) { - var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + var bindingElementPropertySymbol = void 0; + if (onlyIncludeBindingElementAtReferenceLocation) { + bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + } + else { + bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); + } + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + ts.Debug.assert(isForRenamePopulateSearchSymbolSet); + // due to the above assert and the arguments at the uses of this function, + // (onlyIncludeBindingElementAtReferenceLocation <=> !providePrefixAndSuffixTextForRename) holds + var includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation; + if (includeOriginalSymbolOfBindingElement) { + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); } function fromRoot(sym, kind) { @@ -100324,10 +101184,17 @@ var ts; : undefined); }); } + function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { + var bindingElement = ts.getDeclarationOfKind(symbol, 186 /* BindingElement */); + if (bindingElement && ts.isObjectBindingElementWithoutPropertyName(bindingElement)) { + return ts.getPropertySymbolFromBindingElement(checker, bindingElement); + } + } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, + /*onlyIncludeBindingElementAtReferenceLocation*/ !state.options.isForRename || !!state.options.providePrefixAndSuffixTextForRename, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, @@ -100412,6 +101279,9 @@ var ts; }); return res.length === 0 ? undefined : res; } + function isForRenameWithPrefixAndSuffixText(options) { + return options.isForRename && options.providePrefixAndSuffixTextForRename; + } })(Core = FindAllReferences.Core || (FindAllReferences.Core = {})); })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -100524,7 +101394,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_12 = function (sourceFile) { + var _loop_13 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -100546,7 +101416,7 @@ var ts; var toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. // TODO:GH#18217 - ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew) : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) @@ -100556,7 +101426,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_12(sourceFile); + _loop_13(sourceFile); } } function combineNormal(pathA, pathB) { @@ -100576,23 +101446,32 @@ var ts; var resolved = host.resolveModuleNames ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); - return getSourceFileToImportFromResolved(resolved, oldToNew, host); + return getSourceFileToImportFromResolved(resolved, oldToNew); } } - function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + function getSourceFileToImportFromResolved(resolved, oldToNew) { // Search through all locations looking for a moved file, and only then test already existing files. // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. - return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); - function tryEach(cb) { - return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + if (!resolved) + return undefined; + // First try resolved module + if (resolved.resolvedModule) { + var result_9 = tryChange(resolved.resolvedModule.resolvedFileName); + if (result_9) + return result_9; } - function tryGetNewFile(oldFileName) { - var newFileName = oldToNew(oldFileName); - return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + // Then failed lookups except package.json since we dont want to touch them (only included ts/js files) + var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson); + if (result) + return result; + // If nothing changed, then result is resolved module file thats not updated + return resolved.resolvedModule && { newFileName: resolved.resolvedModule.resolvedFileName, updated: false }; + function tryChangeWithIgnoringPackageJson(oldFileName) { + return !ts.endsWith(oldFileName, "/package.json") ? tryChange(oldFileName) : undefined; } - function tryGetOldFile(oldFileName) { + function tryChange(oldFileName) { var newFileName = oldToNew(oldFileName); - return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 + return newFileName && { newFileName: newFileName, updated: true }; } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { @@ -100689,10 +101568,10 @@ var ts; // bar(({pr/*goto*/op1})=>{}); if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && (node === (parent.propertyName || parent.name))) { - var name_5 = ts.getNameFromPropertyName(node); + var name_6 = ts.getNameFromPropertyName(node); var type = typeChecker.getTypeAtLocation(parent.parent); - return name_5 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { - var prop = t.getProperty(name_5); + return name_6 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { + var prop = t.getProperty(name_6); return prop && getDefinitionFromSymbol(typeChecker, prop, node); }); } @@ -101337,7 +102216,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_13 = function (sourceFile) { + var _loop_14 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -101349,7 +102228,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { var sourceFile = sourceFiles_6[_i]; - _loop_13(sourceFile); + _loop_14(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -102041,7 +102920,7 @@ var ts; else if (ts.isCallExpression(parent)) { var name = getCalledExpressionName(parent.expression); if (name !== undefined) { - var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteralLike(a) ? a.getText(curSourceFile) : undefined; }).join(", "); return name + "(" + args + ") callback"; } } @@ -102094,10 +102973,12 @@ var ts; organizeImportsWorker(topLevelExportDecls, coalesceExports); for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; - var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217 - var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); + if (!ambientModule.body) { + continue; + } + var ambientModuleImportDecls = ambientModule.body.statements.filter(ts.isImportDeclaration); organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); - var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); organizeImportsWorker(ambientModuleExportDecls, coalesceExports); } return changeTracker.getChanges(); @@ -102137,13 +103018,9 @@ var ts; } } OrganizeImports.organizeImports = organizeImports; - function getModuleBlock(moduleDecl) { - var body = moduleDecl.body; - return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; - } function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); - var jsxNamespace = typeChecker.getJsxNamespace(); + var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { @@ -102403,6 +103280,9 @@ var ts; if (ts.isDeclaration(n)) { addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); } + if (isFunctionExpressionAssignedToVariable(n)) { + addOutliningForLeadingCommentsForNode(n.parent.parent.parent, sourceFile, cancellationToken, out); + } var span = getOutliningSpanForNode(n, sourceFile); if (span) out.push(span); @@ -102420,6 +103300,13 @@ var ts; } depthRemaining++; } + function isFunctionExpressionAssignedToVariable(n) { + if (!ts.isFunctionExpression(n) && !ts.isArrowFunction(n)) { + return false; + } + var ancestor = ts.findAncestor(n, ts.isVariableStatement); + return !!ancestor && ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration(ancestor) === n; + } } function addRegionOutliningSpans(sourceFile, out) { var regions = []; @@ -102535,6 +103422,7 @@ var ts; case 245 /* ModuleBlock */: return spanForNode(n.parent); case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: case 241 /* InterfaceDeclaration */: case 243 /* EnumDeclaration */: case 246 /* CaseBlock */: @@ -102563,10 +103451,10 @@ var ts; } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 18 /* OpenBraceToken */; } - // If the block has no leading keywords and is inside an array literal, + // If the block has no leading keywords and is inside an array literal or call expression, // we only want to collapse the span of the block. // Otherwise, the collapsed section will include the end of the previous line. - return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent), open); + return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent) && !ts.isCallExpression(node.parent), open); } function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { if (autoCollapse === void 0) { autoCollapse = false; } @@ -102868,15 +103756,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_14 = function (start) { + var _loop_15 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_14(start); - if (typeof state_3 === "object") - return state_3.value; + var state_4 = _loop_15(start); + if (typeof state_4 === "object") + return state_4.value; } return -1; } @@ -103390,15 +104278,15 @@ var ts; (function (ts) { var Rename; (function (Rename) { - function getRenameInfo(program, sourceFile, position) { + function getRenameInfo(program, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position); var renameInfo = node && nodeIsEligibleForRename(node) - ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }) + ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options) : undefined; return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) { + function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) return; @@ -103415,7 +104303,7 @@ var ts; return undefined; } if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { - return getRenameInfoForModule(node, sourceFile, symbol); + return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 149 /* ComputedPropertyName */) @@ -103432,7 +104320,7 @@ var ts; var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); if (!moduleSourceFile) return undefined; - var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var withoutIndex = ts.endsWith(node.text, "/index") || ts.endsWith(node.text, "/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; @@ -103887,7 +104775,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_15 = function (n) { + var _loop_16 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -103897,9 +104785,9 @@ var ts; } }; for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { - var state_4 = _loop_15(n); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_16(n); + if (typeof state_5 === "object") + return state_5.value; } return undefined; } @@ -104012,86 +104900,47 @@ var ts; var ts; (function (ts) { var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; - function getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, getProgram) { - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var sourcemappedFileCache; + function getSourceMapper(host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var currentDirectory = host.getCurrentDirectory(); + var sourceFileLike = ts.createMap(); + var documentPositionMappers = ts.createMap(); return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; function toPath(fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } - function scanForSourcemapURL(fileName) { - var mappedFile = sourcemappedFileCache.get(toPath(fileName)); - if (!mappedFile) { - return; + function getDocumentPositionMapper(generatedFileName, sourceFileName) { + var path = toPath(generatedFileName); + var value = documentPositionMappers.get(path); + if (value) + return value; + var mapper; + if (host.getDocumentPositionMapper) { + mapper = host.getDocumentPositionMapper(generatedFileName, sourceFileName); } - return ts.tryGetSourceMappingURL(mappedFile.text, ts.getLineStarts(mappedFile)); - } - function convertDocumentToSourceMapper(file, contents, mapFileName) { - var map = ts.tryParseRawSourceMap(contents); - if (!map || !map.sources || !map.file || !map.mappings) { - // obviously invalid map - return file.sourceMapper = ts.identitySourceMapConsumer; + else if (host.readFile) { + var file = getSourceFileLike(generatedFileName); + mapper = file && ts.getDocumentPositionMapper({ getSourceFileLike: getSourceFileLike, getCanonicalFileName: getCanonicalFileName, log: function (s) { return host.log(s); } }, generatedFileName, ts.getLineInfo(file.text, ts.getLineStarts(file)), function (f) { return !host.fileExists || host.fileExists(f) ? host.readFile(f) : undefined; }); } - var program = getProgram(); - return file.sourceMapper = ts.createDocumentPositionMapper({ - getSourceFileLike: function (s) { - // Lookup file in program, if provided - var file = program && program.getSourceFileByPath(s); - // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file - if (file === undefined || file.resolvedPath !== s) { - // Otherwise check the cache (which may hit disk) - return sourcemappedFileCache.get(s); - } - return file; - }, - getCanonicalFileName: getCanonicalFileName, - log: log, - }, map, mapFileName); - } - function getSourceMapper(fileName, file) { - if (!host.readFile || !host.fileExists) { - return file.sourceMapper = ts.identitySourceMapConsumer; - } - if (file.sourceMapper) { - return file.sourceMapper; - } - var mapFileName = scanForSourcemapURL(fileName); - if (mapFileName) { - var match = base64UrlRegExp.exec(mapFileName); - if (match) { - if (match[1]) { - var base64Object = match[1]; - return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); - } - // Not a data URL we can parse, skip it - mapFileName = undefined; - } - } - var possibleMapLocations = []; - if (mapFileName) { - possibleMapLocations.push(mapFileName); - } - possibleMapLocations.push(fileName + ".map"); - for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { - var location = possibleMapLocations_1[_i]; - var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); - if (host.fileExists(mapPath)) { - return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 - } - } - return file.sourceMapper = ts.identitySourceMapConsumer; + documentPositionMappers.set(path, mapper || ts.identitySourceMapConsumer); + return mapper || ts.identitySourceMapConsumer; } function tryGetSourcePosition(info) { if (!ts.isDeclarationFileName(info.fileName)) return undefined; - var file = getFile(info.fileName); + var file = getSourceFile(info.fileName); if (!file) return undefined; - var newLoc = getSourceMapper(info.fileName, file).getSourcePosition(info); - return newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; + var newLoc = getDocumentPositionMapper(info.fileName).getSourcePosition(info); + return !newLoc || newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; } function tryGetGeneratedPosition(info) { - var program = getProgram(); + if (ts.isDeclarationFileName(info.fileName)) + return undefined; + var sourceFile = getSourceFile(info.fileName); + if (!sourceFile) + return undefined; + var program = host.getProgram(); var options = program.getCompilerOptions(); var outPath = options.outFile || options.out; var declarationPath = outPath ? @@ -104099,49 +104948,96 @@ var ts; ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); if (declarationPath === undefined) return undefined; - var declarationFile = getFile(declarationPath); - if (!declarationFile) - return undefined; - var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + var newLoc = getDocumentPositionMapper(declarationPath, info.fileName).getGeneratedPosition(info); return newLoc === info ? undefined : newLoc; } - function getFile(fileName) { + function getSourceFile(fileName) { + var program = host.getProgram(); + if (!program) + return undefined; var path = toPath(fileName); - var file = getProgram().getSourceFileByPath(path); - if (file && file.resolvedPath === path) { - return file; + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + var file = program.getSourceFileByPath(path); + return file && file.resolvedPath === path ? file : undefined; + } + function getOrCreateSourceFileLike(fileName) { + var path = toPath(fileName); + var fileFromCache = sourceFileLike.get(path); + if (fileFromCache !== undefined) + return fileFromCache ? fileFromCache : undefined; + if (!host.readFile || host.fileExists && !host.fileExists(path)) { + sourceFileLike.set(path, false); + return undefined; } - return sourcemappedFileCache.get(path); + // And failing that, check the disk + var text = host.readFile(path); + var file = text ? createSourceFileLike(text) : false; + sourceFileLike.set(path, file); + return file ? file : undefined; + } + // This can be called from source mapper in either source program or program that includes generated file + function getSourceFileLike(fileName) { + return !host.getSourceFileLike ? + getSourceFile(fileName) || getOrCreateSourceFileLike(fileName) : + host.getSourceFileLike(fileName); } function toLineColumnOffset(fileName, position) { - var file = getFile(fileName); // TODO: GH#18217 + var file = getSourceFileLike(fileName); // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } function clearCache() { - sourcemappedFileCache = createSourceFileLikeCache(host); + sourceFileLike.clear(); + documentPositionMappers.clear(); } } ts.getSourceMapper = getSourceMapper; - function createSourceFileLikeCache(host) { - var cached = ts.createMap(); - return { - get: function (path) { - if (cached.has(path)) { - return cached.get(path); + function getDocumentPositionMapper(host, generatedFileName, generatedFileLineInfo, readMapFile) { + var mapFileName = ts.tryGetSourceMappingURL(generatedFileLineInfo); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(host, ts.base64decode(ts.sys, base64Object), generatedFileName); } - if (!host.fileExists || !host.readFile || !host.fileExists(path)) - return; - // And failing that, check the disk - var text = host.readFile(path); // TODO: GH#18217 - var file = { - text: text, - lineMap: undefined, - getLineAndCharacterOfPosition: function (pos) { - return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); - } - }; - cached.set(path, file); - return file; + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(generatedFileName + ".map"); + var originalMapFileName = mapFileName && ts.getNormalizedAbsolutePath(mapFileName, ts.getDirectoryPath(generatedFileName)); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapFileName_1 = ts.getNormalizedAbsolutePath(location, ts.getDirectoryPath(generatedFileName)); + var mapFileContents = readMapFile(mapFileName_1, originalMapFileName); + if (ts.isString(mapFileContents)) { + return convertDocumentToSourceMapper(host, mapFileContents, mapFileName_1); + } + if (mapFileContents !== undefined) { + return mapFileContents || undefined; + } + } + return undefined; + } + ts.getDocumentPositionMapper = getDocumentPositionMapper; + function convertDocumentToSourceMapper(host, contents, mapFileName) { + var map = ts.tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { + // obviously invalid map + return undefined; + } + return ts.createDocumentPositionMapper(host, map, mapFileName); + } + function createSourceFileLike(text, lineMap) { + return { + text: text, + lineMap: lineMap, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); } }; } @@ -104149,6 +105045,7 @@ var ts; /* @internal */ var ts; (function (ts) { + var visitedNestedConvertibleFunctions = ts.createMap(); function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; @@ -104159,6 +105056,7 @@ var ts; diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } var isJsFile = ts.isSourceFileJS(sourceFile); + visitedNestedConvertibleFunctions.clear(); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -104256,13 +105154,17 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - if (!ts.isAsyncFunction(node) && + // need to check function before checking map so that deeper levels of nested callbacks are checked + if (isConvertibleFunction(node, checker) && !visitedNestedConvertibleFunctions.has(getKeyFromNode(node))) { + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + } + } + function isConvertibleFunction(node, checker) { + return !ts.isAsyncFunction(node) && node.body && ts.isBlock(node.body) && hasReturnStatementWithPromiseHandler(node.body) && - returnsPromise(node, checker)) { - diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); - } + returnsPromise(node, checker); } function returnsPromise(node, checker) { var functionType = checker.getTypeAtLocation(node); @@ -104303,16 +105205,21 @@ var ts; // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts function isFixablePromiseArgument(arg) { switch (arg.kind) { - case 96 /* NullKeyword */: - case 72 /* Identifier */: // identifier includes undefined case 239 /* FunctionDeclaration */: case 196 /* FunctionExpression */: case 197 /* ArrowFunction */: + visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); + /* falls through */ + case 96 /* NullKeyword */: + case 72 /* Identifier */: // identifier includes undefined return true; default: return false; } } + function getKeyFromNode(exp) { + return exp.pos.toString() + ":" + exp.end.toString(); + } })(ts || (ts = {})); /* @internal */ var ts; @@ -105035,7 +105942,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_16 = function (opt) { + var _loop_17 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -105054,7 +105961,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_16(opt); + _loop_17(opt); } return options; } @@ -106967,10 +107874,7 @@ var ts; * Trimming will be done for lines after the previous range */ function trimTrailingWhitespacesForRemainingRange() { - if (!previousRange) { - return; - } - var startPosition = previousRange.end; + var startPosition = previousRange ? previousRange.end : originalRange.pos; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); @@ -108229,7 +109133,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_17 = function (sourceFile, node) { + var _loop_18 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -108242,7 +109146,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_17(sourceFile, node); + _loop_18(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -108299,14 +109203,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_18 = function (i) { + var _loop_19 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_18(i); + _loop_19(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -108910,6 +109814,40 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addNameToNamelessParameter"; + var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(token)) { + return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.formatSyntaxKind(token.kind)); + } + var param = token.parent; + if (!ts.isParameter(param)) { + return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.formatSyntaxKind(token.kind)); + } + var i = param.parent.parameters.indexOf(param); + ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); + ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); + var replacement = ts.createParameter( + /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer); + changeTracker.replaceNode(sourceFile, token, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109237,20 +110175,8 @@ var ts; annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } - function isApplicableFunctionForInference(declaration) { - switch (declaration.kind) { - case 239 /* FunctionDeclaration */: - case 156 /* MethodDeclaration */: - case 157 /* Constructor */: - return true; - case 196 /* FunctionExpression */: - var parent = declaration.parent; - return ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) || !!declaration.name; - } - return false; - } function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { - if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + if (!ts.isIdentifier(parameterDeclaration.name)) { return; } var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || @@ -109263,12 +110189,17 @@ var ts; annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } else { + var needParens = ts.isArrowFunction(containingFunction) && !ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(containingFunction.parameters), ts.createToken(20 /* OpenParenToken */)); for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; if (declaration && !declaration.type && !declaration.initializer) { annotate(changes, sourceFile, declaration, type, program, host); } } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(containingFunction.parameters), ts.createToken(21 /* CloseParenToken */)); } } function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { @@ -109389,6 +110320,7 @@ var ts; case 157 /* Constructor */: searchToken = ts.findChildOfKind(containingFunction, 124 /* ConstructorKeyword */, sourceFile); break; + case 197 /* ArrowFunction */: case 196 /* FunctionExpression */: var parent = containingFunction.parent; searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? @@ -110066,7 +110998,7 @@ var ts; var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_19 = function (statement) { + var _loop_20 = function (statement) { ts.forEachChild(statement, function visit(node) { if (ts.isCallExpression(node)) { startTransformation(node, statement); @@ -110078,7 +111010,7 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_19(statement); + _loop_20(statement); } } function getReturnStatementsWithPromiseHandlers(body) { @@ -110986,11 +111918,10 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var program = context.program, sourceFile = context.sourceFile, span = context.span; + var sourceFile = context.sourceFile, span = context.span; var classDeclaration = getClass(sourceFile, span.start); - var checker = program.getTypeChecker(); return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); }); }, @@ -111002,7 +111933,7 @@ var ts; if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { var implementedTypeNode = _a[_i]; - addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); + addMissingDeclarations(context, implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); } } }); @@ -111014,7 +111945,8 @@ var ts; function symbolPointsToNonPrivateMember(symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); } - function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + function addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + var checker = context.program.getTypeChecker(); var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. @@ -111028,11 +111960,11 @@ var ts; if (!classType.getStringIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); } - codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, context, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); if (indexInfoOfKind) { - changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)); + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration, /*flags*/ undefined, codefix.getNoopSymbolTrackerWithResolver(context))); } } } @@ -111358,7 +112290,7 @@ var ts; var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) - ? checker.getJsxNamespace() + ? checker.getJsxNamespace(sourceFile) : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */); @@ -111730,7 +112662,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_20 = function (info) { + var _loop_21 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -111757,7 +112689,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_20(info); + _loop_21(info); } }); })); @@ -111906,7 +112838,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { - var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, typeDecl); var containingMethodDeclaration = ts.getAncestor(callExpression, 156 /* MethodDeclaration */); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); @@ -111932,6 +112864,40 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingNewOperator"; + var errorCodes = [ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingNewOperator(t, sourceFile, span); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_new_operator_to_call, fixId, ts.Diagnostics.Add_missing_new_operator_to_all_calls)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return addMissingNewOperator(changes, context.sourceFile, diag); + }); }, + }); + function addMissingNewOperator(changes, sourceFile, span) { + var call = ts.cast(findAncestorMatchingSpan(sourceFile, span), ts.isCallExpression); + var newExpression = ts.createNew(call.expression, call.typeArguments, call.arguments); + changes.replaceNode(sourceFile, call, newExpression); + } + function findAncestorMatchingSpan(sourceFile, span) { + var token = ts.getTokenAtPosition(sourceFile, span.start); + var end = ts.textSpanEnd(span); + while (token.end < end) { + token = token.parent; + } + return token; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -112009,10 +112975,10 @@ var ts; var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); if (!tsconfigObjectLiteral) return undefined; - var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + var compilerOptionsProperty = codefix.findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); if (!compilerOptionsProperty) { var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); - changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, codefix.createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); return defaultTypesDirectoryName; } var compilerOptions = compilerOptionsProperty.initializer; @@ -112024,10 +112990,10 @@ var ts; } var defaultBaseUrl = "."; function makeDefaultBaseUrl() { - return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + return codefix.createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); } function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { - var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + var baseUrlProp = codefix.findJsonProperty(compilerOptions, "baseUrl"); if (baseUrlProp) { return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; } @@ -112038,13 +113004,13 @@ var ts; } var defaultTypesDirectoryName = "types"; function makeDefaultPathMapping() { - return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + return codefix.createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); } function makeDefaultPaths() { - return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + return codefix.createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); } function getOrAddPathMapping(changes, tsconfig, compilerOptions) { - var paths = findProperty(compilerOptions, "paths"); + var paths = codefix.findJsonProperty(compilerOptions, "paths"); if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); return defaultTypesDirectoryName; @@ -112060,12 +113026,6 @@ var ts; changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); return defaultTypesDirectoryName; } - function createJsonPropertyAssignment(name, initializer) { - return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); - } - function findProperty(obj, name) { - return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); - } function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } @@ -112094,9 +113054,9 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var program = context.program, sourceFile = context.sourceFile, span = context.span; + var sourceFile = context.sourceFile, span = context.span; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { - return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, context, t, context.preferences); }); return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; }, @@ -112106,7 +113066,7 @@ var ts; return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var classDeclaration = getClass(diag.file, diag.start); if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { - addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); + addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences); } }); }, @@ -112117,13 +113077,14 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, pos); return ts.cast(token.parent, ts.isClassLike); } - function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { + function addMissingMembers(classDeclaration, sourceFile, context, changeTracker, preferences) { var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration); + var checker = context.program.getTypeChecker(); var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); - codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, context, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files @@ -112865,24 +113826,43 @@ var ts; * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. * @returns Empty string iff there are no member insertions. */ - function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, context, preferences, out) { var classMembers = classDeclaration.symbol.members; for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { var symbol = possiblyMissingSymbols_1[_i]; if (!classMembers.has(symbol.escapedName)) { - addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); + addNewNodeForMemberSymbol(symbol, classDeclaration, context, preferences, out); } } } codefix.createMissingMemberNodes = createMissingMemberNodes; + function getModuleSpecifierResolverHost(context) { + return { + directoryExists: context.host.directoryExists ? function (d) { return context.host.directoryExists(d); } : undefined, + fileExists: context.host.fileExists ? function (f) { return context.host.fileExists(f); } : undefined, + getCurrentDirectory: context.host.getCurrentDirectory ? function () { return context.host.getCurrentDirectory(); } : undefined, + readFile: context.host.readFile ? function (f) { return context.host.readFile(f); } : undefined, + useCaseSensitiveFileNames: context.host.useCaseSensitiveFileNames ? function () { return context.host.useCaseSensitiveFileNames(); } : undefined, + getSourceFiles: function () { return context.program.getSourceFiles(); }, + getCommonSourceDirectory: function () { return context.program.getCommonSourceDirectory(); }, + }; + } + function getNoopSymbolTrackerWithResolver(context) { + return { + trackSymbol: ts.noop, + moduleResolverHost: getModuleSpecifierResolverHost(context), + }; + } + codefix.getNoopSymbolTrackerWithResolver = getNoopSymbolTrackerWithResolver; /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, context, preferences, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; } + var checker = context.program.getTypeChecker(); var declaration = declarations[0]; var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); @@ -112894,7 +113874,7 @@ var ts; case 159 /* SetAccessor */: case 153 /* PropertySignature */: case 154 /* PropertyDeclaration */: - var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); + var typeNode = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); out(ts.createProperty( /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); @@ -112934,13 +113914,14 @@ var ts; break; } function outputMethod(signature, modifiers, name, body) { - var method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + var method = signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body); if (method) out(method); } } - function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + function signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body) { + var program = context.program; + var signatureDeclaration = program.getTypeChecker().signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 1 /* NoTruncation */ | 256 /* SuppressAnyReturnType */, getNoopSymbolTrackerWithResolver(context)); if (!signatureDeclaration) { return undefined; } @@ -112951,19 +113932,21 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, contextNode) { + var body = !ts.isInterfaceDeclaration(contextNode); var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); + var tracker = getNoopSymbolTrackerWithResolver(context); var types = ts.map(args, function (arg) { // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, /*flags*/ undefined, tracker); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); var contextualType = checker.getContextualType(call); - var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(120 /* AnyKeyword */); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker) || ts.createKeywordTypeNode(120 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, @@ -113044,6 +114027,38 @@ var ts; } return undefined; } + function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); + if (compilerOptionsProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral([ + createJsonPropertyAssignment(optionName, optionValue), + ]))); + return; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) { + return; + } + var optionProperty = findJsonProperty(compilerOptions, optionName); + if (optionProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); + } + else { + changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + } + } + codefix.setJsonCompilerOptionValue = setJsonCompilerOptionValue; + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + codefix.createJsonPropertyAssignment = createJsonPropertyAssignment; + function findJsonProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + codefix.findJsonProperty = findJsonProperty; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -113405,9 +114420,9 @@ var ts; forEachOwnNodeOfFunction(fnAst, function (node) { if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) { - var name_6 = node.left.name.text; - if (!ts.isJsPrivate(name_6)) { - ts.getOrUpdate(members, name_6, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_6, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); + var name_7 = node.left.name.text; + if (!ts.isJsPrivate(name_7)) { + ts.getOrUpdate(members, name_7, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_7, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); } } }); @@ -113922,7 +114937,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_21 = function (element) { + var _loop_22 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -113941,7 +114956,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_21(element); + _loop_22(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -114336,32 +115351,30 @@ var ts; case 100 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 233 /* LabeledStatement */: - { - var label = node.label; - (seenLabels || (seenLabels = [])).push(label.escapedText); - ts.forEachChild(node, visit); - seenLabels.pop(); - break; - } + case 233 /* LabeledStatement */: { + var label = node.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + ts.forEachChild(node, visit); + seenLabels.pop(); + break; + } case 229 /* BreakStatement */: - case 228 /* ContinueStatement */: - { - var label = node.label; - if (label) { - if (!ts.contains(seenLabels, label.escapedText)) { - // attempts to jump to label that is not in range to be extracted - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); - } + case 228 /* ContinueStatement */: { + var label = node.label; + if (label) { + if (!ts.contains(seenLabels, label.escapedText)) { + // attempts to jump to label that is not in range to be extracted + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); } - else { - if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { - // attempt to break or continue in a forbidden context - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); - } - } - break; } + else { + if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + // attempt to break or continue in a forbidden context + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } case 201 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; @@ -115173,7 +116186,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_22 = function (i) { + var _loop_23 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -115213,7 +116226,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_22(i); + _loop_23(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -115764,10 +116777,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_23 = function (sourceFile) { + var _loop_24 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_24 = function (statement) { + var _loop_25 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -115789,12 +116802,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_24(statement); + _loop_25(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_23(sourceFile); + _loop_24(sourceFile); } } function getNamespaceLikeImport(node) { @@ -116844,8 +117857,8 @@ var ts; SourceFileObject.prototype.getLineStarts = function () { return ts.getLineStarts(this); }; - SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) { - return ts.getPositionOfLineAndCharacter(this, line, character); + SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character, allowEdits) { + return ts.computePositionOfLineAndCharacter(ts.getLineStarts(this), line, character, this.text, allowEdits); }; SourceFileObject.prototype.getLineEndOfPosition = function (pos) { var line = this.getLineAndCharacterOfPosition(pos).line; @@ -117295,7 +118308,16 @@ var ts; } var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var sourceMapper = ts.getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, function () { return program; }); + var sourceMapper = ts.getSourceMapper({ + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCurrentDirectory: function () { return currentDirectory; }, + getProgram: getProgram, + fileExists: host.fileExists && (function (f) { return host.fileExists(f); }), + readFile: host.readFile && (function (f, encoding) { return host.readFile(f, encoding); }), + getDocumentPositionMapper: host.getDocumentPositionMapper && (function (generatedFileName, sourceFileName) { return host.getDocumentPositionMapper(generatedFileName, sourceFileName); }), + getSourceFileLike: host.getSourceFileLike && (function (f) { return host.getSourceFileLike(f); }), + log: log + }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -117348,15 +118370,7 @@ var ts; writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, fileExists: fileExists, - readFile: function (fileName) { - // stub missing host functionality - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - if (entry) { - return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); - } - return host.readFile && host.readFile(fileName); - }, + readFile: readFile, realpath: host.realpath && (function (path) { return host.realpath(path); }), directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); @@ -117410,6 +118424,15 @@ var ts; !ts.isString(entry) : (!!host.fileExists && host.fileExists(fileName)); } + function readFile(fileName) { + // stub missing host functionality + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache && hostCache.getEntryByPath(path); + if (entry) { + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); + } + return host.readFile && host.readFile(fileName); + } // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { @@ -117621,7 +118644,7 @@ var ts; var sourceFile = getValidSourceFile(fileName); return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } - function findRenameLocations(fileName, position, findInStrings, findInComments) { + function findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, position); @@ -117632,7 +118655,7 @@ var ts; }); } else { - return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, providePrefixAndSuffixTextForRename: providePrefixAndSuffixTextForRename, isForRename: true }, function (entry, originalNode, checker) { return ts.FindAllReferences.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false); }); } } function getReferencesAtPosition(fileName, position) { @@ -118056,9 +119079,9 @@ var ts; return ts.stringContains(path, "/node_modules/"); } } - function getRenameInfo(fileName, position) { + function getRenameInfo(fileName, position, options) { synchronizeHostData(); - return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options); } function getRefactorContext(file, positionOrRange, preferences, formatOptions) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; @@ -119316,13 +120339,13 @@ var ts; var _this = this; return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); }; - LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position, options); }); }; - LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { + LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { var _this = this; - return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ", " + providePrefixAndSuffixTextForRename + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename); }); }; /// GET BRACE MATCHING LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { @@ -119853,6 +120876,17 @@ var ts; server.stringifyIndented = stringifyIndented; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +/* @internal */ +(function (ts) { + // Additional tsserver specific watch information + var WatchType; + (function (WatchType) { + WatchType["ClosedScriptInfo"] = "Closed Script info"; + WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; + WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; + WatchType["MissingSourceMapFile"] = "Missing source map file"; + })(WatchType = ts.WatchType || (ts.WatchType = {})); +})(ts || (ts = {})); // tslint:disable no-unnecessary-qualifier /** * Declaration module describing the TypeScript Server protocol @@ -120072,12 +121106,21 @@ var ts; TextStorage.prototype.useScriptVersionCache_TestOnly = function () { this.switchToScriptVersionCache(); }; + TextStorage.prototype.resetSourceMapInfo = function () { + this.info.sourceFileLike = undefined; + this.info.closeSourceMapFileWatcher(); + this.info.sourceMapFilePath = undefined; + this.info.declarationInfoPath = undefined; + this.info.sourceInfos = undefined; + this.info.documentPositionMapper = undefined; + }; /** Public for testing */ TextStorage.prototype.useText = function (newText) { this.svc = undefined; this.text = newText; this.lineMap = undefined; this.fileSize = undefined; + this.resetSourceMapInfo(); this.version.text++; }; TextStorage.prototype.edit = function (start, end, newText) { @@ -120086,6 +121129,7 @@ var ts; this.text = undefined; this.lineMap = undefined; this.fileSize = undefined; + this.resetSourceMapInfo(); }; /** * Set the contents as newText @@ -120153,8 +121197,8 @@ var ts; ? this.svc.getSnapshot() : ts.ScriptSnapshot.fromString(this.getOrLoadText()); }; - TextStorage.prototype.getLineInfo = function (line) { - return this.switchToScriptVersionCache().getLineInfo(line); + TextStorage.prototype.getAbsolutePositionAndLineText = function (line) { + return this.switchToScriptVersionCache().getAbsolutePositionAndLineText(line); }; /** * @param line 0 based index @@ -120172,9 +121216,9 @@ var ts; * @param line 1 based index * @param offset 1 based index */ - TextStorage.prototype.lineOffsetToPosition = function (line, offset) { + TextStorage.prototype.lineOffsetToPosition = function (line, offset, allowEdits) { if (!this.useScriptVersionCacheIfValidOrOpen()) { - return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text); + return ts.computePositionOfLineAndCharacter(this.getLineMap(), line - 1, offset - 1, this.text, allowEdits); } // TODO: assert this offset is actually on the line return this.svc.lineOffsetToPosition(line, offset); @@ -120234,6 +121278,17 @@ var ts; ts.Debug.assert(!this.svc, "ScriptVersionCache should not be set"); return this.lineMap || (this.lineMap = ts.computeLineStarts(this.getOrLoadText())); }; + TextStorage.prototype.getLineInfo = function () { + var _this = this; + if (this.svc) { + return { + getLineCount: function () { return _this.svc.getLineCount(); }, + getLineText: function (line) { return _this.svc.getAbsolutePositionAndLineText(line + 1).lineText; } + }; + } + var lineMap = this.getLineMap(); + return ts.getLineInfo(this.text, lineMap); + }; return TextStorage; }()); server.TextStorage = TextStorage; @@ -120463,8 +121518,8 @@ var ts; return false; }; /*@internal*/ - ScriptInfo.prototype.getLineInfo = function (line) { - return this.textStorage.getLineInfo(line); + ScriptInfo.prototype.getAbsolutePositionAndLineText = function (line) { + return this.textStorage.getAbsolutePositionAndLineText(line); }; ScriptInfo.prototype.editContent = function (start, end, newText) { this.textStorage.edit(start, end, newText); @@ -120485,12 +121540,8 @@ var ts; ScriptInfo.prototype.lineToTextSpan = function (line) { return this.textStorage.lineToTextSpan(line); }; - /** - * @param line 1 based index - * @param offset 1 based index - */ - ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { - return this.textStorage.lineOffsetToPosition(line, offset); + ScriptInfo.prototype.lineOffsetToPosition = function (line, offset, allowEdits) { + return this.textStorage.lineOffsetToPosition(line, offset, allowEdits); }; ScriptInfo.prototype.positionToLineOffset = function (position) { return this.textStorage.positionToLineOffset(position); @@ -120498,6 +121549,17 @@ var ts; ScriptInfo.prototype.isJavaScript = function () { return this.scriptKind === 1 /* JS */ || this.scriptKind === 2 /* JSX */; }; + /*@internal*/ + ScriptInfo.prototype.getLineInfo = function () { + return this.textStorage.getLineInfo(); + }; + /*@internal*/ + ScriptInfo.prototype.closeSourceMapFileWatcher = function () { + if (this.sourceMapFilePath && !ts.isString(this.sourceMapFilePath)) { + ts.closeFileWatcherOf(this.sourceMapFilePath); + this.sourceMapFilePath = undefined; + } + }; return ScriptInfo; }()); server.ScriptInfo = ScriptInfo; @@ -120926,7 +121988,7 @@ var ts; }; /*@internal*/ Project.prototype.watchDirectoryOfFailedLookupLocation = function (directory, cb, flags) { - return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Directory of Failed lookup locations in module resolution" /* FailedLookupLocation */, this); + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Failed Lookup Locations" /* FailedLookupLocations */, this); }; /*@internal*/ Project.prototype.onInvalidatedResolution = function () { @@ -120934,7 +121996,7 @@ var ts; }; /*@internal*/ Project.prototype.watchTypeRootsDirectory = function (directory, cb, flags) { - return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type root directory" /* TypeRoots */, this); + return this.projectService.watchFactory.watchDirectory(this.projectService.host, directory, cb, flags, "Type roots" /* TypeRoots */, this); }; /*@internal*/ Project.prototype.onChangedAutomaticTypeDirectiveNames = function () { @@ -120980,6 +122042,14 @@ var ts; Project.prototype.getSourceMapper = function () { return this.getLanguageService().getSourceMapper(); }; + /*@internal*/ + Project.prototype.getDocumentPositionMapper = function (generatedFileName, sourceFileName) { + return this.projectService.getDocumentPositionMapper(this, generatedFileName, sourceFileName); + }; + /*@internal*/ + Project.prototype.getSourceFileLike = function (fileName) { + return this.projectService.getSourceFileLike(fileName, this); + }; Project.prototype.shouldEmitFile = function (scriptInfo) { return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); }; @@ -121210,7 +122280,12 @@ var ts; return false; }; Project.prototype.containsScriptInfo = function (info) { - return this.isRoot(info) || (!!this.program && this.program.getSourceFileByPath(info.path) !== undefined); + if (this.isRoot(info)) + return true; + if (!this.program) + return false; + var file = this.program.getSourceFileByPath(info.path); + return !!file && file.resolvedPath === info.path; }; Project.prototype.containsFile = function (filename, requireOpen) { var info = this.projectService.getScriptInfoForNormalizedPath(filename); @@ -121398,7 +122473,7 @@ var ts; // When a missing file is created, we should update the graph. _this.projectService.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(_this); } - }, ts.PollingInterval.Medium, "Missing file from program" /* MissingFilePath */, this); + }, ts.PollingInterval.Medium, "Missing file" /* MissingFile */, this); return fileWatcher; }; Project.prototype.isWatchedMissingFile = function (path) { @@ -121517,7 +122592,7 @@ var ts; // ../../.. to walk from X/node_modules/typescript/lib/tsserver.js to X/node_modules/ var searchPaths = [ts.combinePaths(this.projectService.getExecutingFilePath(), "../../..")].concat(this.projectService.pluginProbeLocations); if (this.projectService.globalPlugins) { - var _loop_25 = function (globalPluginName) { + var _loop_26 = function (globalPluginName) { // Skip empty names from odd commandline parses if (!globalPluginName) return "continue"; @@ -121532,7 +122607,7 @@ var ts; // Enable global plugins with synthetic configuration entries for (var _i = 0, _a = this.projectService.globalPlugins; _i < _a.length; _i++) { var globalPluginName = _a[_i]; - _loop_25(globalPluginName); + _loop_26(globalPluginName); } } }; @@ -122102,18 +123177,6 @@ var ts; } } } - /* @internal */ - var WatchType; - (function (WatchType) { - WatchType["ConfigFilePath"] = "Config file for the program"; - WatchType["MissingFilePath"] = "Missing file from program"; - WatchType["WildcardDirectories"] = "Wild card directory"; - WatchType["ClosedScriptInfo"] = "Closed Script info"; - WatchType["ConfigFileForInferredRoot"] = "Config file for the inferred project root"; - WatchType["FailedLookupLocation"] = "Directory of Failed lookup locations in module resolution"; - WatchType["TypeRoots"] = "Type root directory"; - WatchType["NodeModulesForClosedScriptInfo"] = "node_modules for closed script infos in them"; - })(WatchType = server.WatchType || (server.WatchType = {})); var ConfigFileWatcherStatus; (function (ConfigFileWatcherStatus) { ConfigFileWatcherStatus["ReloadingFiles"] = "Reloading configured projects for files"; @@ -122149,6 +123212,7 @@ var ts; /** * Container of all known scripts */ + /*@internal*/ this.filenameToScriptInfo = ts.createMap(); this.scriptInfoInNodeModulesWatchers = ts.createMap(); /** @@ -122565,9 +123629,39 @@ var ts; // this file and set of inferred projects info.delayReloadNonMixedContentFile(); this.delayUpdateProjectGraphs(info.containingProjects); + this.handleSourceMapProjects(info); } } }; + ProjectService.prototype.handleSourceMapProjects = function (info) { + // Change in d.ts, update source projects as well + if (info.sourceMapFilePath) { + if (ts.isString(info.sourceMapFilePath)) { + var sourceMapFileInfo = this.getScriptInfoForPath(info.sourceMapFilePath); + this.delayUpdateSourceInfoProjects(sourceMapFileInfo && sourceMapFileInfo.sourceInfos); + } + else { + this.delayUpdateSourceInfoProjects(info.sourceMapFilePath.sourceInfos); + } + } + // Change in mapInfo, update declarationProjects and source projects + this.delayUpdateSourceInfoProjects(info.sourceInfos); + if (info.declarationInfoPath) { + this.delayUpdateProjectsOfScriptInfoPath(info.declarationInfoPath); + } + }; + ProjectService.prototype.delayUpdateSourceInfoProjects = function (sourceInfos) { + var _this = this; + if (sourceInfos) { + sourceInfos.forEach(function (_value, path) { return _this.delayUpdateProjectsOfScriptInfoPath(path); }); + } + }; + ProjectService.prototype.delayUpdateProjectsOfScriptInfoPath = function (path) { + var info = this.getScriptInfoForPath(path); + if (info) { + this.delayUpdateProjectGraphs(info.containingProjects); + } + }; ProjectService.prototype.handleDeletedFile = function (info) { this.stopWatchingScriptInfo(info); if (!info.isScriptOpen()) { @@ -122577,6 +123671,15 @@ var ts; info.detachAllProjects(); // update projects to make sure that set of referenced files is correct this.delayUpdateProjectGraphs(containingProjects); + this.handleSourceMapProjects(info); + info.closeSourceMapFileWatcher(); + // need to recalculate source map from declaration file + if (info.declarationInfoPath) { + var declarationInfo = this.getScriptInfoForPath(info.declarationInfoPath); + if (declarationInfo) { + declarationInfo.sourceMapFilePath = undefined; + } + } } }; /** @@ -122602,7 +123705,7 @@ var ts; project.pendingReload = ts.ConfigFileProgramReloadLevel.Partial; _this.delayUpdateProjectGraphAndEnsureProjectStructureForOpenFiles(project); } - }, flags, "Wild card directory" /* WildcardDirectories */, project); + }, flags, "Wild card directory" /* WildcardDirectory */, project); }; /** Gets the config file existence info for the configured project */ /*@internal*/ @@ -122688,7 +123791,7 @@ var ts; } project.updateGraph(); if (!this.useSingleInferredProject && !project.projectRootPath) { - var _loop_26 = function (inferredProject) { + var _loop_27 = function (inferredProject) { if (inferredProject === project || inferredProject.isOrphan()) { return "continue"; } @@ -122709,7 +123812,7 @@ var ts; // Note that we need to create a copy of the array since the list of project can change for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var inferredProject = _a[_i]; - _loop_26(inferredProject); + _loop_27(inferredProject); } } return project; @@ -122820,7 +123923,8 @@ var ts; ProjectService.prototype.setConfigFileExistenceByNewConfiguredProject = function (project) { var configFileExistenceInfo = this.getConfigFileExistenceInfo(project); if (configFileExistenceInfo) { - ts.Debug.assert(configFileExistenceInfo.exists); + // The existance might not be set if the file watcher is not invoked by the time config project is created by external project + configFileExistenceInfo.exists = true; // close existing watcher if (configFileExistenceInfo.configFileWatcherForRootOfInferredProject) { var configFileName = project.getConfigFilePath(); @@ -122878,7 +123982,7 @@ var ts; watches.push("Config file for the inferred project root" /* ConfigFileForInferredRoot */); } if (this.configuredProjects.has(canonicalConfigFilePath)) { - watches.push("Config file for the program" /* ConfigFilePath */); + watches.push("Config file" /* ConfigFile */); } this.logger.info("ConfigFilePresence:: Current Watches: " + watches + ":: File: " + configFileName + " Currently impacted open files: RootsOfInferredProjects: " + inferredRoots + " OtherOpenFiles: " + otherFiles + " Status: " + status); }; @@ -123185,7 +124289,7 @@ var ts; this.logger.info("Opened configuration file " + configFileName); var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, cachedDirectoryStructureHost); // TODO: We probably should also watch the configFiles that are extended - project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file for the program" /* ConfigFilePath */, project); + project.configFileWatcher = this.watchFactory.watchFile(this.host, configFileName, function (_fileName, eventKind) { return _this.onConfigChangedForConfiguredProject(project, eventKind); }, ts.PollingInterval.High, "Config file" /* ConfigFile */, project); this.configuredProjects.set(project.canonicalConfigFilePath, project); this.setConfigFileExistenceByNewConfiguredProject(project); return project; @@ -123451,7 +124555,7 @@ var ts; var info = this.getScriptInfoForNormalizedPath(path); if (info) return info; - var configProject = this.configuredProjects.get(uncheckedFileName); + var configProject = this.configuredProjects.get(this.toPath(uncheckedFileName)); return configProject && configProject.getCompilerOptions().configFile; }; /* @internal */ @@ -123479,7 +124583,7 @@ var ts; return projects; function combineProjects(toAddInfo) { if (toAddInfo !== info) { - var _loop_27 = function (project) { + var _loop_28 = function (project) { // Add the projects only if they can use symLink targets and not already in the list if (project.languageServiceEnabled && !project.isOrphan() && @@ -123496,7 +124600,7 @@ var ts; }; for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { var project = _a[_i]; - _loop_27(project); + _loop_28(project); } } } @@ -123660,6 +124764,132 @@ var ts; ProjectService.prototype.getScriptInfoForPath = function (fileName) { return this.filenameToScriptInfo.get(fileName); }; + /*@internal*/ + ProjectService.prototype.getDocumentPositionMapper = function (project, generatedFileName, sourceFileName) { + var _this = this; + // Since declaration info and map file watches arent updating project's directory structure host (which can cache file structure) use host + var declarationInfo = this.getOrCreateScriptInfoNotOpenedByClient(generatedFileName, project.currentDirectory, this.host); + if (!declarationInfo) + return undefined; + // Try to get from cache + declarationInfo.getSnapshot(); // Ensure synchronized + if (ts.isString(declarationInfo.sourceMapFilePath)) { + // Ensure mapper is synchronized + var sourceMapFileInfo_1 = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath); + if (sourceMapFileInfo_1) { + sourceMapFileInfo_1.getSnapshot(); + if (sourceMapFileInfo_1.documentPositionMapper !== undefined) { + sourceMapFileInfo_1.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo_1.sourceInfos); + return sourceMapFileInfo_1.documentPositionMapper ? sourceMapFileInfo_1.documentPositionMapper : undefined; + } + } + declarationInfo.sourceMapFilePath = undefined; + } + else if (declarationInfo.sourceMapFilePath) { + declarationInfo.sourceMapFilePath.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, declarationInfo.sourceMapFilePath.sourceInfos); + return undefined; + } + else if (declarationInfo.sourceMapFilePath !== undefined) { + // Doesnt have sourceMap + return undefined; + } + // Create the mapper + var sourceMapFileInfo; + var mapFileNameFromDeclarationInfo; + var readMapFile = function (mapFileName, mapFileNameFromDts) { + var mapInfo = _this.getOrCreateScriptInfoNotOpenedByClient(mapFileName, project.currentDirectory, _this.host); + if (!mapInfo) { + mapFileNameFromDeclarationInfo = mapFileNameFromDts; + return undefined; + } + sourceMapFileInfo = mapInfo; + var snap = mapInfo.getSnapshot(); + if (mapInfo.documentPositionMapper !== undefined) + return mapInfo.documentPositionMapper; + return snap.getText(0, snap.getLength()); + }; + var projectName = project.projectName; + var documentPositionMapper = ts.getDocumentPositionMapper({ getCanonicalFileName: this.toCanonicalFileName, log: function (s) { return _this.logger.info(s); }, getSourceFileLike: function (f) { return _this.getSourceFileLike(f, projectName, declarationInfo); } }, declarationInfo.fileName, declarationInfo.getLineInfo(), readMapFile); + readMapFile = undefined; // Remove ref to project + if (sourceMapFileInfo) { + declarationInfo.sourceMapFilePath = sourceMapFileInfo.path; + sourceMapFileInfo.declarationInfoPath = declarationInfo.path; + sourceMapFileInfo.documentPositionMapper = documentPositionMapper || false; + sourceMapFileInfo.sourceInfos = this.addSourceInfoToSourceMap(sourceFileName, project, sourceMapFileInfo.sourceInfos); + } + else if (mapFileNameFromDeclarationInfo) { + declarationInfo.sourceMapFilePath = { + watcher: this.addMissingSourceMapFile(project.currentDirectory === this.currentDirectory ? + mapFileNameFromDeclarationInfo : + ts.getNormalizedAbsolutePath(mapFileNameFromDeclarationInfo, project.currentDirectory), declarationInfo.path), + sourceInfos: this.addSourceInfoToSourceMap(sourceFileName, project) + }; + } + else { + declarationInfo.sourceMapFilePath = false; + } + return documentPositionMapper; + }; + ProjectService.prototype.addSourceInfoToSourceMap = function (sourceFileName, project, sourceInfos) { + if (sourceFileName) { + // Attach as source + var sourceInfo = this.getOrCreateScriptInfoNotOpenedByClient(sourceFileName, project.currentDirectory, project.directoryStructureHost); + (sourceInfos || (sourceInfos = ts.createMap())).set(sourceInfo.path, true); + } + return sourceInfos; + }; + ProjectService.prototype.addMissingSourceMapFile = function (mapFileName, declarationInfoPath) { + var _this = this; + var fileWatcher = this.watchFactory.watchFile(this.host, mapFileName, function () { + var declarationInfo = _this.getScriptInfoForPath(declarationInfoPath); + if (declarationInfo && declarationInfo.sourceMapFilePath && !ts.isString(declarationInfo.sourceMapFilePath)) { + // Update declaration and source projects + _this.delayUpdateProjectGraphs(declarationInfo.containingProjects); + _this.delayUpdateSourceInfoProjects(declarationInfo.sourceMapFilePath.sourceInfos); + declarationInfo.closeSourceMapFileWatcher(); + } + }, ts.PollingInterval.High, "Missing source map file" /* MissingSourceMapFile */); + return fileWatcher; + }; + /*@internal*/ + ProjectService.prototype.getSourceFileLike = function (fileName, projectNameOrProject, declarationInfo) { + var project = projectNameOrProject.projectName ? projectNameOrProject : this.findProject(projectNameOrProject); + if (project) { + var path = project.toPath(fileName); + var sourceFile = project.getSourceFile(path); + if (sourceFile && sourceFile.resolvedPath === path) + return sourceFile; + } + // Need to look for other files. + var info = this.getOrCreateScriptInfoNotOpenedByClient(fileName, (project || this).currentDirectory, project ? project.directoryStructureHost : this.host); + if (!info) + return undefined; + // Attach as source + if (declarationInfo && ts.isString(declarationInfo.sourceMapFilePath) && info !== declarationInfo) { + var sourceMapInfo = this.getScriptInfoForPath(declarationInfo.sourceMapFilePath); + if (sourceMapInfo) { + (sourceMapInfo.sourceInfos || (sourceMapInfo.sourceInfos = ts.createMap())).set(info.path, true); + } + } + // Key doesnt matter since its only for text and lines + if (info.cacheSourceFile) + return info.cacheSourceFile.sourceFile; + // Create sourceFileLike + if (!info.sourceFileLike) { + info.sourceFileLike = { + get text() { + ts.Debug.fail("shouldnt need text"); + return ""; + }, + getLineAndCharacterOfPosition: function (pos) { + var lineOffset = info.positionToLineOffset(pos); + return { line: lineOffset.line - 1, character: lineOffset.offset - 1 }; + }, + getPositionOfLineAndCharacter: function (line, character, allowEdits) { return info.lineOffsetToPosition(line + 1, character + 1, allowEdits); } + }; + } + return info.sourceFileLike; + }; ProjectService.prototype.setHostConfiguration = function (args) { var _this = this; if (args.file) { @@ -123864,7 +125094,7 @@ var ts; }; /** @internal */ ProjectService.prototype.fileExists = function (fileName) { - return this.filenameToScriptInfo.has(fileName) || this.host.fileExists(fileName); + return !!this.getScriptInfoForNormalizedPath(fileName) || this.host.fileExists(fileName); }; ProjectService.prototype.findExternalProjectContainingOpenScriptInfo = function (info) { return ts.find(this.externalProjects, function (proj) { @@ -123874,7 +125104,6 @@ var ts; }); }; ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { - var _this = this; var configFileName; var configFileErrors; var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); // TODO: GH#18217 @@ -123930,13 +125159,7 @@ var ts; // when some file/s were closed which resulted in project removal. // It was then postponed to cleanup these script infos so that they can be reused if // the file from that old project is reopened because of opening file from here. - this.filenameToScriptInfo.forEach(function (info) { - if (!info.isScriptOpen() && info.isOrphan()) { - // if there are not projects that include this script info - delete it - _this.stopWatchingScriptInfo(info); - _this.deleteScriptInfo(info); - } - }); + this.removeOrphanScriptInfos(); this.printProjects(); this.telemetryOnOpenFile(info); return { configFileName: configFileName, configFileErrors: configFileErrors }; @@ -123973,11 +125196,66 @@ var ts; } } }; + ProjectService.prototype.removeOrphanScriptInfos = function () { + var _this = this; + var toRemoveScriptInfos = ts.cloneMap(this.filenameToScriptInfo); + this.filenameToScriptInfo.forEach(function (info) { + // If script info is open or orphan, retain it and its dependencies + if (!info.isScriptOpen() && info.isOrphan()) { + // Otherwise if there is any source info that is alive, this alive too + if (!info.sourceMapFilePath) + return; + var sourceInfos = void 0; + if (ts.isString(info.sourceMapFilePath)) { + var sourceMapInfo = _this.getScriptInfoForPath(info.sourceMapFilePath); + sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos; + } + else { + sourceInfos = info.sourceMapFilePath.sourceInfos; + } + if (!sourceInfos) + return; + if (!ts.forEachKey(sourceInfos, function (path) { + var info = _this.getScriptInfoForPath(path); + return !!info && (info.isScriptOpen() || !info.isOrphan()); + })) { + return; + } + } + // Retain this script info + toRemoveScriptInfos.delete(info.path); + if (info.sourceMapFilePath) { + var sourceInfos = void 0; + if (ts.isString(info.sourceMapFilePath)) { + // And map file info and source infos + toRemoveScriptInfos.delete(info.sourceMapFilePath); + var sourceMapInfo = _this.getScriptInfoForPath(info.sourceMapFilePath); + sourceInfos = sourceMapInfo && sourceMapInfo.sourceInfos; + } + else { + sourceInfos = info.sourceMapFilePath.sourceInfos; + } + if (sourceInfos) { + sourceInfos.forEach(function (_value, path) { return toRemoveScriptInfos.delete(path); }); + } + } + }); + toRemoveScriptInfos.forEach(function (info) { + // if there are not projects that include this script info - delete it + _this.stopWatchingScriptInfo(info); + _this.deleteScriptInfo(info); + info.closeSourceMapFileWatcher(); + }); + }; ProjectService.prototype.telemetryOnOpenFile = function (scriptInfo) { if (this.syntaxOnly || !this.eventHandler || !scriptInfo.isJavaScript() || !ts.addToSeen(this.allJsFilesForOpenFileTelemetry, scriptInfo.path)) { return; } - var info = { checkJs: !!scriptInfo.getDefaultProject().getSourceFile(scriptInfo.path).checkJsDirective }; + var project = scriptInfo.getDefaultProject(); + if (!project.languageServiceEnabled) { + return; + } + var info = { checkJs: !!project.getSourceFile(scriptInfo.path).checkJsDirective }; this.eventHandler({ eventName: server.OpenFileInfoTelemetryEvent, data: { info: info } }); }; /** @@ -123992,13 +125270,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_28 = function (proj) { + var _loop_29 = function (proj) { var knownProject = ts.find(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName(); }); result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); }; for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { var proj = currentProjects_1[_i]; - _loop_28(proj); + _loop_29(proj); } }; /* @internal */ @@ -124108,7 +125386,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_29 = function (name) { + var _loop_30 = function (name) { var rule = this_3.safelist[name]; for (var _i = 0, normalizedNames_1 = normalizedNames; _i < normalizedNames_1.length; _i++) { var root = normalizedNames_1[_i]; @@ -124126,7 +125404,7 @@ var ts; } } if (rule.exclude) { - var _loop_31 = function (exclude) { + var _loop_32 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -124153,7 +125431,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_31(exclude); + _loop_32(exclude); } } else { @@ -124169,11 +125447,11 @@ var ts; var this_3 = this; for (var _i = 0, _a = Object.keys(this.safelist); _i < _a.length; _i++) { var name = _a[_i]; - _loop_29(name); + _loop_30(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_30 = function (i) { + var _loop_31 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -124211,7 +125489,7 @@ var ts; }; var this_4 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_30(i); + _loop_31(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -124594,11 +125872,11 @@ var ts; /*getDefinition*/ undefined); return outputs; } - function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments) { + function combineProjectOutputForRenameLocations(projects, defaultProject, initialLocation, findInStrings, findInComments, hostPreferences) { var outputs = []; combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, tryAddToTodo) { var project = _a.project, location = _a.location; - for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments) || server.emptyArray; _i < _b.length; _i++) { + for (var _i = 0, _b = project.getLanguageService().findRenameLocations(location.fileName, location.pos, findInStrings, findInComments, hostPreferences.providePrefixAndSuffixTextForRename) || server.emptyArray; _i < _b.length; _i++) { var output = _b[_i]; if (!ts.contains(outputs, output, ts.documentSpansEqual) && !tryAddToTodo(project, documentSpanLocation(output))) { outputs.push(output); @@ -124616,7 +125894,7 @@ var ts; var outputs = []; combineProjectOutputWorker(projects, defaultProject, initialLocation, function (_a, getMappedLocation) { var project = _a.project, location = _a.location; - var _loop_32 = function (outputReferencedSymbol) { + var _loop_33 = function (outputReferencedSymbol) { var mappedDefinitionFile = getMappedLocation(project, documentSpanLocation(outputReferencedSymbol.definition)); var definition = mappedDefinitionFile === undefined ? outputReferencedSymbol.definition : __assign({}, outputReferencedSymbol.definition, { textSpan: ts.createTextSpan(mappedDefinitionFile.pos, outputReferencedSymbol.definition.textSpan.length), fileName: mappedDefinitionFile.fileName }); var symbolToAddTo = ts.find(outputs, function (o) { return ts.documentSpansEqual(o.definition, definition); }); @@ -124634,7 +125912,7 @@ var ts; }; for (var _i = 0, _b = project.getLanguageService().findReferences(location.fileName, location.pos) || server.emptyArray; _i < _b.length; _i++) { var outputReferencedSymbol = _b[_i]; - _loop_32(outputReferencedSymbol); + _loop_33(outputReferencedSymbol); } }, function () { return getDefinitionLocation(defaultProject, initialLocation); }); return outputs.filter(function (o) { return o.references.length !== 0; }); @@ -125598,7 +126876,8 @@ var ts; Session.prototype.getRenameInfo = function (args) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var position = this.getPositionInFile(args, file); - return project.getLanguageService().getRenameInfo(file, position); + var preferences = this.getHostPreferences(); + return project.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: preferences.allowRenameOfImportPath }); }; Session.prototype.getProjects = function (args, getScriptInfoEnsuringProjectsUptoDate, ignoreNoProjectError) { var projects; @@ -125644,11 +126923,11 @@ var ts; var file = server.toNormalizedPath(args.file); var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); - var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments); + var locations = combineProjectOutputForRenameLocations(projects, this.getDefaultProject(args), { fileName: args.file, pos: position }, !!args.findInStrings, !!args.findInComments, this.getHostPreferences()); if (!simplifiedResult) return locations; var defaultProject = this.getDefaultProject(args); - var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); + var renameInfo = this.mapRenameInfo(defaultProject.getLanguageService().getRenameInfo(file, position, { allowRenameOfImportPath: this.getHostPreferences().allowRenameOfImportPath }), ts.Debug.assertDefined(this.projectService.getScriptInfo(file))); return { info: renameInfo, locs: this.toSpanGroups(locations) }; }; Session.prototype.mapRenameInfo = function (info, scriptInfo) { @@ -125859,7 +127138,7 @@ var ts; // only to the previous line. If all this is true, then // add edits necessary to properly indent the current line. if ((args.key === "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { - var _b = scriptInfo.getLineInfo(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition; + var _b = scriptInfo.getAbsolutePositionAndLineText(args.line), lineText = _b.lineText, absolutePosition = _b.absolutePosition; if (lineText && lineText.search("\\S") < 0) { var preferredIndent = languageService.getIndentationAtPosition(file, position, formatOptions); var hasIndent = 0; @@ -126772,8 +128051,8 @@ var ts; ScriptVersionCache.prototype.getSnapshotVersion = function () { return this._getSnapshot().version; }; - ScriptVersionCache.prototype.getLineInfo = function (line) { - return this._getSnapshot().index.lineNumberToInfo(line); + ScriptVersionCache.prototype.getAbsolutePositionAndLineText = function (oneBasedLine) { + return this._getSnapshot().index.lineNumberToInfo(oneBasedLine); }; ScriptVersionCache.prototype.lineOffsetToPosition = function (line, column) { return this._getSnapshot().index.absolutePositionOfStartOfLine(line) + (column - 1); @@ -126808,6 +128087,9 @@ var ts; return ts.unchangedTextChangeRange; } }; + ScriptVersionCache.prototype.getLineCount = function () { + return this._getSnapshot().index.getLineCount(); + }; ScriptVersionCache.fromString = function (script) { var svc = new ScriptVersionCache(); var snap = new LineIndexSnapshot(0, svc, new LineIndex()); @@ -126863,8 +128145,11 @@ var ts; LineIndex.prototype.positionToColumnAndLineText = function (position) { return this.root.charOffsetToLineInfo(1, position); }; + LineIndex.prototype.getLineCount = function () { + return this.root.lineCount(); + }; LineIndex.prototype.lineNumberToInfo = function (oneBasedLine) { - var lineCount = this.root.lineCount(); + var lineCount = this.getLineCount(); if (oneBasedLine <= lineCount) { var _a = this.root.lineNumberToInfo(oneBasedLine, 0), position = _a.position, leaf = _a.leaf; return { absolutePosition: position, lineText: leaf && leaf.text }; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 0e693f698f2..03f24988ed3 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -1778,7 +1778,7 @@ declare namespace ts { type ResolvedConfigFileName = string & { _isResolvedConfigFileName: never; }; - type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles?: ReadonlyArray) => void; + type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: ReadonlyArray) => void; class OperationCanceledException { } interface CancellationToken { @@ -2689,7 +2689,6 @@ declare namespace ts { getDefaultLibLocation?(): string; writeFile: WriteFileCallback; getCurrentDirectory(): string; - getDirectories(path: string): string[]; getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; @@ -3013,6 +3012,7 @@ declare namespace ts { /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; readonly allowTextChangesInNewFiles?: boolean; + readonly providePrefixAndSuffixTextForRename?: boolean; } /** Represents a bigint literal value without requiring bigint support */ interface PseudoBigInt { @@ -4278,6 +4278,10 @@ declare namespace ts { * Get the syntax diagnostics, for all source files if source file is not supplied */ getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the declaration diagnostics, for all source files if source file is not supplied + */ + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; /** * Get all the dependencies of the file */ @@ -4364,13 +4368,11 @@ declare namespace ts { /** If provided, will be used to reset existing delayed compilation */ clearTimeout?(timeoutId: any): void; } - interface WatchCompilerHost extends WatchHost { + interface ProgramHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; - /** If provided, callback to invoke after every new program creation */ - afterProgramCreate?(program: T): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4404,6 +4406,10 @@ declare namespace ts { /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; } + interface WatchCompilerHost extends ProgramHost, WatchHost { + /** If provided, callback to invoke after every new program creation */ + afterProgramCreate?(program: T): void; + } /** * Host to create watch with root files and options */ @@ -4706,8 +4712,8 @@ declare namespace ts { getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; - getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReadonlyArray | undefined; + getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): RenameInfo; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): ReadonlyArray | undefined; getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; @@ -5150,6 +5156,9 @@ declare namespace ts { canRename: false; localizedErrorMessage: string; } + interface RenameInfoOptions { + readonly allowRenameOfImportPath?: boolean; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; diff --git a/lib/typescript.js b/lib/typescript.js index 25e193cff42..456bf6e54ec 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -75,7 +75,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = ts.versionMajorMinor + ".0-rc"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -1267,6 +1267,18 @@ var ts; return result; } ts.extend = extend; + function copyProperties(first, second) { + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + first[id] = second[id]; + } + } + } + ts.copyProperties = copyProperties; + function maybeBind(obj, fn) { + return fn ? fn.bind(obj) : undefined; + } + ts.maybeBind = maybeBind; function createMultiMap() { var map = createMap(); map.add = multiMapAdd; @@ -1985,7 +1997,11 @@ var ts; } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; function fill(length, cb) { - return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + var result = Array(length); + for (var i = 0; i < length; i++) { + result[i] = cb(i); + } + return result; } ts.fill = fill; })(ts || (ts = {})); @@ -3242,15 +3258,17 @@ var ts; CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; - CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; - CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; - CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; - CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; - CheckFlags[CheckFlags["Late"] = 1024] = "Late"; - CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter"; - CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter"; + CheckFlags[CheckFlags["HasLiteralType"] = 64] = "HasLiteralType"; + CheckFlags[CheckFlags["ContainsPublic"] = 128] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 256] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 512] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 1024] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 2048] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 4096] = "ReverseMapped"; + CheckFlags[CheckFlags["OptionalParameter"] = 8192] = "OptionalParameter"; + CheckFlags[CheckFlags["RestParameter"] = 16384] = "RestParameter"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + CheckFlags[CheckFlags["Discriminant"] = 96] = "Discriminant"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; (function (InternalSymbolName) { @@ -4002,6 +4020,16 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + /* @internal */ + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + ts.generateDjb2Hash = generateDjb2Hash; /** * Set a high stack trace limit to provide more information in case of an error. * Called for command-line and server use cases. @@ -4878,14 +4906,6 @@ var ts; return; } } - /** - * djb2 hashing algorithm - * http://www.cse.yorku.ca/~oz/hash.html - */ - function generateDjb2Hash(data) { - var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); - return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); - } function createMD5HashUsingNativeCrypto(data) { var hash = _crypto.createHash("md5"); hash.update(data); @@ -5239,6 +5259,9 @@ var ts; Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), + An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."), + A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."), + A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5394,8 +5417,6 @@ var ts; Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), - Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), - Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), @@ -5409,7 +5430,7 @@ var ts; A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), - In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values: diag(2474, ts.DiagnosticCategory.Error, "const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values_2474", "const enum member initializers can only contain literal values and other computed enum values."), 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: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'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."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), @@ -5425,11 +5446,11 @@ var ts; The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), - Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Tuple_type_0_of_length_1_has_no_element_at_index_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493", "Tuple type '{0}' of length '{1}' has no element at index '{2}'."), Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), - Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export: diag(2497, ts.DiagnosticCategory.Error, "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497", "This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export."), Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), @@ -5618,6 +5639,11 @@ var ts; Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), + No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments: diag(2743, ts.DiagnosticCategory.Error, "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743", "No overload expects {0} type arguments, but overloads do exist that expect either {1} or {2} type arguments."), + Type_parameter_defaults_can_only_reference_previously_declared_type_parameters: diag(2744, ts.DiagnosticCategory.Error, "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744", "Type parameter defaults can only reference previously declared type parameters."), + This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."), + This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."), + _0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5967,6 +5993,7 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -6045,6 +6072,7 @@ var ts; JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), + Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -6181,6 +6209,7 @@ var ts; Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), + Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"), }; })(ts || (ts = {})); var ts; @@ -6405,16 +6434,13 @@ var ts; return result; } ts.computeLineStarts = computeLineStarts; - function getPositionOfLineAndCharacter(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); + function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) { + return sourceFile.getPositionOfLineAndCharacter ? + sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) : + computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; /* @internal */ - function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); - } - ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; - /* @internal */ function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { if (line < 0 || line >= lineStarts.length) { if (allowEdits) { @@ -6990,6 +7016,7 @@ var ts; result = text.substring(start, end); // No need to use all the fragments; no _ removal needed } if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */)); return { type: 8 /* NumericLiteral */, value: "" + +result // if value is not an integer, it can be safely coerced to a number @@ -6998,9 +7025,29 @@ var ts; else { tokenValue = result; var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + checkForIdentifierStartAfterNumericLiteral(start); return { type: type, value: tokenValue }; } } + function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { + if (!isIdentifierStart(text.charCodeAt(pos), languageVersion)) { + return; + } + var identifierStart = pos; + var length = scanIdentifierParts().length; + if (length === 1 && text[identifierStart] === "n") { + if (isScientific) { + error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1); + } + else { + error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1); + } + } + else { + error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length); + pos = identifierStart; + } + } function scanOctalDigits() { var start = pos; while (isOctalDigit(text.charCodeAt(pos))) { @@ -8909,7 +8956,7 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, node.pos); } var isMissing = nodeIsMissing(errorNode); - var pos = isMissing + var pos = isMissing || ts.isJsxText(node) ? errorNode.pos : ts.skipTrivia(sourceFile.text, errorNode.pos); // These asserts should all be satisfied for a properly constructed `errorNode`. @@ -10104,6 +10151,7 @@ var ts; return node.initializer; } } + ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration; function getSingleVariableOfVariableStatement(node) { return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } @@ -12142,10 +12190,10 @@ var ts; } if (getCheckFlags(s) & 6 /* Synthetic */) { var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : - checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + var accessModifier = checkFlags & 512 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 128 /* ContainsPublic */ ? 4 /* Public */ : 16 /* Protected */; - var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + var staticModifier = checkFlags & 1024 /* ContainsStatic */ ? 32 /* Static */ : 0; return accessModifier | staticModifier; } if (s.flags & 4194304 /* Prototype */) { @@ -12392,6 +12440,10 @@ var ts; || kind === 290 /* JSDocVariadicType */; } ts.isTypeNodeKind = isTypeNodeKind; + function isAccessExpression(node) { + return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */; + } + ts.isAccessExpression = isAccessExpression; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -15270,6 +15322,8 @@ var ts; return path; } ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; function comparePathsWorker(a, b, componentComparer) { if (a === b) return 0 /* EqualTo */; @@ -15277,14 +15331,30 @@ var ts; return -1 /* LessThan */; if (b === undefined) return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, ts.getRootLength(a)); + var bRoot = b.substring(0, ts.getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var 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. var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 0; i < sharedLength; i++) { - var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; - var result = stringComparer(aComponents[i], bComponents[i]); - if (result !== 0 /* EqualTo */) { - return result; + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; } } return ts.compareValues(aComponents.length, bComponents.length); @@ -16776,15 +16846,15 @@ var ts; if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6 /* JSON */) { - var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); - result_1.referencedFiles = ts.emptyArray; - result_1.typeReferenceDirectives = ts.emptyArray; - result_1.libReferenceDirectives = ts.emptyArray; - result_1.amdDependencies = ts.emptyArray; - result_1.hasNoDefaultLib = false; - result_1.pragmas = ts.emptyMap; - return result_1; + var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_2.referencedFiles = ts.emptyArray; + result_2.typeReferenceDirectives = ts.emptyArray; + result_2.libReferenceDirectives = ts.emptyArray; + result_2.amdDependencies = ts.emptyArray; + result_2.hasNoDefaultLib = false; + result_2.pragmas = ts.emptyMap; + return result_2; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); @@ -17663,6 +17733,8 @@ var ts; return parseElement(); } function currentNode(parsingContext) { + // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse. + // // If there is an outstanding parse error that we've encountered, but not attached to // some node, then we cannot get a node from the old source tree. This is because we // want to mark the next node we encounter as being unusable. @@ -17670,25 +17742,15 @@ var ts; // Note: This may be too conservative. Perhaps we could reuse the node and set the bit // on it (or its leftmost child) as having the error. For now though, being conservative // is nice and likely won't ever affect perf. - if (parseErrorBeforeNextFinishedNode) { - return undefined; - } - if (!syntaxCursor) { - // if we don't have a cursor, we could never return a node from the old tree. + if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } var node = syntaxCursor.currentNode(scanner.getStartPos()); // Can't reuse a missing node. - if (ts.nodeIsMissing(node)) { - return undefined; - } // Can't reuse a node that intersected the change range. - if (node.intersectsChange) { - return undefined; - } // Can't reuse a node that contains a parse error. This is necessary so that we // produce the same set of errors again. - if (ts.containsParseError(node)) { + if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) { return undefined; } // We can only reuse a node if it was parsed under the same strict mode that we're @@ -17723,6 +17785,22 @@ var ts; nextToken(); return node; } + function isReusableParsingContext(parsingContext) { + switch (parsingContext) { + case 5 /* ClassMembers */: + case 2 /* SwitchClauses */: + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + case 6 /* EnumMembers */: + case 4 /* TypeMembers */: + case 8 /* VariableDeclarations */: + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + return true; + } + return false; + } function canReuseNode(node, parsingContext) { switch (parsingContext) { case 5 /* ClassMembers */: @@ -17742,22 +17820,20 @@ var ts; case 17 /* JSDocParameters */: case 16 /* Parameters */: return isReusableParameter(node); - case 18 /* RestProperties */: - return false; // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the // parser reached while looking ahead might be in the edited range (see the example // in canReuseVariableDeclaratorNode for a good case of this). - case 22 /* HeritageClauses */: + // case ParsingContext.HeritageClauses: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 19 /* TypeParameters */: + // case ParsingContext.TypeParameters: // This would probably be safe to reuse. There is no speculative parsing with // type parameters. Note that that's because type *parameters* only occur in // unambiguous *type* contexts. While type *arguments* occur in very ambiguous // *expression* contexts. - case 21 /* TupleElementTypes */: + // case ParsingContext.TupleElementTypes: // This would probably be safe to reuse. There is no speculative parsing with // tuple types. // Technically, type argument list types are probably safe to reuse. While @@ -17765,24 +17841,24 @@ var ts; // produced from speculative parsing a < as a type argument list), we only have // the types because speculative parsing succeeded. Thus, the lookahead never // went past the end of the list and rewound. - case 20 /* TypeArguments */: + // case ParsingContext.TypeArguments: // Note: these are almost certainly not safe to ever reuse. Expressions commonly // need a large amount of lookahead, and we should not reuse them as they may // have actually intersected the edit. - case 11 /* ArgumentExpressions */: + // case ParsingContext.ArgumentExpressions: // This is not safe to reuse for the same reason as the 'AssignmentExpression' // cases. i.e. a property assignment may end with an expression, and thus might // have lookahead far beyond it's old node. - case 12 /* ObjectLiteralMembers */: + // case ParsingContext.ObjectLiteralMembers: // This is probably not safe to reuse. There can be speculative parsing with // type names in a heritage clause. There can be generic names in the type // name list, and there can be left hand side expressions (which can have type // arguments.) - case 7 /* HeritageClauseElement */: + // case ParsingContext.HeritageClauseElement: // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes // on any given element. Same for children. - case 13 /* JsxAttributes */: - case 14 /* JsxChildren */: + // case ParsingContext.JsxAttributes: + // case ParsingContext.JsxChildren: } return false; } @@ -23012,17 +23088,18 @@ var ts; var libReferenceDirectives_1 = context.libReferenceDirectives; ts.forEach(ts.toArray(entryOrList), function (arg) { // TODO: GH#18217 + var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path; if (arg.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; } - else if (arg.arguments.types) { - typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + else if (types) { + typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value }); } - else if (arg.arguments.lib) { - libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + else if (lib) { + libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value }); } - else if (arg.arguments.path) { - referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + else if (path) { + referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value }); } else { reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); @@ -24694,12 +24771,12 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, !configParseResult.configFileSpecs ? function (_) { return false; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); - }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), exclude: configParseResult.configFileSpecs.validatedExcludeSpecs } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); @@ -24717,23 +24794,23 @@ var ts; } function matchesSpecs(path, includeSpecs, excludeSpecs) { if (!includeSpecs) - return function (_) { return false; }; + return function (_) { return true; }; var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { - return function (path) { return includeRe.test(path) && !excludeRe.test(path); }; + return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; } - return function (path) { return includeRe.test(path); }; + return function (path) { return !includeRe.test(path); }; } if (excludeRe) { - return function (path) { return !excludeRe.test(path); }; + return function (path) { return excludeRe.test(path); }; } - return function (_) { return false; }; + return function (_) { return true; }; } function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") { // this is of a type CommandLineOptionOfPrimitiveType return undefined; } @@ -24890,7 +24967,7 @@ var ts; result.push(tab + "}"); } result.push("}"); - return result.join(newLine); + return result.join(newLine) + newLine; } } ts.generateTSConfig = generateTSConfig; @@ -27175,6 +27252,10 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } + // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate) + if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) { + symbol.constEnumOnlyModule = false; + } if (symbolFlags & 67220415 /* Value */) { setValueDeclaration(symbol, node); } @@ -27663,7 +27744,7 @@ var ts; } function isNarrowableReference(expr) { return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || - ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || ts.isElementAccessExpression(expr) && expr.argumentExpression && (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && isNarrowableReference(expr.expression); @@ -31107,10 +31188,10 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(262144 /* TypeParameter */); - var markerSubType = createType(262144 /* TypeParameter */); + var markerSuperType = createTypeParameter(); + var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(262144 /* TypeParameter */); + var markerOtherType = createTypeParameter(); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); @@ -31300,7 +31381,6 @@ var ts; var _jsxFactoryEntity; var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); - var definitelyAssignableRelation = ts.createMap(); var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); @@ -32018,13 +32098,18 @@ var ts; } } break; + case 197 /* ArrowFunction */: + // when targeting ES6 or higher there is no 'arguments' in an arrow function + // for lower compile targets the resolved symbol is used to emit an error + if (compilerOptions.target >= 2 /* ES2015 */) { + break; + } + // falls through case 156 /* MethodDeclaration */: - case 155 /* MethodSignature */: case 157 /* Constructor */: case 158 /* GetAccessor */: case 159 /* SetAccessor */: case 239 /* FunctionDeclaration */: - case 197 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -32080,7 +32165,7 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol) && !isInTypeQuery(originalLocation)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { result.isReferenced |= meaning; } if (!result) { @@ -32158,7 +32243,8 @@ var ts; } // If we're in an external module, we can't reference value symbols created from UMD export declarations if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { - if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { + var merged = getMergedSymbol(result); + if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } @@ -32918,7 +33004,10 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { - error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 + ? "allowSyntheticDefaultImports" + : "esModuleInterop"; + error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); return symbol; } if (compilerOptions.esModuleInterop) { @@ -33213,6 +33302,12 @@ var ts; function createTypeofType() { return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); } + function createTypeParameter(symbol) { + var type = createType(262144 /* TypeParameter */); + if (symbol) + type.symbol = symbol; + return type; + } // A reserved member name starts with two underscores, but the third character cannot be an underscore // or the @ symbol. A third underscore indicates an escaped form of an identifer that started // with at least two underscores. The @ character indicates that the name is denoted by a well known ES @@ -34166,12 +34261,12 @@ var ts; return ts.createKeywordTypeNode(120 /* AnyKeyword */); } function addPropertyToElementList(propertySymbol, context, typeElements) { - var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 4096 /* ReverseMapped */); var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 2048 /* Late */) { var decl = ts.first(propertySymbol.declarations); if (hasLateBindableName(decl)) { trackComputedName(decl.name, saveEnclosingDeclaration, context); @@ -34344,7 +34439,7 @@ var ts; } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; - var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* RestParameter */; var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -34353,7 +34448,7 @@ var ts; cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); - var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* OptionalParameter */; var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, @@ -34749,6 +34844,21 @@ var ts; function isDefaultBindingContext(location) { return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); } + function getNameOfSymbolFromNameType(symbol, context) { + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 384 /* StringOrNumberLiteral */) { + var name = "" + nameType.value; + if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { + return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\""; + } + return name; + } + if (nameType.flags & 8192 /* UniqueESSymbol */) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; + } + } + } /** * Gets a human-readable name for a symbol. * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. @@ -34768,12 +34878,19 @@ var ts; } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - var name = ts.getNameOfDeclaration(declaration); - if (name) { + var name_2 = ts.getNameOfDeclaration(declaration); + if (name_2) { if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { return ts.symbolName(symbol); } - return ts.declarationNameToString(name); + if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 2048 /* Late */) && symbol.nameType && symbol.nameType.flags & 384 /* StringOrNumberLiteral */) { + // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name + var result = getNameOfSymbolFromNameType(symbol, context); + if (result !== undefined) { + return result; + } + } + return ts.declarationNameToString(name_2); } if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -34788,16 +34905,8 @@ var ts; return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } - var nameType = symbol.nameType; - if (nameType) { - if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { - return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; - } - if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { - return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; - } - } - return ts.symbolName(symbol); + var name = getNameOfSymbolFromNameType(symbol, context); + return name !== undefined ? name : ts.symbolName(symbol); } function isDeclarationVisible(node) { if (node) { @@ -35017,6 +35126,9 @@ var ts; var prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } + function getTypeOfPropertyOrIndexSignature(type, name) { + return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType; + } function isTypeAny(type) { return type && (type.flags & 1 /* Any */) !== 0; } @@ -35063,6 +35175,64 @@ var ts; var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); } + // Determine the control flow type associated with a destructuring declaration or assignment. The following + // forms of destructuring are possible: + // let { x } = obj; // BindingElement + // let [ x ] = obj; // BindingElement + // { x } = obj; // ShorthandPropertyAssignment + // { x: v } = obj; // PropertyAssignment + // [ x ] = obj; // Expression + // We construct a synthetic element access expression corresponding to 'obj.x' such that the control + // flow analyzer doesn't have to handle all the different syntactic forms. + function getFlowTypeOfDestructuring(node, declaredType) { + var reference = getSyntheticElementAccess(node); + return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType; + } + function getSyntheticElementAccess(node) { + var parentAccess = getParentElementAccess(node); + if (parentAccess && parentAccess.flowNode) { + var propName = getDestructuringPropertyName(node); + if (propName) { + var result = ts.createNode(190 /* ElementAccessExpression */, node.pos, node.end); + result.parent = node; + result.expression = parentAccess; + var literal = ts.createNode(10 /* StringLiteral */, node.pos, node.end); + literal.parent = result; + literal.text = propName; + result.argumentExpression = literal; + result.flowNode = parentAccess.flowNode; + return result; + } + } + } + function getParentElementAccess(node) { + var ancestor = node.parent.parent; + switch (ancestor.kind) { + case 186 /* BindingElement */: + case 275 /* PropertyAssignment */: + return getSyntheticElementAccess(ancestor); + case 187 /* ArrayLiteralExpression */: + return getSyntheticElementAccess(node.parent); + case 237 /* VariableDeclaration */: + return ancestor.initializer; + case 204 /* BinaryExpression */: + return ancestor.right; + } + } + function getDestructuringPropertyName(node) { + var parent = node.parent; + if (node.kind === 186 /* BindingElement */ && parent.kind === 184 /* ObjectBindingPattern */) { + return getLiteralPropertyNameText(node.propertyName || node.name); + } + if (node.kind === 275 /* PropertyAssignment */ || node.kind === 276 /* ShorthandPropertyAssignment */) { + return getLiteralPropertyNameText(node.name); + } + return "" + parent.elements.indexOf(node); + } + function getLiteralPropertyNameText(name) { + var type = getLiteralTypeFromPropertyName(name); + return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined; + } /** Return the inferred type for a binding element */ function getTypeForBindingElement(declaration) { var pattern = declaration.parent; @@ -35103,9 +35273,9 @@ var ts; else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; - var exprType = getLiteralTypeFromPropertyName(name); - var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); - type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); + var indexType = getLiteralTypeFromPropertyName(name); + var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); } } else { @@ -35122,21 +35292,13 @@ var ts; mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } + else if (isArrayLikeType(parentType)) { + var indexType = getLiteralType(index_1); + var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, declaration.name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); + } else { - // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_2 = pattern.elements.indexOf(declaration); - type = everyType(parentType, isTupleLikeType) ? - getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : - elementType; - if (!type) { - if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); - } - else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); - } - return errorType; - } + type = elementType; } } // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -35587,12 +35749,11 @@ var ts; return anyType; } // Handle export default expressions - if (ts.isSourceFile(declaration)) { - var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - if (!jsonSourceFile.statements.length) { + if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) { + if (!declaration.statements.length) { return emptyObjectType; } - var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + var type_1 = getWidenedLiteralType(checkExpression(declaration.statements[0].expression)); if (type_1.flags & 524288 /* Object */) { return getRegularTypeOfObjectLiteral(type_1); } @@ -35603,6 +35764,10 @@ var ts; } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & 512 /* ValueModule */) { + return getTypeOfFuncClassEnumModule(symbol); + } return errorType; } var type; @@ -35616,7 +35781,8 @@ var ts; || ts.isClassDeclaration(declaration) || ts.isFunctionDeclaration(declaration) || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { + || ts.isMethodSignature(declaration) + || ts.isSourceFile(declaration)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { return getTypeOfFuncClassEnumModule(symbol); @@ -35656,6 +35822,10 @@ var ts; return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } if (!popTypeResolution()) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & 512 /* ValueModule */) { + return getTypeOfFuncClassEnumModule(symbol); + } type = reportCircularityError(symbol); } return type; @@ -35849,7 +36019,7 @@ var ts; if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } - if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) { + if (ts.getCheckFlags(symbol) & 4096 /* ReverseMapped */) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -36228,9 +36398,8 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(262144 /* TypeParameter */); + type.thisType = createTypeParameter(symbol); type.thisType.isThisType = true; - type.thisType.symbol = symbol; type.thisType.constraint = type; } } @@ -36366,19 +36535,11 @@ var ts; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var type = createType(262144 /* TypeParameter */); - type.symbol = symbol; - links.declaredType = type; - } - return links.declaredType; + return links.declaredType || (links.declaredType = createTypeParameter(symbol)); } function getDeclaredTypeOfAlias(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); - } - return links.declaredType; + return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol))); } function getDeclaredTypeOfSymbol(symbol) { return tryGetDeclaredTypeOfSymbol(symbol) || errorType; @@ -36575,7 +36736,7 @@ var ts; * members. */ function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { - ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol."); + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 2048 /* Late */), "Expected a late-bound symbol."); symbol.flags |= symbolFlags; getSymbolLinks(member.symbol).lateSymbol = symbol; if (!symbol.declarations) { @@ -36632,7 +36793,7 @@ var ts; // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations. var lateSymbol = lateSymbols.get(memberName); if (!lateSymbol) - lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */)); + lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 2048 /* Late */)); // Report an error if a late-bound member has the same name as an early-bound member, // or if we have another early-bound symbol declaration with the same name and // conflicting flags. @@ -36641,10 +36802,10 @@ var ts; // If we have an existing early-bound member, combine its declarations so that we can // report an error at each declaration. var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_2 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); - lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); + var name_3 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + lateSymbol = createSymbol(0 /* None */, memberName, 2048 /* Late */); } lateSymbol.nameType = type; addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); @@ -36820,8 +36981,8 @@ var ts; var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; var restParams = ts.map(elementTypes, function (t, i) { var name = getParameterNameAtPosition(sig, restIndex_1 + i); - var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ : - i >= minLength_1 ? 4096 /* OptionalParameter */ : 0; + var checkFlags = i === tupleRestIndex_1 ? 16384 /* RestParameter */ : + i >= minLength_1 ? 8192 /* OptionalParameter */ : 0; var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; return symbol; @@ -36894,7 +37055,13 @@ var ts; // type is the union of the constituent return types. function getUnionSignatures(signatureLists) { var result; + var indexWithLengthOverOne; for (var i = 0; i < signatureLists.length; i++) { + if (signatureLists[i].length === 0) + return ts.emptyArray; + if (signatureLists[i].length > 1) { + indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets + } for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { var signature = _a[_i]; // Only process signatures with parameter lists that aren't already in the result list @@ -36919,8 +37086,82 @@ var ts; } } } + if (!ts.length(result) && indexWithLengthOverOne !== -1) { + // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single + // signature that handles all over them. We only do this when there are overloads in only one constituent. + // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of + // signatures from the type, whose ordering would be non-obvious) + var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; + var results = masterList.slice(); + var _loop_5 = function (signatures) { + if (signatures !== masterList) { + var signature_1 = signatures[0]; + ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); + results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); + if (!results) { + return "break"; + } + } + }; + for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) { + var signatures = signatureLists_1[_b]; + var state_2 = _loop_5(signatures); + if (state_2 === "break") + break; + } + result = results; + } return result || ts.emptyArray; } + function combineUnionThisParam(left, right) { + if (!left || !right) { + return left || right; + } + // A signature `this` type might be a read or a write position... It's very possible that it should be invariant + // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be + // permissive when calling, for now, we'll union the `this` types just like the overlapping-union-signature check does + var thisType = getUnionType([getTypeOfSymbol(left), getTypeOfSymbol(right)], 2 /* Subtype */); + return createSymbolWithType(left, thisType); + } + function combineUnionParameters(left, right) { + var longest = getParameterCount(left) >= getParameterCount(right) ? left : right; + var shorter = longest === left ? right : left; + var longestCount = getParameterCount(longest); + var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (var i = 0; i < longestCount; i++) { + var longestParamType = tryGetTypeAtPosition(longest, i); + var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + var unionParamType = getIntersectionType([longestParamType, shorterParamType]); + var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + var leftName = getParameterNameAtPosition(left, i); + var rightName = getParameterNameAtPosition(right, i); + var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), leftName === rightName ? leftName : "arg" + i); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args"); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfUnionMembers(left, right) { + var declaration = left.declaration; + var params = combineUnionParameters(left, right); + var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); + var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + var hasRestParam = left.hasRestParameter || right.hasRestParameter; + var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; + var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); + return result; + } function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; @@ -36938,7 +37179,7 @@ var ts; function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union // type use getPropertiesOfType (only the language service uses this). - var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); })); var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); @@ -36974,7 +37215,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_5 = function (i) { + var _loop_6 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -36997,7 +37238,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_5(i); + _loop_6(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -37073,7 +37314,7 @@ var ts; var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { var prop = _a[_i]; - var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + var checkFlags = 4096 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); inferredProp.declarations = prop.declarations; inferredProp.nameType = prop.nameType; @@ -37084,6 +37325,37 @@ var ts; } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); } + // Return the lower bound of the key type in a mapped type. Intuitively, the lower + // bound includes those keys that are known to always be present, for example because + // because of constraints on type parameters (e.g. 'keyof T' for a constrained T). + function getLowerBoundOfKeyType(type) { + if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) { + return type; + } + if (type.flags & 4194304 /* Index */) { + return getIndexType(getApparentType(type.type)); + } + if (type.flags & 16777216 /* Conditional */) { + return getLowerBoundOfConditionalType(type); + } + if (type.flags & 1048576 /* Union */) { + return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); + } + if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); + } + return neverType; + } + function getLowerBoundOfConditionalType(type) { + if (type.root.isDistributive) { + var constraint = getLowerBoundOfKeyType(type.checkType); + if (constraint !== type.checkType) { + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** Resolve the members of a mapped type { [P in K]: T } */ function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); @@ -37113,10 +37385,7 @@ var ts; } } else { - // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Then iterate over the constituents of the key type. - var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; - forEachType(iterationType, addMemberForKeyType); + forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); function addMemberForKeyType(t) { @@ -37300,7 +37569,7 @@ var ts; return list.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); }); } function getAllPossiblePropertiesOfTypes(types) { @@ -37364,7 +37633,7 @@ var ts; if (type.root.isDistributive) { var simplified = getSimplifiedType(type.checkType); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; - if (constraint) { + if (constraint && constraint !== type.checkType) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); if (!(instantiated.flags & 131072 /* Never */)) { @@ -37609,10 +37878,10 @@ var ts; commonFlags &= prop.flags; props = ts.appendIfUnique(props, prop); checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | - (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | - (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | - (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | - (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 512 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 1024 /* ContainsStatic */ : 0); if (!isPrototypeProperty(prop)) { syntheticFlag = 2 /* SyntheticProperty */; } @@ -37636,39 +37905,38 @@ var ts; return props[0]; } var declarations; - var commonType; + var firstType; var nameType; var propTypes = []; - var first = true; - var commonValueDeclaration; + var firstValueDeclaration; var hasNonUniformValueDeclaration = false; for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { var prop = props_1[_b]; - if (!commonValueDeclaration) { - commonValueDeclaration = prop.valueDeclaration; + if (!firstValueDeclaration) { + firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== commonValueDeclaration) { + else if (prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = ts.addRange(declarations, prop.declarations); var type = getTypeOfSymbol(prop); - if (first) { - commonType = type; + if (!firstType) { + firstType = type; nameType = prop.nameType; - first = false; } - else { - if (type !== commonType) { - checkFlags |= 32 /* HasNonUniformType */; - } + else if (type !== firstType) { + checkFlags |= 32 /* HasNonUniformType */; + } + if (isLiteralType(type)) { + checkFlags |= 64 /* HasLiteralType */; } propTypes.push(type); } ts.addRange(propTypes, indexTypes); var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; - if (!hasNonUniformValueDeclaration && commonValueDeclaration) { - result.valueDeclaration = commonValueDeclaration; + if (!hasNonUniformValueDeclaration && firstValueDeclaration) { + result.valueDeclaration = firstValueDeclaration; } result.declarations = declarations; result.nameType = nameType; @@ -37868,21 +38136,17 @@ var ts; var numTypeArguments = ts.length(typeArguments); if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { var result = typeArguments ? typeArguments.slice() : []; - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + // Map invalid forward references in default types to the error type for (var i = numTypeArguments; i < numTypeParameters; i++) { - result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + result[i] = errorType; } + var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny); for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, result); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { defaultType = anyType; } - result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType; } result.length = typeParameters.length; return result; @@ -37971,7 +38235,7 @@ var ts; var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); - var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */); + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 16384 /* RestParameter */); syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; if (lastParamVariadicType) { // Replace the last parameter with a rest parameter. @@ -38842,7 +39106,7 @@ var ts; if (arity) { typeParameters = new Array(arity); for (var i = 0; i < arity; i++) { - var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); + var typeParameter = typeParameters[i] = createTypeParameter(); if (i < maxLength) { var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); property.type = typeParameter; @@ -38864,7 +39128,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(262144 /* TypeParameter */); + type.thisType = createTypeParameter(); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -39365,8 +39629,13 @@ var ts; if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { - var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + if (prop.escapedName === "default" /* Default */) { + type = getLiteralType("default"); + } + else { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + } } if (type && type.flags & include) { return type; @@ -39456,14 +39725,14 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = isTypeUsableAsLateBoundName(indexType) - ? getLateBoundNameFromType(indexType) - : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) - ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) - : accessNode && ts.isPropertyName(accessNode) + var propName = isTypeUsableAsLateBoundName(indexType) ? + getLateBoundNameFromType(indexType) : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? + ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : + accessNode && ts.isPropertyName(accessNode) ? // late bound names are handled in the first branch, so here we only need to handle normal names - ? ts.getPropertyNameForPropertyNameNode(accessNode) - : undefined; + ts.getPropertyNameForPropertyNameNode(accessNode) : + undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { @@ -39485,7 +39754,12 @@ var ts; if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { var indexNode = getIndexNodeForAccessExpression(accessNode); - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + if (isTupleType(objectType)) { + error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName)); + } + else { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } } return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } @@ -39610,24 +39884,14 @@ var ts; // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we - // construct the type Box. We do not further simplify the result because mapped types can be recursive - // and we might never terminate. + // construct the type Box. if (isGenericMappedType(objectType)) { - return type.simplified = substituteIndexedMappedType(objectType, type); - } - if (objectType.flags & 262144 /* TypeParameter */) { - var constraint = getConstraintOfTypeParameter(objectType); - if (constraint && isGenericMappedType(constraint)) { - return type.simplified = substituteIndexedMappedType(constraint, type); - } + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var templateMapper = combineTypeMappers(objectType.mapper, mapper); + return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType); } return type.simplified = type; } - function substituteIndexedMappedType(objectType, type) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); - } function getIndexedAccessType(objectType, indexType, accessNode, missingType) { if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { @@ -39715,14 +39979,11 @@ var ts; if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } - // If this is a distributive conditional type and the check type is generic we need to defer - // resolution of the conditional type such that a later instantiation will properly distribute - // over union types. - var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); + var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */); var combinedMapper; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); - if (!isDeferred) { + if (!checkTypeInstantiable) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. @@ -39730,28 +39991,30 @@ var ts; } combinedMapper = combineTypeMappers(mapper, context); } - if (!isDeferred) { - if (extendsType.flags & 3 /* AnyOrUnknown */) { + // Instantiate the extends type including inferences for 'infer T' type parameters + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // We attempt to resolve the conditional type only when the check and extends types are non-generic + if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */)) { + if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) { return instantiateType(root.trueType, mapper); } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & 1 /* Any */) { return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); } - // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; // Return falseType for a definitely false extends check. We check an instantations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instatiations will be and we can just return the false branch type. - if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { return instantiateType(root.falseType, mapper); } - // Return trueType for a definitely true extends check. The definitely assignable relation excludes - // type variable constraints from consideration. Without the definitely assignable relation, the type + // Return trueType for a definitely true extends check. We check instantiations of the two + // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter + // that has no constraint. This ensures that, for example, the type // type Foo = T extends { x: string } ? string : number - // would immediately resolve to 'string' instead of being deferred. - if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + // doesn't immediately resolve to 'string' instead of being deferred. + if (isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) { return instantiateType(root.trueType, combinedMapper || mapper); } } @@ -40300,12 +40563,17 @@ var ts; function createReplacementMapper(source, target, baseMapper) { return function (t) { return t === source ? target : baseMapper(t); }; } - function wildcardMapper(type) { + function permissiveMapper(type) { return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; } + function getRestrictiveTypeParameter(tp) { + return !tp.constraint ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol)); + } + function restrictiveMapper(type) { + return type.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(type) : type; + } function cloneTypeParameter(typeParameter) { - var result = createType(262144 /* TypeParameter */); - result.symbol = typeParameter.symbol; + var result = createTypeParameter(typeParameter.symbol); result.target = typeParameter; return result; } @@ -40364,7 +40632,7 @@ var ts; } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */)); + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */)); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -40636,9 +40904,13 @@ var ts; } return type; } - function getWildcardInstantiation(type) { + function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : - type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); + type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); + } + function getRestrictiveInstantiation(type) { + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : + type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); @@ -40702,8 +40974,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - var body = node.body; - return body.kind === 218 /* Block */ ? false : isContextSensitive(body); + return !!node.body && node.body.kind !== 218 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -40820,7 +41091,7 @@ var ts; case 187 /* ArrayLiteralExpression */: return elaborateArrayLiteral(node, source, target, relation); case 268 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target, relation); + return elaborateJsxComponents(node, source, target, relation); case 197 /* ArrowFunction */: return elaborateArrowFunction(node, source, target, relation); } @@ -40961,8 +41232,117 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target, relation) { - return elaborateElementwise(generateJsxAttributes(node), source, target, relation); + function generateJsxChildren(node, getInvalidTextDiagnostic) { + var memberOffset, i, child, nameType, elem; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!ts.length(node.children)) + return [2 /*return*/]; + memberOffset = 0; + i = 0; + _a.label = 1; + case 1: + if (!(i < node.children.length)) return [3 /*break*/, 5]; + child = node.children[i]; + nameType = getLiteralType(i - memberOffset); + elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic); + if (!elem) return [3 /*break*/, 3]; + return [4 /*yield*/, elem]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + memberOffset++; + _a.label = 4; + case 4: + i++; + return [3 /*break*/, 1]; + case 5: return [2 /*return*/]; + } + }); + } + function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { + switch (child.kind) { + case 270 /* JsxExpression */: + // child is of the type of the expression + return { errorNode: child, innerExpression: child.expression, nameType: nameType }; + case 11 /* JsxText */: + if (child.containsOnlyWhiteSpaces) { + break; // Whitespace only jsx text isn't real jsx text + } + // child is a string + return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + // child is of type JSX.Element + return { errorNode: child, innerExpression: child, nameType: nameType }; + default: + return ts.Debug.assertNever(child, "Found invalid jsx child"); + } + } + function elaborateJsxComponents(node, source, target, relation) { + var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation); + var invalidTextDiagnostic; + if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) { + var containingElement = node.parent.parent; + var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName); + var childrenNameType = getLiteralType(childrenPropName); + var childrenTargetType = getIndexedAccessType(target, childrenNameType); + var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; }); + if (!ts.length(validChildren)) { + return result; + } + var moreThanOneRealChildren = ts.length(validChildren) > 1; + var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType); + var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); }); + if (moreThanOneRealChildren) { + if (arrayLikeTargetParts !== neverType) { + var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */)); + result = elaborateElementwise(generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic), realSource, arrayLikeTargetParts, relation) || result; + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + // arity mismatch + result = true; + error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, typeToString(childrenTargetType)); + } + } + else { + if (nonArrayLikeTargetParts !== neverType) { + var child = validChildren[0]; + var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic); + if (elem_1) { + result = elaborateElementwise((function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, elem_1]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); })(), source, target, relation) || result; + } + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + // arity mismatch + result = true; + error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, typeToString(childrenTargetType)); + } + } + } + return result; + function getInvalidTextualChildDiagnostic() { + if (!invalidTextDiagnostic) { + var tagNameText = ts.getTextOfNode(node.parent.tagName); + var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName); + var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName)); + var diagnostic = ts.Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2; + invalidTextDiagnostic = __assign({}, diagnostic, { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) }); + } + return invalidTextDiagnostic; + } } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -41215,7 +41595,7 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & 67108864 /* NonPrimitive */ ? true : type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : @@ -41298,9 +41678,7 @@ var ts; return true; if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) return true; - if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) - return false; - if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { + if (relation === assignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) return true; // Type number or any numeric literal type is assignable to any numeric enum type or any @@ -41470,7 +41848,7 @@ var ts; target = target.regularType; } if (source.flags & 33554432 /* Substitution */) { - source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; + source = source.substitute; } if (target.flags & 33554432 /* Substitution */) { target = target.typeVariable; @@ -41645,9 +42023,9 @@ var ts; if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + if (isExcessPropertyCheckTarget(target)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && + if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } @@ -41655,9 +42033,12 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_6 = function (prop) { + var _loop_7 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { + // Report error in terms of object types in the target as those are the only ones + // we check in isKnownProperty. + var errorTarget = filterType(target, isExcessPropertyCheckTarget); // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. @@ -41667,7 +42048,7 @@ var ts; // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) - reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget)); } else { // use the property's value declaration if the property is assigned inside the literal itself @@ -41679,14 +42060,14 @@ var ts; errorNode = propDeclaration; var name = propDeclaration.name; if (ts.isIdentifier(name)) { - suggestion = getSuggestionForNonexistentProperty(name, target); + suggestion = getSuggestionForNonexistentProperty(name, errorTarget); } } if (suggestion !== undefined) { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion); } else { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget)); } } } @@ -41695,9 +42076,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_6(prop); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_7(prop); + if (typeof state_3 === "object") + return state_3.value; } } return false; @@ -41734,7 +42115,8 @@ var ts; var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || - findBestTypeForInvokable(source, target); + findBestTypeForInvokable(source, target) || + findMostOverlappyType(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -41769,6 +42151,34 @@ var ts; return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); } } + function findMostOverlappyType(source, unionTarget) { + var bestMatch; + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target_1 = _a[_i]; + var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]); + if (overlap.flags & 4194304 /* Index */) { + // perfect overlap of keys + bestMatch = target_1; + matchingCount = Infinity; + } + else if (overlap.flags & 1048576 /* Union */) { + // We only want to account for literal types otherwise. + // If we have a union of index types, it seems likely that we + // needed to elaborate between two generic mapped types anyway. + var len = ts.length(ts.filter(overlap.types, isUnitType)); + if (len >= matchingCount) { + bestMatch = target_1; + matchingCount = len; + } + } + else if (isUnitType(overlap) && 1 >= matchingCount) { + bestMatch = target_1; + matchingCount = 1; + } + } + return bestMatch; + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { if (target.flags & 1048576 /* Union */) { @@ -41942,30 +42352,27 @@ var ts; } return result; } - function getConstraintForRelation(type) { - return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); - } function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { var flags = source.flags & target.flags; if (relation === identityRelation && !(flags & 524288 /* Object */)) { if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_2 = 0 /* False */; + var result_3 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_2; + if (result_3 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_3; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_2; + if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_3; } } } @@ -42014,24 +42421,23 @@ var ts; } // A type S is assignable to keyof T if S is assignable to keyof C, where C is the // simplified form of T or, if T doesn't simplify, the constraint of T. - if (relation !== definitelyAssignableRelation) { - var simplified = getSimplifiedType(target.type); - var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); - if (constraint) { - // We require Ternary.True here such that circular constraints don't cause - // false positives. For example, given 'T extends { [K in keyof T]: string }', - // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when - // related to other types. - if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { - return -1 /* True */; - } + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } else if (target.flags & 8388608 /* IndexedAccess */) { // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, // where C is the base constraint of T[K] - if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + if (relation !== identityRelation && + !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { var constraint = getBaseConstraintOfType(target); if (constraint && constraint !== target) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -42072,8 +42478,8 @@ var ts; return result; } } - var constraint = getConstraintForRelation(source); - if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + var constraint = getConstraintOfType(source); + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { errorInfo = saveErrorInfo; @@ -42113,7 +42519,7 @@ var ts; } } } - else if (relation !== definitelyAssignableRelation) { + else { var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { @@ -42132,7 +42538,7 @@ var ts; } else { // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + if (isPartialMappedType(target) && isEmptyObjectType(source)) { return -1 /* True */; } if (isGenericMappedType(target)) { @@ -42144,9 +42550,6 @@ var ts; } return 0 /* False */; } - if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { - return 0 /* False */; - } var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); if (relation !== identityRelation) { source = getApparentType(source); @@ -42226,10 +42629,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_3; - if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_4; + if (result_4 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_4 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -42239,10 +42642,10 @@ var ts; return propertiesIdenticalTo(source, target); } var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); - var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false); if (unmatchedProperty) { if (reportErrors) { - var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false)); if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it @@ -42318,7 +42721,7 @@ var ts; var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; - if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */ && hasDifferingDeclarations) { + if (ts.getCheckFlags(sourceProp) & 512 /* ContainsPrivate */ && hasDifferingDeclarations) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -42994,6 +43397,9 @@ var ts; function isTupleLikeType(type) { return isTupleType(type) || !!getPropertyOfType(type, "0"); } + function isArrayOrTupleLikeType(type) { + return isArrayLikeType(type) || isTupleLikeType(type); + } function getTupleElementType(type, index) { var propType = getTypeOfPropertyOfType(type, "" + index); if (propType) { @@ -43283,6 +43689,9 @@ var ts; // union includes empty object types (e.g. reducing {} | string to just {}). return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); } + if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.sameMap(type.types, getWidenedType)); + } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); } @@ -43369,6 +43778,10 @@ var ts; break; case 186 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + if (!noImplicitAny) { + // Don't issue a suggestion for binding elements since the codefix doesn't yet support them. + return; + } break; case 289 /* JSDocFunctionType */: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); @@ -43566,8 +43979,8 @@ var ts; inferTypes([inference], sourceType, templateType); return getTypeFromInference(inference); } - function getUnmatchedProperties(source, target, requireOptionalProperties) { - var properties, _i, properties_4, targetProp, sourceProp; + function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) { + var properties, _i, properties_4, targetProp, sourceProp, targetType, sourceType; return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -43575,24 +43988,34 @@ var ts; _i = 0, properties_4 = properties; _a.label = 1; case 1: - if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + if (!(_i < properties_4.length)) return [3 /*break*/, 6]; targetProp = properties_4[_i]; - if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 5]; sourceProp = getPropertyOfType(source, targetProp.escapedName); if (!!sourceProp) return [3 /*break*/, 3]; return [4 /*yield*/, targetProp]; case 2: _a.sent(); - _a.label = 3; + return [3 /*break*/, 5]; case 3: + if (!matchDiscriminantProperties) return [3 /*break*/, 5]; + targetType = getTypeOfSymbol(targetProp); + if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5]; + sourceType = getTypeOfSymbol(sourceProp); + if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5]; + return [4 /*yield*/, targetProp]; + case 4: + _a.sent(); + _a.label = 5; + case 5: _i++; return [3 /*break*/, 1]; - case 4: return [2 /*return*/]; + case 6: return [2 /*return*/]; } }); } - function getUnmatchedProperty(source, target, requireOptionalProperties) { - return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; + function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next().value; } function tupleTypesDefinitelyUnrelated(source, target) { return target.target.minLength > source.target.minLength || @@ -43602,7 +44025,8 @@ var ts; // Two tuple types with incompatible arities are definitely unrelated. // Two object types that each have a property that is unmatched in the other are definitely unrelated. return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || - !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) && + !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true); } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : @@ -44207,48 +44631,31 @@ var ts; // occurring in an apparent type position with '@' because the control flow type // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { - if (node.kind === 72 /* Identifier */) { - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; - } - if (node.kind === 100 /* ThisKeyword */) { - return "0"; - } - if (node.kind === 189 /* PropertyAccessExpression */) { - var key = getFlowCacheKey(node.expression); - return key && key + "." + ts.idText(node.name); - } - if (node.kind === 186 /* BindingElement */) { - var container = node.parent.parent; - var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); - var text = getBindingElementNameText(node); - var result = key && text && (key + "." + text); - return result; + switch (node.kind) { + case 72 /* Identifier */: + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + case 100 /* ThisKeyword */: + return "0"; + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + return getFlowCacheKey(node.expression); + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + var propName = getAccessedPropertyName(node); + if (propName !== undefined) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + propName; + } } return undefined; } - function getBindingElementNameText(element) { - var parent = element.parent; - if (parent.kind === 184 /* ObjectBindingPattern */) { - var name = element.propertyName || element.name; - switch (name.kind) { - case 72 /* Identifier */: - return ts.idText(name); - case 149 /* ComputedPropertyName */: - return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; - case 10 /* StringLiteral */: - case 8 /* NumericLiteral */: - return name.text; - default: - // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined - ts.Debug.fail("Unexpected name kind for binding element name"); - } - } - else { - return "" + parent.elements.indexOf(element); - } - } function isMatchingReference(source, target) { + switch (target.kind) { + case 195 /* ParenthesizedExpression */: + case 213 /* NonNullExpression */: + return isMatchingReference(source, target.expression); + } switch (source.kind) { case 72 /* Identifier */: return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || @@ -44258,34 +44665,24 @@ var ts; return target.kind === 100 /* ThisKeyword */; case 98 /* SuperKeyword */: return target.kind === 98 /* SuperKeyword */; + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + return isMatchingReference(source.expression, target); case 189 /* PropertyAccessExpression */: case 190 /* ElementAccessExpression */: - return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 186 /* BindingElement */: - if (target.kind !== 189 /* PropertyAccessExpression */) - return false; - var t = target; - if (t.name.escapedText !== getBindingElementNameText(source)) - return false; - if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { - return true; - } - if (source.parent.parent.kind === 237 /* VariableDeclaration */) { - var maybeId = source.parent.parent.initializer; - return !!maybeId && isMatchingReference(maybeId, t.expression); - } } return false; } function getAccessedPropertyName(access) { - return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + return access.kind === 189 /* PropertyAccessExpression */ ? access.name.escapedText : ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : undefined; } function containsMatchingReference(source, target) { - while (source.kind === 189 /* PropertyAccessExpression */) { + while (ts.isAccessExpression(source)) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -44298,42 +44695,37 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 189 /* PropertyAccessExpression */ && + var name; + return ts.isAccessExpression(target) && containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + (name = getAccessedPropertyName(target)) !== undefined && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), name); } function getDeclaredTypeOfReference(expr) { if (expr.kind === 72 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 189 /* PropertyAccessExpression */) { + if (ts.isAccessExpression(expr)) { var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + if (type) { + var propName = getAccessedPropertyName(expr); + return propName !== undefined ? getTypeOfPropertyOfType(type, propName) : undefined; + } } return undefined; } function isDiscriminantType(type) { - if (type.flags & 1048576 /* Union */) { - if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { - return true; - } - var combined = 0; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - combined |= t.flags; - } - if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { - return true; - } - } - return false; + return !!(type.flags & 1048576 /* Union */ && + (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */) || !isGenericIndexType(type))); } function isDiscriminantProperty(type, name) { if (type && type.flags & 1048576 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = + (prop.checkFlags & 96 /* Discriminant */) === 96 /* Discriminant */ && + isDiscriminantType(getTypeOfSymbol(prop)); } return !!prop.isDiscriminantProperty; } @@ -45192,25 +45584,23 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 1048576 /* Union */) || - expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { return false; } - var access = expr; - var name = getAccessedPropertyName(access); - if (!name) { + var name = getAccessedPropertyName(expr); + if (name === undefined) { return false; } - return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); - if (!propName) { + if (propName === undefined) { return type; } var propType = getTypeOfPropertyOfType(type, propName); var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOrIndexSignature(t, propName), narrowedPropType); }); } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { @@ -45555,9 +45945,8 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { - var accessExpression = invokedExpression; - var possibleReference = ts.skipParentheses(accessExpression.expression); + if (ts.isAccessExpression(invokedExpression)) { + var possibleReference = ts.skipParentheses(invokedExpression.expression); if (isMatchingReference(reference, possibleReference)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } @@ -45974,7 +46363,7 @@ var ts; } function checkThisBeforeSuper(node, container, diagnosticMessage) { var containingClassDecl = container.parent; - var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); + var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl); // If a containing class does not have extends clause or the class extends null // skip checking whether super statement is called before "this" accessing. if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { @@ -46295,7 +46684,7 @@ var ts; } // at this point the only legal case for parent is ClassLikeDeclaration var classLikeDeclaration = container.parent; - if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { + if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); return errorType; } @@ -46452,6 +46841,30 @@ var ts; tryGetTypeAtPosition(contextualSignature, index); } } + function getContextualTypeForVariableLikeDeclaration(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + switch (declaration.kind) { + case 151 /* Parameter */: + return getContextuallyTypedParameterType(declaration); + case 186 /* BindingElement */: + return getContextualTypeForBindingElement(declaration); + // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent + } + } + function getContextualTypeForBindingElement(declaration) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + var parentType = getContextualTypeForVariableLikeDeclaration(parentDeclaration); + if (parentType && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text !== undefined) { + return getTypeOfPropertyOfType(parentType, text); + } + } + } // In a variable, parameter or property declaration with a type annotation, // the contextual type of an initializer expression is the type of the variable, parameter or property. // Otherwise, in a parameter declaration of a contextually typed function expression, @@ -46463,32 +46876,13 @@ var ts; function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; if (ts.hasInitializer(declaration) && node === declaration.initializer) { - var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - return getTypeFromTypeNode(typeNode); + var result = getContextualTypeForVariableLikeDeclaration(declaration); + if (result) { + return result; } - if (declaration.kind === 151 /* Parameter */) { - var type = getContextuallyTypedParameterType(declaration); - if (type) { - return type; - } - } - if (ts.isBindingPattern(declaration.name)) { + if (ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } - if (ts.isBindingPattern(declaration.parent)) { - var parentDeclaration = declaration.parent.parent; - var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 186 /* BindingElement */) { - var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); - if (parentTypeNode && !ts.isBindingPattern(name)) { - var text = ts.getTextOfPropertyName(name); - if (text) { - return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); - } - } - } - } } return undefined; } @@ -46741,18 +47135,30 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForChildJsxExpression(node) { + function getContextualTypeForChildJsxExpression(node, child) { var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); - return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { + return undefined; + } + var childIndex = node.children.indexOf(child); + var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName); + return childFieldType && mapType(childFieldType, function (t) { + if (isArrayLikeType(t)) { + return getIndexedAccessType(t, getLiteralType(childIndex)); + } + else { + return t; + } + }, /*noReductions*/ true); } function getContextualTypeForJsxExpression(node) { var exprParent = node.parent; return ts.isJsxAttributeLike(exprParent) ? getContextualType(node) : ts.isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent, node) : undefined; } function getContextualTypeForJsxAttribute(attribute) { @@ -46919,6 +47325,27 @@ var ts; return propsType; } function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + if (sig.unionSignatures) { + // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input + // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature, + // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur + // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input. + // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane. + var results = []; + for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + var instance = getReturnTypeOfSignature(signature); + if (isTypeAny(instance)) { + return instance; + } + var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation); + if (!propType) { + return; + } + results.push(propType); + } + return getIntersectionType(results); + } var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } @@ -47310,7 +47737,7 @@ var ts; var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? computedNameType : undefined; var prop = nameType ? - createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : + createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 2048 /* Late */) : createSymbol(4 /* Property */ | member.flags, member.escapedName); if (nameType) { prop.nameType = nameType; @@ -47910,7 +48337,7 @@ var ts; return true; } } - else if (targetType.flags & 3145728 /* UnionOrIntersection */) { + else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -47918,12 +48345,14 @@ var ts; } } } - else if (targetType.flags & 16777216 /* Conditional */) { - return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || - isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); - } return false; } + function isExcessPropertyCheckTarget(type) { + return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) || + type.flags & 67108864 /* NonPrimitive */ || + type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) || + type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget)); + } function checkJsxExpression(node, checkMode) { if (node.expression) { var type = checkExpression(node.expression, checkMode); @@ -47964,7 +48393,7 @@ var ts; function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; - if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(prop) & 512 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; @@ -48328,7 +48757,7 @@ var ts; } } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (nodeForCheckWriteOnly && isInTypeQuery(nodeForCheckWriteOnly) || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { @@ -48354,7 +48783,7 @@ var ts; } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind === 189 /* PropertyAccessExpression */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -49039,15 +49468,32 @@ var ts; return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { - var min = Infinity; - var max = -Infinity; + var argCount = typeArguments.length; + // No overloads exist + if (signatures.length === 1) { + var sig = signatures[0]; + var min_1 = getMinTypeArgumentCount(sig.typeParameters); + var max = ts.length(sig.typeParameters); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, min_1 < max ? min_1 + "-" + max : min_1, argCount); + } + // Overloads exist + var belowArgCount = -Infinity; + var aboveArgCount = Infinity; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, ts.length(sig.typeParameters)); + var min_2 = getMinTypeArgumentCount(sig.typeParameters); + var max = ts.length(sig.typeParameters); + if (min_2 > argCount) { + aboveArgCount = Math.min(aboveArgCount, min_2); + } + else if (max < argCount) { + belowArgCount = Math.max(belowArgCount, max); + } } - var paramCount = min === max ? min : min + "-" + max; - return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) { + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; @@ -49276,7 +49722,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_7 = function (i) { + var _loop_8 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -49287,7 +49733,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_7(i); + _loop_8(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -49444,7 +49890,7 @@ var ts; */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { @@ -49952,6 +50398,7 @@ var ts; if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.nameType = getLiteralType("default"); newSymbol.target = resolveSymbol(symbol); memberTable.set("default" /* Default */, newSymbol); var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); @@ -50945,20 +51392,18 @@ var ts; if (rightIsThis === void 0) { rightIsThis = false; } if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 149 /* ComputedPropertyName */) { - checkComputedPropertyName(name); - } - if (isComputedNonLiteralName(name)) { - return undefined; - } - var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); - if (type) { - // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); - } - else { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + var text = ts.getTextOfPropertyName(name); + if (text) { + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + } } + var exprType = getLiteralTypeFromPropertyName(name); + var elementType = getIndexedAccessType(objectLiteralType, exprType, name); + var type = getFlowTypeOfDestructuring(property, elementType); + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else if (property.kind === 277 /* SpreadAssignment */) { if (languageVersion < 6 /* ESNext */) { @@ -50978,23 +51423,6 @@ var ts; error(property, ts.Diagnostics.Property_assignment_expected); } } - function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { - if (isTypeAny(objectLiteralType)) { - return objectLiteralType; - } - var type; - var text = ts.getTextOfPropertyName(name); - if (text) { // TODO: GH#26379 - var prop = getPropertyOfType(objectLiteralType, text); - if (prop) { - markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); - type = getTypeOfSymbol(prop); - } - type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); - } - return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); - } function checkArrayLiteralAssignment(node, sourceType, checkMode) { var elements = node.elements; if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { @@ -51014,39 +51442,30 @@ var ts; var element = elements[elementIndex]; if (element.kind !== 210 /* OmittedExpression */) { if (element.kind !== 208 /* SpreadElement */) { - var propName = "" + elementIndex; - var type = isTypeAny(sourceType) ? sourceType : - everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : - elementType; - if (type) { + var indexType = getLiteralType(elementIndex); + if (isArrayLikeType(sourceType)) { + // We create a synthetic expression so that getIndexedAccessType doesn't get confused + // when the element is a SyntaxKind.ElementAccessExpression. + var elementType_2 = getIndexedAccessType(sourceType, indexType, createSyntheticExpression(element, indexType)); + var type = getFlowTypeOfDestructuring(element, elementType_2); return checkDestructuringAssignment(element, type, checkMode); } - // We still need to check element expression here because we may need to set appropriate flag on the expression - // such as NodeCheckFlags.LexicalThis on "this"expression. - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } + return checkDestructuringAssignment(element, elementType, checkMode); + } + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { - if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + var restExpression = element.expression; + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { - var restExpression = element.expression; - if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { - error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - else { - checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = everyType(sourceType, isTupleType) ? - mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : - createArrayType(elementType); - return checkDestructuringAssignment(restExpression, type, checkMode); - } + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); } } } @@ -51567,7 +51986,8 @@ var ts; var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) || - isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + isTypeAssertion(initializer) || + isLiteralOfContextualType(type, getContextualType(initializer)) ? type : getWidenedLiteralType(type); if (ts.isInJSFile(declaration)) { if (widened.flags & 98304 /* Nullable */) { reportImplicitAny(declaration, anyType); @@ -52250,7 +52670,7 @@ var ts; // Constructors of classes with no extends clause may not contain super calls, whereas // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; - if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { + if (ts.getClassExtendsHeritageElement(containingClassDecl)) { captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); @@ -52444,7 +52864,6 @@ var ts; break; } } - checkGrammarForDisallowedTrailingComma(node.elementTypes); ts.forEach(node.elementTypes, checkSourceElement); } function checkUnionOrIntersectionType(node) { @@ -52813,10 +53232,10 @@ var ts; case 248 /* ImportEqualsDeclaration */: case 251 /* NamespaceImport */: case 250 /* ImportClause */: - var result_4 = 0 /* None */; + var result_5 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); - return result_4; + ts.forEach(target.declarations, function (d) { result_5 |= getDeclarationSpaces(d); }); + return result_5; case 237 /* VariableDeclaration */: case 186 /* BindingElement */: case 239 /* FunctionDeclaration */: @@ -53304,7 +53723,12 @@ var ts; return; } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + if (ts.isQualifiedName(node.name)) { + error(node.name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(node.name), ts.entityNameToString(node.name.left)); + } + else { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name)); + } } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && @@ -54842,6 +55266,7 @@ var ts; if (produceDiagnostics) { if (node.default) { seenDefault = true; + checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i); } else if (seenDefault) { error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); @@ -54855,6 +55280,23 @@ var ts; } } } + /** Check that type parameter defaults only reference previously declared type parameters */ + function checkTypeParametersNotReferenced(root, typeParameters, index) { + visit(root); + function visit(node) { + if (node.kind === 164 /* TypeReference */) { + var type = getTypeFromTypeReference(node); + if (type.flags & 262144 /* TypeParameter */) { + for (var i = index; i < typeParameters.length; i++) { + if (type.symbol === getSymbolOfNode(typeParameters[i])) { + error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters); + } + } + } + } + ts.forEachChild(node, visit); + } + } /** Check that type parameter lists are identical across multiple declarations */ function checkTypeParameterListsIdentical(symbol) { if (symbol.declarations.length === 1) { @@ -55045,7 +55487,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_8 = function (member) { + var _loop_9 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -55064,7 +55506,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_8(member); + _loop_9(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -55338,7 +55780,7 @@ var ts; return 0; } else if (isConstEnum) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values); } else if (member.parent.flags & 4194304 /* Ambient */) { error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); @@ -57420,7 +57862,7 @@ var ts; isLateBound: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); var symbol = node && getSymbolOfNode(node); - return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); + return !!(symbol && ts.getCheckFlags(symbol) & 2048 /* Late */); }, getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { @@ -58012,9 +58454,6 @@ var ts; if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070 checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); } - if (ts.isBindingPattern(parameter.name)) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } if (parameter.questionToken) { return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); } @@ -59000,9 +59439,6 @@ var ts; JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; // tslint:enable variable-name })(JsxNames || (JsxNames = {})); - function typeIsLiteralType(type) { - return !!(type.flags & 2944 /* Literal */); - } })(ts || (ts = {})); var ts; (function (ts) { @@ -64566,15 +65002,19 @@ var ts; // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + function getLineInfo(text, lineStarts) { + return { + getLineCount: function () { return lineStarts.length; }, + getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); } + }; + } + ts.getLineInfo = getLineInfo; /** * Tries to find the sourceMappingURL comment at the end of a file. - * @param text The source text of the file. - * @param lineStarts The line starts of the file. */ - function tryGetSourceMappingURL(text, lineStarts) { - if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } - for (var index = lineStarts.length - 1; index >= 0; index--) { - var line = text.substring(lineStarts[index], lineStarts[index + 1]); + function tryGetSourceMappingURL(lineInfo) { + for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) { + var line = lineInfo.getLineText(index); var comment = sourceMapCommentRegExp.exec(line); if (comment) { return comment[1]; @@ -64818,7 +65258,10 @@ var ts; && left.sourcePosition === right.sourcePosition; } function compareSourcePositions(left, right) { - return ts.compareValues(left.sourceIndex, right.sourceIndex); + // Compares sourcePosition without comparing sourceIndex + // since the mappings are grouped by sourceIndex + ts.Debug.assert(left.sourceIndex === right.sourceIndex); + return ts.compareValues(left.sourcePosition, right.sourcePosition); } function compareGeneratedPositions(left, right) { return ts.compareValues(left.generatedPosition, right.generatedPosition); @@ -64833,11 +65276,9 @@ var ts; var mapDirectory = ts.getDirectoryPath(mapPath); var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); - var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); - var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath); var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); - var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); - var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; })); var decodedMappings; var generatedMappings; var sourceMappings; @@ -64847,16 +65288,15 @@ var ts; }; function processMapping(mapping) { var generatedPosition = generatedFile !== undefined - ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true) : -1; var source; var sourcePosition; if (isSourceMapping(mapping)) { - var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; - var sourceFile = host.getSourceFileLike(sourceFilePath); + var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]); source = map.sources[mapping.sourceIndex]; sourcePosition = sourceFile !== undefined - ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true) : -1; } return { @@ -67274,6 +67714,7 @@ var ts; switch (node.literal.kind) { case 10 /* StringLiteral */: return ts.createIdentifier("String"); + case 202 /* PrefixUnaryExpression */: case 8 /* NumericLiteral */: return ts.createIdentifier("Number"); case 9 /* BigIntLiteral */: @@ -71044,7 +71485,7 @@ var ts; if (node.name) { enableSubstitutionsForBlockScopedBindings(); } - var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + var extendsClauseElement = ts.getClassExtendsHeritageElement(node); var classFunction = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -71453,7 +71894,7 @@ var ts; * synthesized call to `super` */ function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; + return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper); } /** * Adds statements to the body of a function-like node if it contains a rest parameter. @@ -71470,10 +71911,10 @@ var ts; return; } // `declarationName` is the name of the local declaration for the parameter. - var declarationName = ts.getMutableClone(parameter.name); + var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined); ts.setEmitFlags(declarationName, 48 /* NoSourceMap */); // `expressionName` is the name of the parameter used in expressions. - var expressionName = ts.getSynthesizedClone(parameter.name); + var expressionName = parameter.name.kind === 72 /* Identifier */ ? ts.getSynthesizedClone(parameter.name) : declarationName; var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; @@ -71497,6 +71938,11 @@ var ts; ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); statements.push(forStatement); + if (parameter.name.kind !== 72 /* Identifier */) { + // do the actual destructuring of the rest parameter if necessary + statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */)); + } } /** * Adds a statement to capture the `this` of a function declaration if it is needed. @@ -79732,6 +80178,7 @@ var ts; case 241 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; + case 166 /* ConstructorType */: case 161 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; @@ -79750,6 +80197,7 @@ var ts; diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; + case 165 /* FunctionType */: case 239 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; @@ -80327,7 +80775,10 @@ var ts; if (!ts.isLateVisibilityPaintedStatement(i)) { return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); } + var priorNeedsDeclare = needsDeclare; + needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + needsDeclare = priorNeedsDeclare; lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); } // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list @@ -80690,7 +81141,8 @@ var ts; var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression - var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 + var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default"; + var newId_1 = ts.createOptimisticUniqueName(oldId + "_base"); getSymbolAccessibilityDiagnostic = function () { return ({ diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: extendsClause_1, @@ -80844,7 +81296,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_9 = function (range) { + var _loop_10 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -80858,7 +81310,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_9(range); + _loop_10(range); } } return prop; @@ -82748,18 +83200,22 @@ var ts; function emitPropertyAccessExpression(node) { var indentBeforeDot = false; var indentAfterDot = false; + var dotRangeFirstCommentStart = ts.skipTrivia(currentSourceFile.text, node.expression.end, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ true); + var dotRangeStart = ts.skipTrivia(currentSourceFile.text, dotRangeFirstCommentStart); + var dotRangeEnd = dotRangeStart + 1; if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { - var dotRangeStart = node.expression.end; - var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; var dotToken = ts.createToken(24 /* DotToken */); - dotToken.pos = dotRangeStart; + dotToken.pos = node.expression.end; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } emitExpression(node.expression); increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + var dotHasCommentTrivia = dotRangeFirstCommentStart !== dotRangeStart; + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression, dotHasCommentTrivia); if (shouldEmitDotDot) { writePunctuation("."); } @@ -82770,13 +83226,15 @@ var ts; } // 1..toString is a valid property access, emit a dot after the literal // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal - function needsDotDotForPropertyAccess(expression) { + function needsDotDotForPropertyAccess(expression, dotHasTrivia) { expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); - return !expression.numericLiteralFlags - && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); + // If he number will be printed verbatim and it doesn't already contain a dot, add one + // if the expression doesn't have any comments that will be emitted. + return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)) && + (!dotHasTrivia || printerOptions.removeComments); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -83527,6 +83985,7 @@ var ts; function emitJsxSelfClosingElement(node) { writePunctuation("<"); emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); writeSpace(); emit(node.attributes); writePunctuation("/>"); @@ -83540,6 +83999,7 @@ var ts; writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } @@ -85145,7 +85605,7 @@ var ts; if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { return; } - var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character; sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, /*nameIndex*/ undefined); } @@ -85554,7 +86014,7 @@ var ts; }, flags); } function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { - return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2); } function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); @@ -85635,7 +86095,7 @@ var ts; var text; try { ts.performance.mark("beforeIORead"); - text = system.readFile(fileName, options.charset); + text = compilerHost.readFile(fileName); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -85661,7 +86121,12 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - system.createDirectory(directoryPath); + if (compilerHost.createDirectory) { + compilerHost.createDirectory(directoryPath); + } + else { + system.createDirectory(directoryPath); + } } } var outputFingerprints; @@ -85713,7 +86178,7 @@ var ts; } var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); var realpath = system.realpath && (function (path) { return system.realpath(path); }); - return { + var compilerHost = { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -85729,10 +86194,112 @@ var ts; getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }, + createDirectory: function (d) { return system.createDirectory(d); } }; + return compilerHost; } ts.createCompilerHostWorker = createCompilerHostWorker; + /*@internal*/ + function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) { + var originalReadFile = host.readFile; + var originalFileExists = host.fileExists; + var originalDirectoryExists = host.directoryExists; + var originalCreateDirectory = host.createDirectory; + var originalWriteFile = host.writeFile; + var readFileCache = ts.createMap(); + var fileExistsCache = ts.createMap(); + var directoryExistsCache = ts.createMap(); + var sourceFileCache = ts.createMap(); + var readFileWithCache = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value || undefined; + return setReadFileCache(key, fileName); + }; + var setReadFileCache = function (key, fileName) { + var newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue || false); + return newValue; + }; + host.readFile = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value; // could be .d.ts from output + if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) { + return originalReadFile.call(host, fileName); + } + return setReadFileCache(key, fileName); + }; + var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { + var key = toPath(fileName); + var value = sourceFileCache.get(key); + if (value) + return value; + var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile); + if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) { + sourceFileCache.set(key, sourceFile); + } + return sourceFile; + } : undefined; + // fileExists for any kind of extension + host.fileExists = function (fileName) { + var key = toPath(fileName); + var value = fileExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + if (originalWriteFile) { + host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) { + var key = toPath(fileName); + fileExistsCache.delete(key); + var value = readFileCache.get(key); + if (value && value !== data) { + readFileCache.delete(key); + sourceFileCache.delete(key); + } + else if (getSourceFileWithCache) { + var sourceFile = sourceFileCache.get(key); + if (sourceFile && sourceFile.text !== data) { + sourceFileCache.delete(key); + } + } + originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles); + }; + } + // directoryExists + if (originalDirectoryExists && originalCreateDirectory) { + host.directoryExists = function (directory) { + var key = toPath(directory); + var value = directoryExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + return { + originalReadFile: originalReadFile, + originalFileExists: originalFileExists, + originalDirectoryExists: originalDirectoryExists, + originalCreateDirectory: originalCreateDirectory, + originalWriteFile: originalWriteFile, + getSourceFileWithCache: getSourceFileWithCache, + readFileWithCache: readFileWithCache + }; + } + ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (ts.getEmitDeclarations(program.getCompilerOptions())) { @@ -86065,7 +86632,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); - var configParsingHost = parseConfigHostFromCompilerHost(host); + var configParsingHost = parseConfigHostFromCompilerHostLike(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); @@ -86111,6 +86678,12 @@ var ts; var sourceFileToPackageName = ts.createMap(); // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. var redirectTargetsMap = ts.createMultiMap(); + /** + * map with + * - SourceFile if present + * - false if sourceFile missing for source of project reference redirect + * - undefined otherwise + */ var filesByName = ts.createMap(); var missingFilePaths; // stores 'filename -> file association' ignoring case @@ -86171,7 +86744,10 @@ var ts; }); } } - missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) { + var path = _a[0], file = _a[1]; + return file === undefined ? path : undefined; + })); files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); processingDefaultLibFiles = undefined; processingOtherFiles = undefined; @@ -86317,13 +86893,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_5 = []; + var result_6 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_5.push(resolvedModule); + result_6.push(resolvedModule); } - return result_5; + return result_6; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -86779,7 +87355,7 @@ var ts; return getSourceFileByPath(toPath(fileName)); } function getSourceFileByPath(path) { - return filesByName.get(path); + return filesByName.get(path) || undefined; } function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { if (sourceFile) { @@ -87257,7 +87833,7 @@ var ts; } /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ function getSourceFileFromReference(referencingFile, ref) { - return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; }); } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { @@ -87363,7 +87939,9 @@ var ts; processReferencedFiles(file_1, isDefaultLib); processTypeReferenceDirectives(file_1); } - processLibReferenceDirectives(file_1); + if (!options.noLib) { + processLibReferenceDirectives(file_1); + } modulesWithElidedImports.set(file_1.path, false); processImportedModules(file_1); } @@ -87374,7 +87952,7 @@ var ts; processImportedModules(file_1); } } - return file_1; + return file_1 || undefined; } var redirectedPath; if (refFile) { @@ -87440,7 +88018,9 @@ var ts; processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } - processLibReferenceDirectives(file); + if (!options.noLib) { + processLibReferenceDirectives(file); + } // always process imported modules to record module name resolutions processImportedModules(file); if (isDefaultLib) { @@ -87453,9 +88033,12 @@ var ts; return file; } function addFileToFilesByName(file, path, redirectedPath) { - filesByName.set(path, file); if (redirectedPath) { filesByName.set(redirectedPath, file); + filesByName.set(path, file || false); + } + else { + filesByName.set(path, file); } } function getProjectReferenceRedirect(fileName) { @@ -88118,21 +88701,22 @@ var ts; } ts.createProgram = createProgram; /* @internal */ - function parseConfigHostFromCompilerHost(host) { + function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) { + if (directoryStructureHost === void 0) { directoryStructureHost = host; } return { - fileExists: function (f) { return host.fileExists(f); }, + fileExists: function (f) { return directoryStructureHost.fileExists(f); }, readDirectory: function (root, extensions, excludes, includes, depth) { - ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(root, extensions, excludes, includes, depth); + ts.Debug.assertDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); }, - readFile: function (f) { return host.readFile(f); }, + readFile: function (f) { return directoryStructureHost.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, - onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }), trace: host.trace ? function (s) { return host.trace(s); } : undefined }; } - ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike; function resolveProjectReferencePath(hostOrRef, ref) { var passedInRef = ref ? ref : hostOrRef; return ts.resolveConfigFileProjectName(passedInRef.path); @@ -88199,6 +88783,10 @@ var ts; } } ts.getFileEmitOutput = getFileEmitOutput; + function cloneMapOrUndefined(map) { + return map ? ts.cloneMap(map) : undefined; + } + ts.cloneMapOrUndefined = cloneMapOrUndefined; })(ts || (ts = {})); /*@internal*/ (function (ts) { @@ -88346,12 +88934,35 @@ var ts; fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, - allFilesExcludingDefaultLibraryFile: undefined, - allFileNames: undefined + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature }; } BuilderState.create = create; + /** + * Releases needed properties + */ + function releaseCache(state) { + state.allFilesExcludingDefaultLibraryFile = undefined; + state.allFileNames = undefined; + } + BuilderState.releaseCache = releaseCache; + /** + * Creates a clone of the state + */ + function clone(state) { + var fileInfos = ts.createMap(); + state.fileInfos.forEach(function (value, key) { + fileInfos.set(key, __assign({}, value)); + }); + // Dont need to backup allFiles info since its cache anyway + return { + fileInfos: fileInfos, + referencedMap: ts.cloneMapOrUndefined(state.referencedMap), + exportedModulesMap: ts.cloneMapOrUndefined(state.exportedModulesMap), + hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature), + }; + } + BuilderState.clone = clone; /** * Gets the files affected by the path from the program */ @@ -88600,7 +89211,7 @@ var ts; var seenFileNamesMap = ts.createMap(); // Start with the paths this file was referenced by seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); - var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath); while (queue.length > 0) { var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { @@ -88608,7 +89219,7 @@ var ts; seenFileNamesMap.set(currentPath, currentSourceFile); if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 queue.push.apply(// TODO: GH#18217 - queue, getReferencedByPaths(state, currentPath)); + queue, getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } } @@ -88632,24 +89243,32 @@ var ts; var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); - if (!compilerOptions.outFile && !compilerOptions.out) { + state.compilerOptions = compilerOptions; + // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them + // With --isolatedModules, emitting changed file doesnt emit dependent files so we cant know of dependent files to retrieve errors so dont cache the errors + if (!compilerOptions.outFile && !compilerOptions.out && !compilerOptions.isolatedModules) { state.semanticDiagnosticsPerFile = ts.createMap(); } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; + var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { - ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + var affectedSignatures = oldState.currentAffectedFilesSignatures; + ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); } if (canCopySemanticDiagnostics) { ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); } // Copy old state's changed files set ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit; + state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; + } } // Update changed files and copy semantic diagnostics if we can var referencedMap = state.referencedMap; @@ -88673,7 +89292,7 @@ var ts; state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { - var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + var sourceFile = newProgram.getSourceFileByPath(sourceFilePath); if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { return; } @@ -88693,6 +89312,36 @@ var ts; }); return state; } + /** + * Releases program and other related not needed properties + */ + function releaseCache(state) { + ts.BuilderState.releaseCache(state); + state.program = undefined; + } + /** + * Creates a clone of the state + */ + function cloneBuilderProgramState(state) { + var newState = ts.BuilderState.clone(state); + newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile); + newState.changedFilesSet = ts.cloneMap(state.changedFilesSet); + newState.affectedFiles = state.affectedFiles; + newState.affectedFilesIndex = state.affectedFilesIndex; + newState.currentChangedFilePath = state.currentChangedFilePath; + newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures); + newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap); + newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles); + newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; + newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState); + newState.program = state.program; + newState.compilerOptions = state.compilerOptions; + newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit; + newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; + newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles); + newState.programEmitComplete = state.programEmitComplete; + return newState; + } /** * Verifies that source file is ok to be used in calls that arent handled by next */ @@ -88739,22 +89388,43 @@ var ts; } // With --out or --outFile all outputs go into single file // so operations are performed directly on program, return program - var compilerOptions = state.program.getCompilerOptions(); + var program = ts.Debug.assertDefined(state.program); + var compilerOptions = program.getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); - return state.program; + return program; } // Get next batch of affected files state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); if (state.exportedModulesMap) { state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); } - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); } } + /** + * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet + */ + function getNextAffectedFilePendingEmit(state) { + var affectedFilesPendingEmit = state.affectedFilesPendingEmit; + if (affectedFilesPendingEmit) { + var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap()); + for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) { + var affectedFile = ts.Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]); + if (affectedFile && !seenEmittedFiles.has(affectedFile.path)) { + // emit this file + state.affectedFilesPendingEmitIndex = i; + return affectedFile; + } + } + state.affectedFilesPendingEmit = undefined; + state.affectedFilesPendingEmitIndex = undefined; + } + return undefined; + } /** * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file */ @@ -88766,9 +89436,10 @@ var ts; // Clean lib file diagnostics if its all files excluding default files to emit if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { state.cleanedDiagnosticsOfLibFiles = true; - var options_2 = state.program.getCompilerOptions(); - if (ts.forEach(state.program.getSourceFiles(), function (f) { - return state.program.isSourceFileDefaultLibrary(f) && + var program_1 = ts.Debug.assertDefined(state.program); + var options_2 = program_1.getCompilerOptions(); + if (ts.forEach(program_1.getSourceFiles(), function (f) { + return program_1.isSourceFileDefaultLibrary(f) && !ts.skipTypeChecking(f, options_2) && removeSemanticDiagnosticsOf(state, f.path); })) { @@ -88829,11 +89500,20 @@ var ts; return true; } // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected - return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(filePath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); - }); + })) { + return true; + } + // Remove diagnostics of files that import this file (without going to exports of referencing files) + return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) { + return referencesInFile.has(filePath) && + !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file + removeSemanticDiagnosticsOf(state, referencingFilePath); + } // Dont add to seen since this is not yet done with the export removal + ); } /** * Removes semantic diagnostics for path and @@ -88851,20 +89531,26 @@ var ts; * This is called after completing operation on the next affected file. * The operations here are postponed to ensure that cancellation during the iteration is handled correctly */ - function doneWithAffectedFile(state, affected) { + function doneWithAffectedFile(state, affected, isPendingEmit) { if (affected === state.program) { state.changedFilesSet.clear(); + state.programEmitComplete = true; } else { state.seenAffectedFiles.set(affected.path, true); - state.affectedFilesIndex++; + if (isPendingEmit) { + state.affectedFilesPendingEmitIndex++; + } + else { + state.affectedFilesIndex++; + } } } /** * Returns the result with affected file */ - function toAffectedFileResult(state, result, affected) { - doneWithAffectedFile(state, affected); + function toAffectedFileResult(state, result, affected, isPendingEmit) { + doneWithAffectedFile(state, affected, isPendingEmit); return { result: result, affected: affected }; } /** @@ -88873,14 +89559,18 @@ var ts; */ function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { var path = sourceFile.path; - var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - return cachedDiagnostics; + if (state.semanticDiagnosticsPerFile) { + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } } // Diagnostics werent cached, get them from program, and cache the result - var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); - state.semanticDiagnosticsPerFile.set(path, diagnostics); + var diagnostics = ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); + if (state.semanticDiagnosticsPerFile) { + state.semanticDiagnosticsPerFile.set(path, diagnostics); + } return diagnostics; } var BuilderProgramKind; @@ -88905,7 +89595,7 @@ var ts; rootNames: newProgramOrRootNames, options: hostOrOptions, host: oldProgramOrHost, - oldProgram: oldProgram && oldProgram.getProgram(), + oldProgram: oldProgram && oldProgram.getProgramOrUndefined(), configFileParsingDiagnostics: configFileParsingDiagnostics, projectReferences: projectReferences }); @@ -88936,26 +89626,29 @@ var ts; /** * Computing hash to for signature verification */ - var computeHash = host.createHash || ts.identity; + var computeHash = host.createHash || ts.generateDjb2Hash; var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + var backupState; // To ensure that we arent storing any references to old program or new program without state newProgram = undefined; // TODO: GH#18217 oldProgram = undefined; oldState = undefined; - var result = { - getState: function () { return state; }, - getProgram: function () { return state.program; }, - getCompilerOptions: function () { return state.program.getCompilerOptions(); }, - getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, - getSourceFiles: function () { return state.program.getSourceFiles(); }, - getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, - getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, - getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, - getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, - getSemanticDiagnostics: getSemanticDiagnostics, - emit: emit, - getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, - getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + var result = createRedirectedBuilderProgram(state, configFileParsingDiagnostics); + result.getState = function () { return state; }; + result.backupState = function () { + ts.Debug.assert(backupState === undefined); + backupState = cloneBuilderProgramState(state); + }; + result.restoreState = function () { + state = ts.Debug.assertDefined(backupState); + backupState = undefined; + }; + result.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.assertDefined(state.program), sourceFile); }; + result.getSemanticDiagnostics = getSemanticDiagnostics; + result.emit = emit; + result.releaseProgram = function () { + releaseCache(state); + backupState = undefined; }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; @@ -88974,14 +89667,33 @@ var ts; */ function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { var affected = getNextAffectedFile(state, cancellationToken, computeHash); + var isPendingEmitFile = false; if (!affected) { - // Done - return undefined; + if (!state.compilerOptions.out && !state.compilerOptions.outFile) { + affected = getNextAffectedFilePendingEmit(state); + if (!affected) { + return undefined; + } + isPendingEmitFile = true; + } + else { + var program = ts.Debug.assertDefined(state.program); + // Check if program uses any prepend project references, if thats the case we cant track of the js files of those, so emit even though there are no changes + if (state.programEmitComplete || !ts.some(program.getProjectReferences(), function (ref) { return !!ref.prepend; })) { + state.programEmitComplete = true; + return undefined; + } + affected = program; + } + } + // Mark seen emitted files if there are pending files to be emitted + if (state.affectedFilesPendingEmit && state.program !== affected) { + (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.path, true); } return toAffectedFileResult(state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file - state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + ts.Debug.assertDefined(state.program).emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected, isPendingEmitFile); } /** * Emits the JavaScript and declaration files. @@ -89018,7 +89730,7 @@ var ts; }; } } - return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return ts.Debug.assertDefined(state.program).emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); } /** * Return the semantic diagnostics for the next affected file or undefined if iteration is complete @@ -89054,25 +89766,38 @@ var ts; */ function getSemanticDiagnostics(sourceFile, cancellationToken) { assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); - var compilerOptions = state.program.getCompilerOptions(); + var compilerOptions = ts.Debug.assertDefined(state.program).getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); // We dont need to cache the diagnostics just return them from program - return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + return ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); } if (sourceFile) { return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); } - if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { - // When semantic builder asks for diagnostics of the whole program, - // ensure that all the affected files are handled - var affected = void 0; - while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { - doneWithAffectedFile(state, affected); + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected; + var affectedFilesPendingEmit; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + if (affected !== state.program && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push(affected.path); + } + doneWithAffectedFile(state, affected); + } + // In case of emit builder, cache the files to be emitted + if (affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, affectedFilesPendingEmit); + // affectedFilesPendingEmitIndex === undefined + // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files + // so start from 0 as array would be affectedFilesPendingEmit + // else, continue to iterate from existing index, the current set is appended to existing files + if (state.affectedFilesPendingEmitIndex === undefined) { + state.affectedFilesPendingEmitIndex = 0; } } var diagnostics; - for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { var sourceFile_2 = _a[_i]; diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); } @@ -89080,6 +89805,32 @@ var ts; } } ts.createBuilderProgram = createBuilderProgram; + function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { + return { + getState: ts.notImplemented, + backupState: ts.noop, + restoreState: ts.noop, + getProgram: getProgram, + getProgramOrUndefined: function () { return state.program; }, + releaseProgram: function () { return state.program = undefined; }, + getCompilerOptions: function () { return state.compilerOptions; }, + getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); }, + getSourceFiles: function () { return getProgram().getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); }, + emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); }, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); } + }; + function getProgram() { + return ts.Debug.assertDefined(state.program); + } + } + ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram; })(ts || (ts = {})); (function (ts) { function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { @@ -89091,23 +89842,8 @@ var ts; } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; - return { - // Only return program, all other methods are not implemented - getProgram: function () { return program; }, - getState: ts.notImplemented, - getCompilerOptions: ts.notImplemented, - getSourceFile: ts.notImplemented, - getSourceFiles: ts.notImplemented, - getOptionsDiagnostics: ts.notImplemented, - getGlobalDiagnostics: ts.notImplemented, - getConfigFileParsingDiagnostics: ts.notImplemented, - getSyntacticDiagnostics: ts.notImplemented, - getSemanticDiagnostics: ts.notImplemented, - emit: ts.notImplemented, - getAllDependencies: ts.notImplemented, - getCurrentDirectory: ts.notImplemented - }; + var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics; + return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics); } ts.createAbstractBuilder = createAbstractBuilder; })(ts || (ts = {})); @@ -89911,7 +90647,7 @@ var ts; if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { return; // Don't want to a package to globally import from itself } - var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); if (target === undefined) return; var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); @@ -90286,37 +91022,103 @@ var ts; var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); return { onWatchStatusChange: onWatchStatusChange, - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + watchFile: ts.maybeBind(system, system.watchFile) || (function () { return noopFileWatcher; }), + watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return noopFileWatcher; }), + setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop, + clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop }; } ts.createWatchHost = createWatchHost; + var WatchType; + (function (WatchType) { + WatchType["ConfigFile"] = "Config file"; + WatchType["SourceFile"] = "Source file"; + WatchType["MissingFile"] = "Missing file"; + WatchType["WildcardDirectory"] = "Wild card directory"; + WatchType["FailedLookupLocations"] = "Failed Lookup Locations"; + WatchType["TypeRoots"] = "Type roots"; + })(WatchType = ts.WatchType || (ts.WatchType = {})); + function createWatchFactory(host, options) { + var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop; + var result = ts.getWatchFactory(watchLogLevel, writeLog); + result.writeLog = writeLog; + return result; + } + ts.createWatchFactory = createWatchFactory; + function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) { + if (directoryStructureHost === void 0) { directoryStructureHost = host; } + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); }); + return { + getSourceFile: function (fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, getCompilerOptions().charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + }, + getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); }, + fileExists: function (f) { return host.fileExists(f); }, + readFile: function (f) { return host.readFile(f); }, + trace: ts.maybeBind(host, host.trace), + directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: ts.maybeBind(host, host.realpath), + getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }), + createHash: ts.maybeBind(host, host.createHash), + readDirectory: ts.maybeBind(host, host.readDirectory), + }; + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + if (host.createDirectory) + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ - function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { - if (system === void 0) { system = ts.sys; } - if (!createProgram) { - createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; - } + function createProgramHost(system, createProgram) { + var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); }); var host = system; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) - var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; - var writeFileName = function (s) { return system.write(s + system.newLine); }; - var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getNewLine: function () { return system.newLine; }, - getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, fileExists: function (path) { return system.fileExists(path); }, @@ -90324,29 +91126,31 @@ var ts; directoryExists: function (path) { return system.directoryExists(path); }, getDirectories: function (path) { return system.getDirectories(path); }, readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, - realpath: system.realpath && (function (path) { return system.realpath(path); }), - getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: watchFile, - watchDirectory: watchDirectory, - setTimeout: setTimeout, - clearTimeout: clearTimeout, - trace: function (s) { return system.write(s); }, - onWatchStatusChange: onWatchStatusChange, + realpath: ts.maybeBind(system, system.realpath), + getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable), + trace: function (s) { return system.write(s + system.newLine); }, createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, - createHash: system.createHash && (function (s) { return system.createHash(s); }), - createProgram: createProgram, - afterProgramCreate: emitFilesAndReportErrorUsingBuilder + createHash: ts.maybeBind(system, system.createHash), + createProgram: createProgram }; - function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); - } - function emitFilesAndReportErrorUsingBuilder(builderProgram) { + } + ts.createProgramHost = createProgramHost; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var writeFileName = function (s) { return system.write(s + system.newLine); }; + var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram); + ts.copyProperties(result, createWatchHost(system, reportWatchStatus)); + result.afterProgramCreate = function (builderProgram) { var compilerOptions = builderProgram.getCompilerOptions(); var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); - } + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); + }; + return result; } /** * Report error and exit @@ -90402,8 +91206,6 @@ var ts; var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); var currentDirectory = host.getCurrentDirectory(); - var getCurrentDirectory = function () { return currentDirectory; }; - var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; @@ -90415,15 +91217,7 @@ var ts; host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } var directoryStructureHost = cachedDirectoryStructureHost || host; - var parseConfigFileHost = { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, - fileExists: function (path) { return host.fileExists(path); }, - readFile: readFile, - getCurrentDirectory: getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, - trace: host.trace ? function (s) { return host.trace(s); } : undefined - }; + var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost); // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); if (configFileName && host.configFileParsingResult) { @@ -90437,52 +91231,40 @@ var ts; parseConfigFile(); newLine = updateNewLine(); } - var trace = host.trace && (function (s) { host.trace(s + newLine); }); - var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : - compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; - var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 - var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; + var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); } - var compilerHost = { - // Members for CompilerHost - getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, - getSourceFileByPath: getVersionedSourceFileByPath, - getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), - getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, - writeFile: writeFile, - getCurrentDirectory: getCurrentDirectory, - useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, - getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return newLine; }, - fileExists: fileExists, - readFile: readFile, - trace: trace, - directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), - getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), - realpath: host.realpath && (function (s) { return host.realpath(s); }), - getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), - onReleaseOldSourceFile: onReleaseOldSourceFile, - createHash: host.createHash && (function (data) { return host.createHash(data); }), - // Members for ResolutionCacheHost - toPath: toPath, - getCompilationSettings: function () { return compilerOptions; }, - watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, - watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, - getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, - onInvalidatedResolution: scheduleProgramUpdate, - onChangedAutomaticTypeDirectiveNames: function () { - hasChangedAutomaticTypeDirectiveNames = true; - scheduleProgramUpdate(); - }, - maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, - getCurrentProgram: getCurrentProgram, - writeLog: writeLog, - readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost); + // Members for CompilerHost + var getNewSourceFile = compilerHost.getSourceFile; + compilerHost.getSourceFile = function (fileName) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return getVersionedSourceFileByPath.apply(void 0, [fileName, toPath(fileName)].concat(args)); }; + compilerHost.getSourceFileByPath = getVersionedSourceFileByPath; + compilerHost.getNewLine = function () { return newLine; }; + compilerHost.fileExists = fileExists; + compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + // Members for ResolutionCacheHost + compilerHost.toPath = toPath; + compilerHost.getCompilationSettings = function () { return compilerOptions; }; + compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations" /* FailedLookupLocations */); }; + compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots" /* TypeRoots */); }; + compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; + compilerHost.onInvalidatedResolution = scheduleProgramUpdate; + compilerHost.onChangedAutomaticTypeDirectiveNames = function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }; + compilerHost.maxNumberOfFilesToIterateForInvalidation = host.maxNumberOfFilesToIterateForInvalidation; + compilerHost.getCurrentProgram = getCurrentProgram; + compilerHost.writeLog = writeLog; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -90535,11 +91317,9 @@ var ts; } function createNewProgram(program, hasInvalidatedResolution) { // Compile the program - if (watchLogLevel !== ts.WatchLogLevel.None) { - writeLog("CreatingProgramWith::"); - writeLog(" roots: " + JSON.stringify(rootFileNames)); - writeLog(" options: " + JSON.stringify(compilerOptions)); - } + writeLog("CreatingProgramWith::"); + writeLog(" roots: " + JSON.stringify(rootFileNames)); + writeLog(" options: " + JSON.stringify(compilerOptions)); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -90602,7 +91382,7 @@ var ts; } // Create new source file if requested or the versions dont match if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { - var sourceFile = getNewSourceFile(); + var sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { if (shouldCreateNewSourceFile) { hostSourceFile.version++; @@ -90612,7 +91392,7 @@ var ts; hostSourceFile.sourceFile = sourceFile; sourceFile.version = hostSourceFile.version.toString(); if (!hostSourceFile.fileWatcher) { - hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); } } else { @@ -90626,7 +91406,7 @@ var ts; else { if (sourceFile) { sourceFile.version = initialVersion.toString(); - var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); } else { @@ -90636,21 +91416,6 @@ var ts; return sourceFile; } return hostSourceFile.sourceFile; - function getNewSourceFile() { - var text; - try { - ts.performance.mark("beforeIORead"); - text = host.readFile(fileName, compilerOptions.charset); - ts.performance.mark("afterIORead"); - ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; - } } function nextSourceFileVersion(path) { var hostSourceFile = sourceFilesCache.get(path); @@ -90777,7 +91542,7 @@ var ts; } } function watchMissingFilePath(missingFilePath) { - return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file"); + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file" /* MissingFile */); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -90821,28 +91586,7 @@ var ts; // Schedule Update the program scheduleProgramUpdate(); } - }, flags, "Wild card directories"); - } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - host.createDirectory(directoryPath); - } - } - function writeFile(fileName, text, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } + }, flags, "Wild card directory" /* WildcardDirectory */); } } ts.createWatchProgram = createWatchProgram; @@ -91011,9 +91755,8 @@ var ts; }; } ts.createBuilderStatusReporter = createBuilderStatusReporter; - function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { - if (system === void 0) { system = ts.sys; } - var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) { + var host = ts.createProgramHost(system, createProgram); host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; @@ -91021,21 +91764,18 @@ var ts; host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); return host; } - function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { if (system === void 0) { system = ts.sys; } - var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus); host.reportErrorSummary = reportErrorSummary; return host; } ts.createSolutionBuilderHost = createSolutionBuilderHost; - function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { - var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus); var watchHost = ts.createWatchHost(system, reportWatchStatus); - host.onWatchStatusChange = watchHost.onWatchStatusChange; - host.watchFile = watchHost.watchFile; - host.watchDirectory = watchHost.watchDirectory; - host.setTimeout = watchHost.setTimeout; - host.clearTimeout = watchHost.clearTimeout; + ts.copyProperties(host, watchHost); return host; } ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; @@ -91050,7 +91790,7 @@ var ts; var hostWithWatch = host; var currentDirectory = host.getCurrentDirectory(); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host); // State of the solution var options = defaultOptions; var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); @@ -91062,7 +91802,14 @@ var ts; var missingRoots = ts.createMap(); var globalDependencyGraph; var writeFileName = function (s) { return host.trace && host.trace(s); }; + var readFileWithCache = function (f) { return host.readFile(f); }; + var projectCompilerOptions = baseCompilerOptions; + var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; }); + var originalGetSourceFile = compilerHost.getSourceFile; + var computeHash = host.createHash || ts.generateDjb2Hash; + updateGetSourceFile(); // Watch state + var builderPrograms = createFileMap(toPath); var diagnostics = createFileMap(toPath); var projectPendingBuild = createFileMap(toPath); var projectErrorsReported = createFileMap(toPath); @@ -91070,6 +91817,7 @@ var ts; var nextProjectToBuild = 0; var timerToBuildInvalidatedProject; var reportFileChangeDetected = false; + var _a = ts.createWatchFactory(host, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; // Watches for the solution var allWatchedWildcardDirectories = createFileMap(toPath); var allWatchedInputFiles = createFileMap(toPath); @@ -91110,6 +91858,30 @@ var ts; ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + builderPrograms.clear(); + updateGetSourceFile(); + } + function updateGetSourceFile() { + if (options.watch) { + if (compilerHost.getSourceFile === originalGetSourceFile) { + compilerHost.getSourceFile = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); + if (result && options.watch) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + } + else { + if (compilerHost.getSourceFile !== originalGetSourceFile) { + compilerHost.getSourceFile = originalGetSourceFile; + } + } } function isParsedCommandLine(entry) { return !!entry.options; @@ -91159,36 +91931,34 @@ var ts; } function watchConfigFile(resolved) { if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { - allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + allWatchedConfigFiles.setValue(resolved, watchFile(hostWithWatch, resolved, function () { invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); - })); + }, ts.PollingInterval.High, "Config file" /* ConfigFile */, resolved)); } } function watchWildCardDirectories(resolved, parsed) { if (!options.watch) return; ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { - return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + return watchDirectory(hostWithWatch, dir, function (fileOrDirectory) { var fileOrDirectoryPath = toPath(fileOrDirectory); if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { - // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory); return; } if (isOutputFile(fileOrDirectory, parsed)) { - // writeLog(`${fileOrDirectory} is output file`); + writeLog(fileOrDirectory + " is output file"); return; } invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); - }, !!(flags & 1 /* Recursive */)); + }, flags, "Wild card directory" /* WildcardDirectory */, resolved); }); } function watchInputFiles(resolved, parsed) { if (!options.watch) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { - createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); - }); }, + createNewValue: function (path, input) { return watchFilePath(hostWithWatch, input, function () { return invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, path, "Source file" /* SourceFile */, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -91508,18 +92278,39 @@ var ts; reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); return; } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes) { + // Fake that files have been built by updating output file stamps + updateOutputTimestamps(proj); + return; + } var buildResult = buildSingleProject(resolved); - var dependencyGraph = getGlobalDependencyGraph(); - var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (buildResult & BuildResultFlags.AnyErrors) + return; + var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue; + var referencingProjects = referencingProjectsMap.getValue(resolved); if (!referencingProjects) return; // Always use build order to queue projects - for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { - var project = _a[_i]; + for (var index = buildQueue.indexOf(resolved) + 1; index < buildQueue.length; index++) { + var project = buildQueue[index]; var prepend = referencingProjects.getValue(project); - // If the project is referenced with prepend, always build downstream projectm, - // otherwise queue it only if declaration output changed - if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + if (prepend !== undefined) { + // If the project is referenced with prepend, always build downstream projects, + // If declaration output is changed, build the project + // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps + var status_1 = projectStatus.getValue(project); + if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { + if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) { + projectStatus.setValue(project, { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: status_1.oldestOutputFileName, + newerProjectName: resolved + }); + } + } + else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) { + status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes; + } addProjToQueue(project); } } @@ -91590,98 +92381,118 @@ var ts; // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } - var programOptions = { - projectReferences: configFile.projectReferences, - host: host, - rootNames: configFile.fileNames, - options: configFile.options, - configFileParsingDiagnostics: configFile.errors - }; - if (host.beforeCreateProgram) { - host.beforeCreateProgram(options); - } - var program = ts.createProgram(programOptions); + // TODO: handle resolve module name to cache result in project reference redirect + projectCompilerOptions = configFile.options; + var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences); + projectCompilerOptions = baseCompilerOptions; // Don't emit anything in the presence of syntactic errors or options diagnostics - var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } - // Don't emit .d.ts if there are decl file errors - if (ts.getEmitDeclarations(program.getCompilerOptions())) { - var declDiagnostics = program.getDeclarationDiagnostics(); - if (declDiagnostics.length) { - return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); - } - } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } + // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly + program.backupState(); var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - var emitDiagnostics; - var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; - ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { + var declDiagnostics; + var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; + var outputFiles = []; + ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }); + // Don't emit .d.ts if there are decl file errors + if (declDiagnostics) { + program.restoreState(); + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); + } + // Actual Emit + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emittedOutputs = createFileMap(toPath); + outputFiles.forEach(function (_a) { + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName)) { + if (!anyDtsChanged && isDeclarationFile(name)) { // Check for unchanged .d.ts files - if (host.fileExists(fileName) && host.readFile(fileName) === content) { - priorChangeTime = host.getModifiedTime(fileName); + if (host.fileExists(name) && readFileWithCache(name) === text) { + priorChangeTime = host.getModifiedTime(name); } else { resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + emittedOutputs.setValue(name, true); + ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(name, priorChangeTime); } }); - if (emitDiagnostics) { + var emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); } + // Update time stamps for rest of the outputs + newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(configFile, newestDeclarationFileContentChangedTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); var status = { type: UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime, + oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile) }; diagnostics.removeKey(proj); projectStatus.setValue(proj, status); - if (host.afterProgramEmitAndDiagnostics) { - host.afterProgramEmitAndDiagnostics(program); - } + afterProgramCreate(proj, program); return resultFlags; function buildErrors(diagnostics, errorFlags, errorType) { resultFlags |= errorFlags; reportAndStoreErrors(proj, diagnostics); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); - if (host.afterProgramEmitAndDiagnostics) { - host.afterProgramEmitAndDiagnostics(program); - } + afterProgramCreate(proj, program); return resultFlags; } } + function afterProgramCreate(proj, program) { + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + if (options.watch) { + program.releaseProgram(); + builderPrograms.setValue(proj, program); + } + } function updateOutputTimestamps(proj) { if (options.dry) { return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (options.verbose) { - reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); - } - var now = new Date(); - var outputs = getAllProjectOutputs(proj); - var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { - var file = outputs_2[_i]; - if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); - } - host.setModifiedTime(file, now); - } + var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } + function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { + var outputs = getAllProjectOutputs(proj); + if (!skipOutputs || outputs.length !== skipOutputs.getSize()) { + if (options.verbose) { + reportStatus(verboseMessage, proj.options.configFilePath); + } + var now = host.now ? host.now() : new Date(); + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; + if (skipOutputs && skipOutputs.hasKey(file)) { + continue; + } + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + } + host.setModifiedTime(file, now); + if (proj.options.listEmittedFiles) { + writeFileName("TSFILE: " + file); + } + } + } + return priorNewestUpdateTime; + } function getFilesToClean() { // Get the same graph for cleaning we'd use for building var graph = getGlobalDependencyGraph(); @@ -91726,11 +92537,24 @@ var ts; if (options.watch) { reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); } + // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api + // Override readFile for json files and output .d.ts to cache the text + var savedReadFileWithCache = readFileWithCache; + var savedGetSourceFile = compilerHost.getSourceFile; + var _a = ts.changeCompilerHostLikeToUseCache(host, toPath, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return savedGetSourceFile.call.apply(savedGetSourceFile, [compilerHost].concat(args)); + }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, newReadFileWithCache = _a.readFileWithCache; + readFileWithCache = newReadFileWithCache; + compilerHost.getSourceFile = getSourceFileWithCache; var graph = getGlobalDependencyGraph(); reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; + for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) { + var next = _b[_i]; var proj = parseConfigFile(next); if (proj === undefined) { reportParseConfigFileDiagnostic(next); @@ -91772,6 +92596,13 @@ var ts; anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } reportErrorSummary(); + host.readFile = originalReadFile; + host.fileExists = originalFileExists; + host.directoryExists = originalDirectoryExists; + host.createDirectory = originalCreateDirectory; + host.writeFile = originalWriteFile; + compilerHost.getSourceFile = savedGetSourceFile; + readFileWithCache = savedReadFileWithCache; return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } function reportParseConfigFileDiagnostic(proj) { @@ -91794,7 +92625,7 @@ var ts; } } function relName(path) { - return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode @@ -91827,6 +92658,19 @@ var ts; } } ts.getAllProjectOutputs = getAllProjectOutputs; + function getFirstProjectOutput(project) { + if (project.options.outFile || project.options.out) { + return ts.first(getOutFileOutputs(project)); + } + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + var outputs = getOutputFileNames(inputFile, project); + if (outputs.length) { + return ts.first(outputs); + } + } + return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output"); + } function formatUpToDateStatus(configFileName, status, relName, formatMessage) { switch (status.type) { case UpToDateStatusType.OutOfDateWithSelf: @@ -91879,17 +92723,17 @@ var ts; } ts.inspectValue = inspectValue; function getRecurser() { - var seen = new Set(); + var seen = []; var nameStack = []; return function (obj, name, cbOk, cbFail) { - if (seen.has(obj) || nameStack.length > 4) { - return cbFail(seen.has(obj), nameStack); + if (seen.indexOf(obj) !== -1 || nameStack.length > 4) { + return cbFail(seen.indexOf(obj) !== -1, nameStack); } - seen.add(obj); + seen.push(obj); nameStack.push(name); var res = cbOk(); nameStack.pop(); - seen.delete(obj); + seen.pop(); return res; }; } @@ -91947,8 +92791,8 @@ var ts; return key === "constructor" ? undefined : getValueInfo(key, value, recurser); }); } - var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); - var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + var ignoredProperties = ["arguments", "caller", "constructor", "eval", "super_"]; + var reservedFunctionProperties = Object.getOwnPropertyNames(ts.noop); function getEntriesOfObject(obj) { var seen = ts.createMap(); var entries = []; @@ -91957,8 +92801,8 @@ var ts; for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { var key = _a[_i]; if (!isJsPrivate(key) && - !ignoredProperties.has(key) && - (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + ignoredProperties.indexOf(key) === -1 && + (typeof obj !== "function" || reservedFunctionProperties.indexOf(key) === -1) && // Don't add property from a higher prototype if it already exists in a lower one ts.addToSeen(seen, key)) { var value = safeGetPropertyOfObject(chain, key); @@ -91986,7 +92830,7 @@ var ts; return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; } function isJsPrivate(name) { - return name.startsWith("_"); + return ts.startsWith(name, "_"); } ts.isJsPrivate = isJsPrivate; function tryRequire(fileNameToRequire) { @@ -92247,8 +93091,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_6.config; + var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_7.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -95680,7 +96524,7 @@ var ts; continue; var patterns = paths[path]; if (patterns) { - var _loop_10 = function (name, kind, extension) { + var _loop_11 = function (name, kind, extension) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind, extension)); @@ -95688,7 +96532,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_10(name, kind, extension); + _loop_11(name, kind, extension); } } } @@ -95723,7 +96567,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_11 = function (moduleName) { + var _loop_12 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); @@ -95731,7 +96575,7 @@ var ts; }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_11(moduleName); + _loop_12(moduleName); } } if (!foundGlobal) { @@ -96085,7 +96929,7 @@ var ts; getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { - if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { + if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); @@ -96285,7 +97129,8 @@ var ts; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + return origin && originIsExport(origin) && ((origin.isDefaultExport && symbol.escapedName === "default" /* Default */) || + (symbol.escapedName === "export=" /* ExportEquals */)) // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) @@ -96855,14 +97700,11 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // For JS, stay on the safe side. - if (isUncheckedFile) - return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. - return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); + if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) + return true; + // If some file is using ES6 modules, assume that it's OK to add more. + return ts.programContainsEs6Modules(program); } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { @@ -97661,7 +98503,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 121 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); + return kind === 121 /* AsyncKeyword */ || kind === 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -98949,9 +99791,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { - var result_7 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); - return result_7; + var result_8 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_8.push(nodeEntry(node)); }); + return result_8; } else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -98983,8 +99825,8 @@ var ts; case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; + var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case 1 /* Label */: { var node_3 = def.node; @@ -98992,8 +99834,8 @@ var ts; } case 2 /* Keyword */: { var node_4 = def.node; - var name_4 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; + var name_5 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; } case 3 /* This */: { var node_5 = def.node; @@ -99019,8 +99861,8 @@ var ts; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } - function toRenameLocation(entry, originalNode, checker) { - return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker)); + function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText) { + return __assign({}, entryToDocumentSpan(entry), (providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker))); } FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { @@ -99325,12 +100167,12 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol; + var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol; // Compute the meaning from the location and the symbol it references var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); - var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); if (exportSpecifier) { // When renaming at an export specifier, rename the export and not the thing being exported. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); @@ -99340,7 +100182,7 @@ var ts; searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -99373,9 +100215,9 @@ var ts; } } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, useLocalSymbolForExportSpecifier) { var parent = node.parent; - if (ts.isExportSpecifier(parent) && !isForRename) { + if (ts.isExportSpecifier(parent) && useLocalSymbolForExportSpecifier) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); } // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. @@ -99837,6 +100679,7 @@ var ts; getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { + ts.Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled"); var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); @@ -99865,14 +100708,14 @@ var ts; } } // For `export { foo as bar }`, rename `foo`, but not `bar`. - if (!state.options.isForRename || alwaysGetReferences) { + if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) { var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. - if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) { + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (imported) searchForImportedSymbol(imported, state); @@ -99904,7 +100747,7 @@ var ts; return; var symbol = importOrExport.symbol; if (importOrExport.kind === 0 /* Import */) { - if (!state.options.isForRename) { + if (!(isForRenameWithPrefixAndSuffixText(state.options))) { searchForImportedSymbol(symbol, state); } } @@ -100166,6 +101009,9 @@ var ts; }); return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } + function isParameterName(node) { + return node.kind === 72 /* Identifier */ && node.parent.kind === 151 /* Parameter */ && node.parent.name === node; + } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. @@ -100186,7 +101032,7 @@ var ts; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; case 279 /* SourceFile */: - if (ts.isExternalModule(searchSpaceNode)) { + if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) { return undefined; } // falls through @@ -100218,7 +101064,7 @@ var ts; // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; case 279 /* SourceFile */: - return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container); + return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); @@ -100242,13 +101088,13 @@ var ts; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, providePrefixAndSuffixText, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, !(isForRename && providePrefixAndSuffixText), function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, onlyIncludeBindingElementAtReferenceLocation, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { /* Because in short-hand property assignment, location has two meaning : property name and as value of the property @@ -100295,9 +101141,23 @@ var ts; return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. - // Don't do this when populating search set for a rename -- just rename the local. + // Don't do this when populating search set for a rename when prefix and suffix text will be provided -- just rename the local. if (!isForRenamePopulateSearchSymbolSet) { - var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + var bindingElementPropertySymbol = void 0; + if (onlyIncludeBindingElementAtReferenceLocation) { + bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + } + else { + bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); + } + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + ts.Debug.assert(isForRenamePopulateSearchSymbolSet); + // due to the above assert and the arguments at the uses of this function, + // (onlyIncludeBindingElementAtReferenceLocation <=> !providePrefixAndSuffixTextForRename) holds + var includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation; + if (includeOriginalSymbolOfBindingElement) { + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); } function fromRoot(sym, kind) { @@ -100315,10 +101175,17 @@ var ts; : undefined); }); } + function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { + var bindingElement = ts.getDeclarationOfKind(symbol, 186 /* BindingElement */); + if (bindingElement && ts.isObjectBindingElementWithoutPropertyName(bindingElement)) { + return ts.getPropertySymbolFromBindingElement(checker, bindingElement); + } + } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, + /*onlyIncludeBindingElementAtReferenceLocation*/ !state.options.isForRename || !!state.options.providePrefixAndSuffixTextForRename, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, @@ -100403,6 +101270,9 @@ var ts; }); return res.length === 0 ? undefined : res; } + function isForRenameWithPrefixAndSuffixText(options) { + return options.isForRename && options.providePrefixAndSuffixTextForRename; + } })(Core = FindAllReferences.Core || (FindAllReferences.Core = {})); })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -100515,7 +101385,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_12 = function (sourceFile) { + var _loop_13 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -100537,7 +101407,7 @@ var ts; var toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. // TODO:GH#18217 - ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew) : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) @@ -100547,7 +101417,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_12(sourceFile); + _loop_13(sourceFile); } } function combineNormal(pathA, pathB) { @@ -100567,23 +101437,32 @@ var ts; var resolved = host.resolveModuleNames ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); - return getSourceFileToImportFromResolved(resolved, oldToNew, host); + return getSourceFileToImportFromResolved(resolved, oldToNew); } } - function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + function getSourceFileToImportFromResolved(resolved, oldToNew) { // Search through all locations looking for a moved file, and only then test already existing files. // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. - return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); - function tryEach(cb) { - return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + if (!resolved) + return undefined; + // First try resolved module + if (resolved.resolvedModule) { + var result_9 = tryChange(resolved.resolvedModule.resolvedFileName); + if (result_9) + return result_9; } - function tryGetNewFile(oldFileName) { - var newFileName = oldToNew(oldFileName); - return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + // Then failed lookups except package.json since we dont want to touch them (only included ts/js files) + var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson); + if (result) + return result; + // If nothing changed, then result is resolved module file thats not updated + return resolved.resolvedModule && { newFileName: resolved.resolvedModule.resolvedFileName, updated: false }; + function tryChangeWithIgnoringPackageJson(oldFileName) { + return !ts.endsWith(oldFileName, "/package.json") ? tryChange(oldFileName) : undefined; } - function tryGetOldFile(oldFileName) { + function tryChange(oldFileName) { var newFileName = oldToNew(oldFileName); - return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 + return newFileName && { newFileName: newFileName, updated: true }; } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { @@ -100680,10 +101559,10 @@ var ts; // bar(({pr/*goto*/op1})=>{}); if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && (node === (parent.propertyName || parent.name))) { - var name_5 = ts.getNameFromPropertyName(node); + var name_6 = ts.getNameFromPropertyName(node); var type = typeChecker.getTypeAtLocation(parent.parent); - return name_5 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { - var prop = t.getProperty(name_5); + return name_6 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { + var prop = t.getProperty(name_6); return prop && getDefinitionFromSymbol(typeChecker, prop, node); }); } @@ -101328,7 +102207,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_13 = function (sourceFile) { + var _loop_14 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -101340,7 +102219,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { var sourceFile = sourceFiles_6[_i]; - _loop_13(sourceFile); + _loop_14(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -102032,7 +102911,7 @@ var ts; else if (ts.isCallExpression(parent)) { var name = getCalledExpressionName(parent.expression); if (name !== undefined) { - var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteralLike(a) ? a.getText(curSourceFile) : undefined; }).join(", "); return name + "(" + args + ") callback"; } } @@ -102085,10 +102964,12 @@ var ts; organizeImportsWorker(topLevelExportDecls, coalesceExports); for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; - var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217 - var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); + if (!ambientModule.body) { + continue; + } + var ambientModuleImportDecls = ambientModule.body.statements.filter(ts.isImportDeclaration); organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); - var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); organizeImportsWorker(ambientModuleExportDecls, coalesceExports); } return changeTracker.getChanges(); @@ -102128,13 +103009,9 @@ var ts; } } OrganizeImports.organizeImports = organizeImports; - function getModuleBlock(moduleDecl) { - var body = moduleDecl.body; - return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; - } function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); - var jsxNamespace = typeChecker.getJsxNamespace(); + var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { @@ -102394,6 +103271,9 @@ var ts; if (ts.isDeclaration(n)) { addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); } + if (isFunctionExpressionAssignedToVariable(n)) { + addOutliningForLeadingCommentsForNode(n.parent.parent.parent, sourceFile, cancellationToken, out); + } var span = getOutliningSpanForNode(n, sourceFile); if (span) out.push(span); @@ -102411,6 +103291,13 @@ var ts; } depthRemaining++; } + function isFunctionExpressionAssignedToVariable(n) { + if (!ts.isFunctionExpression(n) && !ts.isArrowFunction(n)) { + return false; + } + var ancestor = ts.findAncestor(n, ts.isVariableStatement); + return !!ancestor && ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration(ancestor) === n; + } } function addRegionOutliningSpans(sourceFile, out) { var regions = []; @@ -102526,6 +103413,7 @@ var ts; case 245 /* ModuleBlock */: return spanForNode(n.parent); case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: case 241 /* InterfaceDeclaration */: case 243 /* EnumDeclaration */: case 246 /* CaseBlock */: @@ -102554,10 +103442,10 @@ var ts; } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 18 /* OpenBraceToken */; } - // If the block has no leading keywords and is inside an array literal, + // If the block has no leading keywords and is inside an array literal or call expression, // we only want to collapse the span of the block. // Otherwise, the collapsed section will include the end of the previous line. - return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent), open); + return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent) && !ts.isCallExpression(node.parent), open); } function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { if (autoCollapse === void 0) { autoCollapse = false; } @@ -102859,15 +103747,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_14 = function (start) { + var _loop_15 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_14(start); - if (typeof state_3 === "object") - return state_3.value; + var state_4 = _loop_15(start); + if (typeof state_4 === "object") + return state_4.value; } return -1; } @@ -103381,15 +104269,15 @@ var ts; (function (ts) { var Rename; (function (Rename) { - function getRenameInfo(program, sourceFile, position) { + function getRenameInfo(program, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position); var renameInfo = node && nodeIsEligibleForRename(node) - ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }) + ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options) : undefined; return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) { + function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) return; @@ -103406,7 +104294,7 @@ var ts; return undefined; } if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { - return getRenameInfoForModule(node, sourceFile, symbol); + return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 149 /* ComputedPropertyName */) @@ -103423,7 +104311,7 @@ var ts; var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); if (!moduleSourceFile) return undefined; - var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var withoutIndex = ts.endsWith(node.text, "/index") || ts.endsWith(node.text, "/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; @@ -103878,7 +104766,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_15 = function (n) { + var _loop_16 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -103888,9 +104776,9 @@ var ts; } }; for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { - var state_4 = _loop_15(n); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_16(n); + if (typeof state_5 === "object") + return state_5.value; } return undefined; } @@ -104003,86 +104891,47 @@ var ts; var ts; (function (ts) { var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; - function getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, getProgram) { - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var sourcemappedFileCache; + function getSourceMapper(host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var currentDirectory = host.getCurrentDirectory(); + var sourceFileLike = ts.createMap(); + var documentPositionMappers = ts.createMap(); return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; function toPath(fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } - function scanForSourcemapURL(fileName) { - var mappedFile = sourcemappedFileCache.get(toPath(fileName)); - if (!mappedFile) { - return; + function getDocumentPositionMapper(generatedFileName, sourceFileName) { + var path = toPath(generatedFileName); + var value = documentPositionMappers.get(path); + if (value) + return value; + var mapper; + if (host.getDocumentPositionMapper) { + mapper = host.getDocumentPositionMapper(generatedFileName, sourceFileName); } - return ts.tryGetSourceMappingURL(mappedFile.text, ts.getLineStarts(mappedFile)); - } - function convertDocumentToSourceMapper(file, contents, mapFileName) { - var map = ts.tryParseRawSourceMap(contents); - if (!map || !map.sources || !map.file || !map.mappings) { - // obviously invalid map - return file.sourceMapper = ts.identitySourceMapConsumer; + else if (host.readFile) { + var file = getSourceFileLike(generatedFileName); + mapper = file && ts.getDocumentPositionMapper({ getSourceFileLike: getSourceFileLike, getCanonicalFileName: getCanonicalFileName, log: function (s) { return host.log(s); } }, generatedFileName, ts.getLineInfo(file.text, ts.getLineStarts(file)), function (f) { return !host.fileExists || host.fileExists(f) ? host.readFile(f) : undefined; }); } - var program = getProgram(); - return file.sourceMapper = ts.createDocumentPositionMapper({ - getSourceFileLike: function (s) { - // Lookup file in program, if provided - var file = program && program.getSourceFileByPath(s); - // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file - if (file === undefined || file.resolvedPath !== s) { - // Otherwise check the cache (which may hit disk) - return sourcemappedFileCache.get(s); - } - return file; - }, - getCanonicalFileName: getCanonicalFileName, - log: log, - }, map, mapFileName); - } - function getSourceMapper(fileName, file) { - if (!host.readFile || !host.fileExists) { - return file.sourceMapper = ts.identitySourceMapConsumer; - } - if (file.sourceMapper) { - return file.sourceMapper; - } - var mapFileName = scanForSourcemapURL(fileName); - if (mapFileName) { - var match = base64UrlRegExp.exec(mapFileName); - if (match) { - if (match[1]) { - var base64Object = match[1]; - return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); - } - // Not a data URL we can parse, skip it - mapFileName = undefined; - } - } - var possibleMapLocations = []; - if (mapFileName) { - possibleMapLocations.push(mapFileName); - } - possibleMapLocations.push(fileName + ".map"); - for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { - var location = possibleMapLocations_1[_i]; - var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); - if (host.fileExists(mapPath)) { - return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 - } - } - return file.sourceMapper = ts.identitySourceMapConsumer; + documentPositionMappers.set(path, mapper || ts.identitySourceMapConsumer); + return mapper || ts.identitySourceMapConsumer; } function tryGetSourcePosition(info) { if (!ts.isDeclarationFileName(info.fileName)) return undefined; - var file = getFile(info.fileName); + var file = getSourceFile(info.fileName); if (!file) return undefined; - var newLoc = getSourceMapper(info.fileName, file).getSourcePosition(info); - return newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; + var newLoc = getDocumentPositionMapper(info.fileName).getSourcePosition(info); + return !newLoc || newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; } function tryGetGeneratedPosition(info) { - var program = getProgram(); + if (ts.isDeclarationFileName(info.fileName)) + return undefined; + var sourceFile = getSourceFile(info.fileName); + if (!sourceFile) + return undefined; + var program = host.getProgram(); var options = program.getCompilerOptions(); var outPath = options.outFile || options.out; var declarationPath = outPath ? @@ -104090,49 +104939,96 @@ var ts; ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); if (declarationPath === undefined) return undefined; - var declarationFile = getFile(declarationPath); - if (!declarationFile) - return undefined; - var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + var newLoc = getDocumentPositionMapper(declarationPath, info.fileName).getGeneratedPosition(info); return newLoc === info ? undefined : newLoc; } - function getFile(fileName) { + function getSourceFile(fileName) { + var program = host.getProgram(); + if (!program) + return undefined; var path = toPath(fileName); - var file = getProgram().getSourceFileByPath(path); - if (file && file.resolvedPath === path) { - return file; + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + var file = program.getSourceFileByPath(path); + return file && file.resolvedPath === path ? file : undefined; + } + function getOrCreateSourceFileLike(fileName) { + var path = toPath(fileName); + var fileFromCache = sourceFileLike.get(path); + if (fileFromCache !== undefined) + return fileFromCache ? fileFromCache : undefined; + if (!host.readFile || host.fileExists && !host.fileExists(path)) { + sourceFileLike.set(path, false); + return undefined; } - return sourcemappedFileCache.get(path); + // And failing that, check the disk + var text = host.readFile(path); + var file = text ? createSourceFileLike(text) : false; + sourceFileLike.set(path, file); + return file ? file : undefined; + } + // This can be called from source mapper in either source program or program that includes generated file + function getSourceFileLike(fileName) { + return !host.getSourceFileLike ? + getSourceFile(fileName) || getOrCreateSourceFileLike(fileName) : + host.getSourceFileLike(fileName); } function toLineColumnOffset(fileName, position) { - var file = getFile(fileName); // TODO: GH#18217 + var file = getSourceFileLike(fileName); // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } function clearCache() { - sourcemappedFileCache = createSourceFileLikeCache(host); + sourceFileLike.clear(); + documentPositionMappers.clear(); } } ts.getSourceMapper = getSourceMapper; - function createSourceFileLikeCache(host) { - var cached = ts.createMap(); - return { - get: function (path) { - if (cached.has(path)) { - return cached.get(path); + function getDocumentPositionMapper(host, generatedFileName, generatedFileLineInfo, readMapFile) { + var mapFileName = ts.tryGetSourceMappingURL(generatedFileLineInfo); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(host, ts.base64decode(ts.sys, base64Object), generatedFileName); } - if (!host.fileExists || !host.readFile || !host.fileExists(path)) - return; - // And failing that, check the disk - var text = host.readFile(path); // TODO: GH#18217 - var file = { - text: text, - lineMap: undefined, - getLineAndCharacterOfPosition: function (pos) { - return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); - } - }; - cached.set(path, file); - return file; + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(generatedFileName + ".map"); + var originalMapFileName = mapFileName && ts.getNormalizedAbsolutePath(mapFileName, ts.getDirectoryPath(generatedFileName)); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapFileName_1 = ts.getNormalizedAbsolutePath(location, ts.getDirectoryPath(generatedFileName)); + var mapFileContents = readMapFile(mapFileName_1, originalMapFileName); + if (ts.isString(mapFileContents)) { + return convertDocumentToSourceMapper(host, mapFileContents, mapFileName_1); + } + if (mapFileContents !== undefined) { + return mapFileContents || undefined; + } + } + return undefined; + } + ts.getDocumentPositionMapper = getDocumentPositionMapper; + function convertDocumentToSourceMapper(host, contents, mapFileName) { + var map = ts.tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { + // obviously invalid map + return undefined; + } + return ts.createDocumentPositionMapper(host, map, mapFileName); + } + function createSourceFileLike(text, lineMap) { + return { + text: text, + lineMap: lineMap, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); } }; } @@ -104140,6 +105036,7 @@ var ts; /* @internal */ var ts; (function (ts) { + var visitedNestedConvertibleFunctions = ts.createMap(); function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; @@ -104150,6 +105047,7 @@ var ts; diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } var isJsFile = ts.isSourceFileJS(sourceFile); + visitedNestedConvertibleFunctions.clear(); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -104247,13 +105145,17 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - if (!ts.isAsyncFunction(node) && + // need to check function before checking map so that deeper levels of nested callbacks are checked + if (isConvertibleFunction(node, checker) && !visitedNestedConvertibleFunctions.has(getKeyFromNode(node))) { + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + } + } + function isConvertibleFunction(node, checker) { + return !ts.isAsyncFunction(node) && node.body && ts.isBlock(node.body) && hasReturnStatementWithPromiseHandler(node.body) && - returnsPromise(node, checker)) { - diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); - } + returnsPromise(node, checker); } function returnsPromise(node, checker) { var functionType = checker.getTypeAtLocation(node); @@ -104294,16 +105196,21 @@ var ts; // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts function isFixablePromiseArgument(arg) { switch (arg.kind) { - case 96 /* NullKeyword */: - case 72 /* Identifier */: // identifier includes undefined case 239 /* FunctionDeclaration */: case 196 /* FunctionExpression */: case 197 /* ArrowFunction */: + visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); + /* falls through */ + case 96 /* NullKeyword */: + case 72 /* Identifier */: // identifier includes undefined return true; default: return false; } } + function getKeyFromNode(exp) { + return exp.pos.toString() + ":" + exp.end.toString(); + } })(ts || (ts = {})); /* @internal */ var ts; @@ -105026,7 +105933,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_16 = function (opt) { + var _loop_17 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -105045,7 +105952,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_16(opt); + _loop_17(opt); } return options; } @@ -106958,10 +107865,7 @@ var ts; * Trimming will be done for lines after the previous range */ function trimTrailingWhitespacesForRemainingRange() { - if (!previousRange) { - return; - } - var startPosition = previousRange.end; + var startPosition = previousRange ? previousRange.end : originalRange.pos; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); @@ -108220,7 +109124,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_17 = function (sourceFile, node) { + var _loop_18 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -108233,7 +109137,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_17(sourceFile, node); + _loop_18(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -108290,14 +109194,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_18 = function (i) { + var _loop_19 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_18(i); + _loop_19(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -108901,6 +109805,40 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addNameToNamelessParameter"; + var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(token)) { + return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.formatSyntaxKind(token.kind)); + } + var param = token.parent; + if (!ts.isParameter(param)) { + return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.formatSyntaxKind(token.kind)); + } + var i = param.parent.parameters.indexOf(param); + ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); + ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); + var replacement = ts.createParameter( + /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer); + changeTracker.replaceNode(sourceFile, token, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109228,20 +110166,8 @@ var ts; annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } - function isApplicableFunctionForInference(declaration) { - switch (declaration.kind) { - case 239 /* FunctionDeclaration */: - case 156 /* MethodDeclaration */: - case 157 /* Constructor */: - return true; - case 196 /* FunctionExpression */: - var parent = declaration.parent; - return ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) || !!declaration.name; - } - return false; - } function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { - if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + if (!ts.isIdentifier(parameterDeclaration.name)) { return; } var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || @@ -109254,12 +110180,17 @@ var ts; annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } else { + var needParens = ts.isArrowFunction(containingFunction) && !ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(containingFunction.parameters), ts.createToken(20 /* OpenParenToken */)); for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; if (declaration && !declaration.type && !declaration.initializer) { annotate(changes, sourceFile, declaration, type, program, host); } } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(containingFunction.parameters), ts.createToken(21 /* CloseParenToken */)); } } function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { @@ -109380,6 +110311,7 @@ var ts; case 157 /* Constructor */: searchToken = ts.findChildOfKind(containingFunction, 124 /* ConstructorKeyword */, sourceFile); break; + case 197 /* ArrowFunction */: case 196 /* FunctionExpression */: var parent = containingFunction.parent; searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? @@ -110057,7 +110989,7 @@ var ts; var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_19 = function (statement) { + var _loop_20 = function (statement) { ts.forEachChild(statement, function visit(node) { if (ts.isCallExpression(node)) { startTransformation(node, statement); @@ -110069,7 +111001,7 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_19(statement); + _loop_20(statement); } } function getReturnStatementsWithPromiseHandlers(body) { @@ -110977,11 +111909,10 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var program = context.program, sourceFile = context.sourceFile, span = context.span; + var sourceFile = context.sourceFile, span = context.span; var classDeclaration = getClass(sourceFile, span.start); - var checker = program.getTypeChecker(); return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); }); }, @@ -110993,7 +111924,7 @@ var ts; if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { var implementedTypeNode = _a[_i]; - addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); + addMissingDeclarations(context, implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); } } }); @@ -111005,7 +111936,8 @@ var ts; function symbolPointsToNonPrivateMember(symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); } - function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + function addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + var checker = context.program.getTypeChecker(); var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. @@ -111019,11 +111951,11 @@ var ts; if (!classType.getStringIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); } - codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, context, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); if (indexInfoOfKind) { - changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)); + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration, /*flags*/ undefined, codefix.getNoopSymbolTrackerWithResolver(context))); } } } @@ -111349,7 +112281,7 @@ var ts; var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) - ? checker.getJsxNamespace() + ? checker.getJsxNamespace(sourceFile) : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */); @@ -111721,7 +112653,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_20 = function (info) { + var _loop_21 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -111748,7 +112680,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_20(info); + _loop_21(info); } }); })); @@ -111897,7 +112829,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { - var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, typeDecl); var containingMethodDeclaration = ts.getAncestor(callExpression, 156 /* MethodDeclaration */); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); @@ -111923,6 +112855,40 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingNewOperator"; + var errorCodes = [ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingNewOperator(t, sourceFile, span); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_new_operator_to_call, fixId, ts.Diagnostics.Add_missing_new_operator_to_all_calls)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return addMissingNewOperator(changes, context.sourceFile, diag); + }); }, + }); + function addMissingNewOperator(changes, sourceFile, span) { + var call = ts.cast(findAncestorMatchingSpan(sourceFile, span), ts.isCallExpression); + var newExpression = ts.createNew(call.expression, call.typeArguments, call.arguments); + changes.replaceNode(sourceFile, call, newExpression); + } + function findAncestorMatchingSpan(sourceFile, span) { + var token = ts.getTokenAtPosition(sourceFile, span.start); + var end = ts.textSpanEnd(span); + while (token.end < end) { + token = token.parent; + } + return token; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -112000,10 +112966,10 @@ var ts; var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); if (!tsconfigObjectLiteral) return undefined; - var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + var compilerOptionsProperty = codefix.findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); if (!compilerOptionsProperty) { var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); - changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, codefix.createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); return defaultTypesDirectoryName; } var compilerOptions = compilerOptionsProperty.initializer; @@ -112015,10 +112981,10 @@ var ts; } var defaultBaseUrl = "."; function makeDefaultBaseUrl() { - return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + return codefix.createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); } function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { - var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + var baseUrlProp = codefix.findJsonProperty(compilerOptions, "baseUrl"); if (baseUrlProp) { return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; } @@ -112029,13 +112995,13 @@ var ts; } var defaultTypesDirectoryName = "types"; function makeDefaultPathMapping() { - return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + return codefix.createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); } function makeDefaultPaths() { - return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + return codefix.createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); } function getOrAddPathMapping(changes, tsconfig, compilerOptions) { - var paths = findProperty(compilerOptions, "paths"); + var paths = codefix.findJsonProperty(compilerOptions, "paths"); if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); return defaultTypesDirectoryName; @@ -112051,12 +113017,6 @@ var ts; changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); return defaultTypesDirectoryName; } - function createJsonPropertyAssignment(name, initializer) { - return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); - } - function findProperty(obj, name) { - return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); - } function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } @@ -112085,9 +113045,9 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var program = context.program, sourceFile = context.sourceFile, span = context.span; + var sourceFile = context.sourceFile, span = context.span; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { - return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, context, t, context.preferences); }); return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; }, @@ -112097,7 +113057,7 @@ var ts; return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var classDeclaration = getClass(diag.file, diag.start); if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { - addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); + addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences); } }); }, @@ -112108,13 +113068,14 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, pos); return ts.cast(token.parent, ts.isClassLike); } - function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { + function addMissingMembers(classDeclaration, sourceFile, context, changeTracker, preferences) { var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration); + var checker = context.program.getTypeChecker(); var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); - codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, context, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files @@ -112856,24 +113817,43 @@ var ts; * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. * @returns Empty string iff there are no member insertions. */ - function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, context, preferences, out) { var classMembers = classDeclaration.symbol.members; for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { var symbol = possiblyMissingSymbols_1[_i]; if (!classMembers.has(symbol.escapedName)) { - addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); + addNewNodeForMemberSymbol(symbol, classDeclaration, context, preferences, out); } } } codefix.createMissingMemberNodes = createMissingMemberNodes; + function getModuleSpecifierResolverHost(context) { + return { + directoryExists: context.host.directoryExists ? function (d) { return context.host.directoryExists(d); } : undefined, + fileExists: context.host.fileExists ? function (f) { return context.host.fileExists(f); } : undefined, + getCurrentDirectory: context.host.getCurrentDirectory ? function () { return context.host.getCurrentDirectory(); } : undefined, + readFile: context.host.readFile ? function (f) { return context.host.readFile(f); } : undefined, + useCaseSensitiveFileNames: context.host.useCaseSensitiveFileNames ? function () { return context.host.useCaseSensitiveFileNames(); } : undefined, + getSourceFiles: function () { return context.program.getSourceFiles(); }, + getCommonSourceDirectory: function () { return context.program.getCommonSourceDirectory(); }, + }; + } + function getNoopSymbolTrackerWithResolver(context) { + return { + trackSymbol: ts.noop, + moduleResolverHost: getModuleSpecifierResolverHost(context), + }; + } + codefix.getNoopSymbolTrackerWithResolver = getNoopSymbolTrackerWithResolver; /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, context, preferences, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; } + var checker = context.program.getTypeChecker(); var declaration = declarations[0]; var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); @@ -112885,7 +113865,7 @@ var ts; case 159 /* SetAccessor */: case 153 /* PropertySignature */: case 154 /* PropertyDeclaration */: - var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); + var typeNode = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); out(ts.createProperty( /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); @@ -112925,13 +113905,14 @@ var ts; break; } function outputMethod(signature, modifiers, name, body) { - var method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + var method = signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body); if (method) out(method); } } - function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + function signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body) { + var program = context.program; + var signatureDeclaration = program.getTypeChecker().signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 1 /* NoTruncation */ | 256 /* SuppressAnyReturnType */, getNoopSymbolTrackerWithResolver(context)); if (!signatureDeclaration) { return undefined; } @@ -112942,19 +113923,21 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, contextNode) { + var body = !ts.isInterfaceDeclaration(contextNode); var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); + var tracker = getNoopSymbolTrackerWithResolver(context); var types = ts.map(args, function (arg) { // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, /*flags*/ undefined, tracker); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); var contextualType = checker.getContextualType(call); - var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(120 /* AnyKeyword */); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker) || ts.createKeywordTypeNode(120 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, @@ -113035,6 +114018,38 @@ var ts; } return undefined; } + function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); + if (compilerOptionsProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral([ + createJsonPropertyAssignment(optionName, optionValue), + ]))); + return; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) { + return; + } + var optionProperty = findJsonProperty(compilerOptions, optionName); + if (optionProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); + } + else { + changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + } + } + codefix.setJsonCompilerOptionValue = setJsonCompilerOptionValue; + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + codefix.createJsonPropertyAssignment = createJsonPropertyAssignment; + function findJsonProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + codefix.findJsonProperty = findJsonProperty; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -113396,9 +114411,9 @@ var ts; forEachOwnNodeOfFunction(fnAst, function (node) { if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) { - var name_6 = node.left.name.text; - if (!ts.isJsPrivate(name_6)) { - ts.getOrUpdate(members, name_6, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_6, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); + var name_7 = node.left.name.text; + if (!ts.isJsPrivate(name_7)) { + ts.getOrUpdate(members, name_7, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_7, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); } } }); @@ -113913,7 +114928,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_21 = function (element) { + var _loop_22 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -113932,7 +114947,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_21(element); + _loop_22(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -114327,32 +115342,30 @@ var ts; case 100 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 233 /* LabeledStatement */: - { - var label = node.label; - (seenLabels || (seenLabels = [])).push(label.escapedText); - ts.forEachChild(node, visit); - seenLabels.pop(); - break; - } + case 233 /* LabeledStatement */: { + var label = node.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + ts.forEachChild(node, visit); + seenLabels.pop(); + break; + } case 229 /* BreakStatement */: - case 228 /* ContinueStatement */: - { - var label = node.label; - if (label) { - if (!ts.contains(seenLabels, label.escapedText)) { - // attempts to jump to label that is not in range to be extracted - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); - } + case 228 /* ContinueStatement */: { + var label = node.label; + if (label) { + if (!ts.contains(seenLabels, label.escapedText)) { + // attempts to jump to label that is not in range to be extracted + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); } - else { - if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { - // attempt to break or continue in a forbidden context - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); - } - } - break; } + else { + if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + // attempt to break or continue in a forbidden context + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } case 201 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; @@ -115164,7 +116177,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_22 = function (i) { + var _loop_23 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -115204,7 +116217,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_22(i); + _loop_23(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -115755,10 +116768,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_23 = function (sourceFile) { + var _loop_24 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_24 = function (statement) { + var _loop_25 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -115780,12 +116793,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_24(statement); + _loop_25(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_23(sourceFile); + _loop_24(sourceFile); } } function getNamespaceLikeImport(node) { @@ -116835,8 +117848,8 @@ var ts; SourceFileObject.prototype.getLineStarts = function () { return ts.getLineStarts(this); }; - SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) { - return ts.getPositionOfLineAndCharacter(this, line, character); + SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character, allowEdits) { + return ts.computePositionOfLineAndCharacter(ts.getLineStarts(this), line, character, this.text, allowEdits); }; SourceFileObject.prototype.getLineEndOfPosition = function (pos) { var line = this.getLineAndCharacterOfPosition(pos).line; @@ -117286,7 +118299,16 @@ var ts; } var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var sourceMapper = ts.getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, function () { return program; }); + var sourceMapper = ts.getSourceMapper({ + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCurrentDirectory: function () { return currentDirectory; }, + getProgram: getProgram, + fileExists: host.fileExists && (function (f) { return host.fileExists(f); }), + readFile: host.readFile && (function (f, encoding) { return host.readFile(f, encoding); }), + getDocumentPositionMapper: host.getDocumentPositionMapper && (function (generatedFileName, sourceFileName) { return host.getDocumentPositionMapper(generatedFileName, sourceFileName); }), + getSourceFileLike: host.getSourceFileLike && (function (f) { return host.getSourceFileLike(f); }), + log: log + }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -117339,15 +118361,7 @@ var ts; writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, fileExists: fileExists, - readFile: function (fileName) { - // stub missing host functionality - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - if (entry) { - return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); - } - return host.readFile && host.readFile(fileName); - }, + readFile: readFile, realpath: host.realpath && (function (path) { return host.realpath(path); }), directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); @@ -117401,6 +118415,15 @@ var ts; !ts.isString(entry) : (!!host.fileExists && host.fileExists(fileName)); } + function readFile(fileName) { + // stub missing host functionality + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache && hostCache.getEntryByPath(path); + if (entry) { + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); + } + return host.readFile && host.readFile(fileName); + } // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { @@ -117612,7 +118635,7 @@ var ts; var sourceFile = getValidSourceFile(fileName); return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } - function findRenameLocations(fileName, position, findInStrings, findInComments) { + function findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, position); @@ -117623,7 +118646,7 @@ var ts; }); } else { - return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, providePrefixAndSuffixTextForRename: providePrefixAndSuffixTextForRename, isForRename: true }, function (entry, originalNode, checker) { return ts.FindAllReferences.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false); }); } } function getReferencesAtPosition(fileName, position) { @@ -118047,9 +119070,9 @@ var ts; return ts.stringContains(path, "/node_modules/"); } } - function getRenameInfo(fileName, position) { + function getRenameInfo(fileName, position, options) { synchronizeHostData(); - return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options); } function getRefactorContext(file, positionOrRange, preferences, formatOptions) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; @@ -119307,13 +120330,13 @@ var ts; var _this = this; return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); }; - LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position, options); }); }; - LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { + LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { var _this = this; - return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ", " + providePrefixAndSuffixTextForRename + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename); }); }; /// GET BRACE MATCHING LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index cad17f4992f..e3f3ce42b19 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -1778,7 +1778,7 @@ declare namespace ts { type ResolvedConfigFileName = string & { _isResolvedConfigFileName: never; }; - type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles?: ReadonlyArray) => void; + type WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: ReadonlyArray) => void; class OperationCanceledException { } interface CancellationToken { @@ -2689,7 +2689,6 @@ declare namespace ts { getDefaultLibLocation?(): string; writeFile: WriteFileCallback; getCurrentDirectory(): string; - getDirectories(path: string): string[]; getCanonicalFileName(fileName: string): string; useCaseSensitiveFileNames(): boolean; getNewLine(): string; @@ -3013,6 +3012,7 @@ declare namespace ts { /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; readonly allowTextChangesInNewFiles?: boolean; + readonly providePrefixAndSuffixTextForRename?: boolean; } /** Represents a bigint literal value without requiring bigint support */ interface PseudoBigInt { @@ -4278,6 +4278,10 @@ declare namespace ts { * Get the syntax diagnostics, for all source files if source file is not supplied */ getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the declaration diagnostics, for all source files if source file is not supplied + */ + getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; /** * Get all the dependencies of the file */ @@ -4364,13 +4368,11 @@ declare namespace ts { /** If provided, will be used to reset existing delayed compilation */ clearTimeout?(timeoutId: any): void; } - interface WatchCompilerHost extends WatchHost { + interface ProgramHost { /** * Used to create the program when need for program creation or recreation detected */ createProgram: CreateProgram; - /** If provided, callback to invoke after every new program creation */ - afterProgramCreate?(program: T): void; useCaseSensitiveFileNames(): boolean; getNewLine(): string; getCurrentDirectory(): string; @@ -4404,6 +4406,10 @@ declare namespace ts { /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[]; } + interface WatchCompilerHost extends ProgramHost, WatchHost { + /** If provided, callback to invoke after every new program creation */ + afterProgramCreate?(program: T): void; + } /** * Host to create watch with root files and options */ @@ -4706,8 +4712,8 @@ declare namespace ts { getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan | undefined; getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan | undefined; getSignatureHelpItems(fileName: string, position: number, options: SignatureHelpItemsOptions | undefined): SignatureHelpItems | undefined; - getRenameInfo(fileName: string, position: number): RenameInfo; - findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): ReadonlyArray | undefined; + getRenameInfo(fileName: string, position: number, options?: RenameInfoOptions): RenameInfo; + findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename?: boolean): ReadonlyArray | undefined; getDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; getDefinitionAndBoundSpan(fileName: string, position: number): DefinitionInfoAndBoundSpan | undefined; getTypeDefinitionAtPosition(fileName: string, position: number): ReadonlyArray | undefined; @@ -5150,6 +5156,9 @@ declare namespace ts { canRename: false; localizedErrorMessage: string; } + interface RenameInfoOptions { + readonly allowRenameOfImportPath?: boolean; + } interface SignatureHelpParameter { name: string; documentation: SymbolDisplayPart[]; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 25e193cff42..456bf6e54ec 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -75,7 +75,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = ts.versionMajorMinor + ".0-rc"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -1267,6 +1267,18 @@ var ts; return result; } ts.extend = extend; + function copyProperties(first, second) { + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + first[id] = second[id]; + } + } + } + ts.copyProperties = copyProperties; + function maybeBind(obj, fn) { + return fn ? fn.bind(obj) : undefined; + } + ts.maybeBind = maybeBind; function createMultiMap() { var map = createMap(); map.add = multiMapAdd; @@ -1985,7 +1997,11 @@ var ts; } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; function fill(length, cb) { - return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + var result = Array(length); + for (var i = 0; i < length; i++) { + result[i] = cb(i); + } + return result; } ts.fill = fill; })(ts || (ts = {})); @@ -3242,15 +3258,17 @@ var ts; CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; - CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; - CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; - CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; - CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; - CheckFlags[CheckFlags["Late"] = 1024] = "Late"; - CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter"; - CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter"; + CheckFlags[CheckFlags["HasLiteralType"] = 64] = "HasLiteralType"; + CheckFlags[CheckFlags["ContainsPublic"] = 128] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 256] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 512] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 1024] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 2048] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 4096] = "ReverseMapped"; + CheckFlags[CheckFlags["OptionalParameter"] = 8192] = "OptionalParameter"; + CheckFlags[CheckFlags["RestParameter"] = 16384] = "RestParameter"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + CheckFlags[CheckFlags["Discriminant"] = 96] = "Discriminant"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; (function (InternalSymbolName) { @@ -4002,6 +4020,16 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + /* @internal */ + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + ts.generateDjb2Hash = generateDjb2Hash; /** * Set a high stack trace limit to provide more information in case of an error. * Called for command-line and server use cases. @@ -4878,14 +4906,6 @@ var ts; return; } } - /** - * djb2 hashing algorithm - * http://www.cse.yorku.ca/~oz/hash.html - */ - function generateDjb2Hash(data) { - var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); - return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); - } function createMD5HashUsingNativeCrypto(data) { var hash = _crypto.createHash("md5"); hash.update(data); @@ -5239,6 +5259,9 @@ var ts; Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), + An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."), + A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."), + A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5394,8 +5417,6 @@ var ts; Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), - Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), - Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), @@ -5409,7 +5430,7 @@ var ts; A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), - In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values: diag(2474, ts.DiagnosticCategory.Error, "const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values_2474", "const enum member initializers can only contain literal values and other computed enum values."), 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: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'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."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), @@ -5425,11 +5446,11 @@ var ts; The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), - Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Tuple_type_0_of_length_1_has_no_element_at_index_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493", "Tuple type '{0}' of length '{1}' has no element at index '{2}'."), Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), - Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export: diag(2497, ts.DiagnosticCategory.Error, "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497", "This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export."), Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), @@ -5618,6 +5639,11 @@ var ts; Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), + No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments: diag(2743, ts.DiagnosticCategory.Error, "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743", "No overload expects {0} type arguments, but overloads do exist that expect either {1} or {2} type arguments."), + Type_parameter_defaults_can_only_reference_previously_declared_type_parameters: diag(2744, ts.DiagnosticCategory.Error, "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744", "Type parameter defaults can only reference previously declared type parameters."), + This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."), + This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."), + _0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5967,6 +5993,7 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -6045,6 +6072,7 @@ var ts; JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), + Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -6181,6 +6209,7 @@ var ts; Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), + Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"), }; })(ts || (ts = {})); var ts; @@ -6405,16 +6434,13 @@ var ts; return result; } ts.computeLineStarts = computeLineStarts; - function getPositionOfLineAndCharacter(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); + function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) { + return sourceFile.getPositionOfLineAndCharacter ? + sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) : + computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; /* @internal */ - function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); - } - ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; - /* @internal */ function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { if (line < 0 || line >= lineStarts.length) { if (allowEdits) { @@ -6990,6 +7016,7 @@ var ts; result = text.substring(start, end); // No need to use all the fragments; no _ removal needed } if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */)); return { type: 8 /* NumericLiteral */, value: "" + +result // if value is not an integer, it can be safely coerced to a number @@ -6998,9 +7025,29 @@ var ts; else { tokenValue = result; var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + checkForIdentifierStartAfterNumericLiteral(start); return { type: type, value: tokenValue }; } } + function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { + if (!isIdentifierStart(text.charCodeAt(pos), languageVersion)) { + return; + } + var identifierStart = pos; + var length = scanIdentifierParts().length; + if (length === 1 && text[identifierStart] === "n") { + if (isScientific) { + error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1); + } + else { + error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1); + } + } + else { + error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length); + pos = identifierStart; + } + } function scanOctalDigits() { var start = pos; while (isOctalDigit(text.charCodeAt(pos))) { @@ -8909,7 +8956,7 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, node.pos); } var isMissing = nodeIsMissing(errorNode); - var pos = isMissing + var pos = isMissing || ts.isJsxText(node) ? errorNode.pos : ts.skipTrivia(sourceFile.text, errorNode.pos); // These asserts should all be satisfied for a properly constructed `errorNode`. @@ -10104,6 +10151,7 @@ var ts; return node.initializer; } } + ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration; function getSingleVariableOfVariableStatement(node) { return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } @@ -12142,10 +12190,10 @@ var ts; } if (getCheckFlags(s) & 6 /* Synthetic */) { var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : - checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + var accessModifier = checkFlags & 512 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 128 /* ContainsPublic */ ? 4 /* Public */ : 16 /* Protected */; - var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + var staticModifier = checkFlags & 1024 /* ContainsStatic */ ? 32 /* Static */ : 0; return accessModifier | staticModifier; } if (s.flags & 4194304 /* Prototype */) { @@ -12392,6 +12440,10 @@ var ts; || kind === 290 /* JSDocVariadicType */; } ts.isTypeNodeKind = isTypeNodeKind; + function isAccessExpression(node) { + return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */; + } + ts.isAccessExpression = isAccessExpression; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -15270,6 +15322,8 @@ var ts; return path; } ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; function comparePathsWorker(a, b, componentComparer) { if (a === b) return 0 /* EqualTo */; @@ -15277,14 +15331,30 @@ var ts; return -1 /* LessThan */; if (b === undefined) return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, ts.getRootLength(a)); + var bRoot = b.substring(0, ts.getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var 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. var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 0; i < sharedLength; i++) { - var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; - var result = stringComparer(aComponents[i], bComponents[i]); - if (result !== 0 /* EqualTo */) { - return result; + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; } } return ts.compareValues(aComponents.length, bComponents.length); @@ -16776,15 +16846,15 @@ var ts; if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6 /* JSON */) { - var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); - result_1.referencedFiles = ts.emptyArray; - result_1.typeReferenceDirectives = ts.emptyArray; - result_1.libReferenceDirectives = ts.emptyArray; - result_1.amdDependencies = ts.emptyArray; - result_1.hasNoDefaultLib = false; - result_1.pragmas = ts.emptyMap; - return result_1; + var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_2.referencedFiles = ts.emptyArray; + result_2.typeReferenceDirectives = ts.emptyArray; + result_2.libReferenceDirectives = ts.emptyArray; + result_2.amdDependencies = ts.emptyArray; + result_2.hasNoDefaultLib = false; + result_2.pragmas = ts.emptyMap; + return result_2; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); @@ -17663,6 +17733,8 @@ var ts; return parseElement(); } function currentNode(parsingContext) { + // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse. + // // If there is an outstanding parse error that we've encountered, but not attached to // some node, then we cannot get a node from the old source tree. This is because we // want to mark the next node we encounter as being unusable. @@ -17670,25 +17742,15 @@ var ts; // Note: This may be too conservative. Perhaps we could reuse the node and set the bit // on it (or its leftmost child) as having the error. For now though, being conservative // is nice and likely won't ever affect perf. - if (parseErrorBeforeNextFinishedNode) { - return undefined; - } - if (!syntaxCursor) { - // if we don't have a cursor, we could never return a node from the old tree. + if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } var node = syntaxCursor.currentNode(scanner.getStartPos()); // Can't reuse a missing node. - if (ts.nodeIsMissing(node)) { - return undefined; - } // Can't reuse a node that intersected the change range. - if (node.intersectsChange) { - return undefined; - } // Can't reuse a node that contains a parse error. This is necessary so that we // produce the same set of errors again. - if (ts.containsParseError(node)) { + if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) { return undefined; } // We can only reuse a node if it was parsed under the same strict mode that we're @@ -17723,6 +17785,22 @@ var ts; nextToken(); return node; } + function isReusableParsingContext(parsingContext) { + switch (parsingContext) { + case 5 /* ClassMembers */: + case 2 /* SwitchClauses */: + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + case 6 /* EnumMembers */: + case 4 /* TypeMembers */: + case 8 /* VariableDeclarations */: + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + return true; + } + return false; + } function canReuseNode(node, parsingContext) { switch (parsingContext) { case 5 /* ClassMembers */: @@ -17742,22 +17820,20 @@ var ts; case 17 /* JSDocParameters */: case 16 /* Parameters */: return isReusableParameter(node); - case 18 /* RestProperties */: - return false; // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the // parser reached while looking ahead might be in the edited range (see the example // in canReuseVariableDeclaratorNode for a good case of this). - case 22 /* HeritageClauses */: + // case ParsingContext.HeritageClauses: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 19 /* TypeParameters */: + // case ParsingContext.TypeParameters: // This would probably be safe to reuse. There is no speculative parsing with // type parameters. Note that that's because type *parameters* only occur in // unambiguous *type* contexts. While type *arguments* occur in very ambiguous // *expression* contexts. - case 21 /* TupleElementTypes */: + // case ParsingContext.TupleElementTypes: // This would probably be safe to reuse. There is no speculative parsing with // tuple types. // Technically, type argument list types are probably safe to reuse. While @@ -17765,24 +17841,24 @@ var ts; // produced from speculative parsing a < as a type argument list), we only have // the types because speculative parsing succeeded. Thus, the lookahead never // went past the end of the list and rewound. - case 20 /* TypeArguments */: + // case ParsingContext.TypeArguments: // Note: these are almost certainly not safe to ever reuse. Expressions commonly // need a large amount of lookahead, and we should not reuse them as they may // have actually intersected the edit. - case 11 /* ArgumentExpressions */: + // case ParsingContext.ArgumentExpressions: // This is not safe to reuse for the same reason as the 'AssignmentExpression' // cases. i.e. a property assignment may end with an expression, and thus might // have lookahead far beyond it's old node. - case 12 /* ObjectLiteralMembers */: + // case ParsingContext.ObjectLiteralMembers: // This is probably not safe to reuse. There can be speculative parsing with // type names in a heritage clause. There can be generic names in the type // name list, and there can be left hand side expressions (which can have type // arguments.) - case 7 /* HeritageClauseElement */: + // case ParsingContext.HeritageClauseElement: // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes // on any given element. Same for children. - case 13 /* JsxAttributes */: - case 14 /* JsxChildren */: + // case ParsingContext.JsxAttributes: + // case ParsingContext.JsxChildren: } return false; } @@ -23012,17 +23088,18 @@ var ts; var libReferenceDirectives_1 = context.libReferenceDirectives; ts.forEach(ts.toArray(entryOrList), function (arg) { // TODO: GH#18217 + var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path; if (arg.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; } - else if (arg.arguments.types) { - typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + else if (types) { + typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value }); } - else if (arg.arguments.lib) { - libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + else if (lib) { + libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value }); } - else if (arg.arguments.path) { - referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + else if (path) { + referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value }); } else { reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); @@ -24694,12 +24771,12 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, !configParseResult.configFileSpecs ? function (_) { return false; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); - }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), exclude: configParseResult.configFileSpecs.validatedExcludeSpecs } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); @@ -24717,23 +24794,23 @@ var ts; } function matchesSpecs(path, includeSpecs, excludeSpecs) { if (!includeSpecs) - return function (_) { return false; }; + return function (_) { return true; }; var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { - return function (path) { return includeRe.test(path) && !excludeRe.test(path); }; + return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; } - return function (path) { return includeRe.test(path); }; + return function (path) { return !includeRe.test(path); }; } if (excludeRe) { - return function (path) { return !excludeRe.test(path); }; + return function (path) { return excludeRe.test(path); }; } - return function (_) { return false; }; + return function (_) { return true; }; } function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") { // this is of a type CommandLineOptionOfPrimitiveType return undefined; } @@ -24890,7 +24967,7 @@ var ts; result.push(tab + "}"); } result.push("}"); - return result.join(newLine); + return result.join(newLine) + newLine; } } ts.generateTSConfig = generateTSConfig; @@ -27175,6 +27252,10 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } + // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate) + if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) { + symbol.constEnumOnlyModule = false; + } if (symbolFlags & 67220415 /* Value */) { setValueDeclaration(symbol, node); } @@ -27663,7 +27744,7 @@ var ts; } function isNarrowableReference(expr) { return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || - ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || ts.isElementAccessExpression(expr) && expr.argumentExpression && (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && isNarrowableReference(expr.expression); @@ -31107,10 +31188,10 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(262144 /* TypeParameter */); - var markerSubType = createType(262144 /* TypeParameter */); + var markerSuperType = createTypeParameter(); + var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(262144 /* TypeParameter */); + var markerOtherType = createTypeParameter(); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); @@ -31300,7 +31381,6 @@ var ts; var _jsxFactoryEntity; var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); - var definitelyAssignableRelation = ts.createMap(); var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); @@ -32018,13 +32098,18 @@ var ts; } } break; + case 197 /* ArrowFunction */: + // when targeting ES6 or higher there is no 'arguments' in an arrow function + // for lower compile targets the resolved symbol is used to emit an error + if (compilerOptions.target >= 2 /* ES2015 */) { + break; + } + // falls through case 156 /* MethodDeclaration */: - case 155 /* MethodSignature */: case 157 /* Constructor */: case 158 /* GetAccessor */: case 159 /* SetAccessor */: case 239 /* FunctionDeclaration */: - case 197 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -32080,7 +32165,7 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol) && !isInTypeQuery(originalLocation)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { result.isReferenced |= meaning; } if (!result) { @@ -32158,7 +32243,8 @@ var ts; } // If we're in an external module, we can't reference value symbols created from UMD export declarations if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { - if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { + var merged = getMergedSymbol(result); + if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } @@ -32918,7 +33004,10 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { - error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 + ? "allowSyntheticDefaultImports" + : "esModuleInterop"; + error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); return symbol; } if (compilerOptions.esModuleInterop) { @@ -33213,6 +33302,12 @@ var ts; function createTypeofType() { return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); } + function createTypeParameter(symbol) { + var type = createType(262144 /* TypeParameter */); + if (symbol) + type.symbol = symbol; + return type; + } // A reserved member name starts with two underscores, but the third character cannot be an underscore // or the @ symbol. A third underscore indicates an escaped form of an identifer that started // with at least two underscores. The @ character indicates that the name is denoted by a well known ES @@ -34166,12 +34261,12 @@ var ts; return ts.createKeywordTypeNode(120 /* AnyKeyword */); } function addPropertyToElementList(propertySymbol, context, typeElements) { - var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 4096 /* ReverseMapped */); var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 2048 /* Late */) { var decl = ts.first(propertySymbol.declarations); if (hasLateBindableName(decl)) { trackComputedName(decl.name, saveEnclosingDeclaration, context); @@ -34344,7 +34439,7 @@ var ts; } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; - var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* RestParameter */; var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -34353,7 +34448,7 @@ var ts; cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); - var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* OptionalParameter */; var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, @@ -34749,6 +34844,21 @@ var ts; function isDefaultBindingContext(location) { return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); } + function getNameOfSymbolFromNameType(symbol, context) { + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 384 /* StringOrNumberLiteral */) { + var name = "" + nameType.value; + if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { + return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\""; + } + return name; + } + if (nameType.flags & 8192 /* UniqueESSymbol */) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; + } + } + } /** * Gets a human-readable name for a symbol. * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. @@ -34768,12 +34878,19 @@ var ts; } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - var name = ts.getNameOfDeclaration(declaration); - if (name) { + var name_2 = ts.getNameOfDeclaration(declaration); + if (name_2) { if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { return ts.symbolName(symbol); } - return ts.declarationNameToString(name); + if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 2048 /* Late */) && symbol.nameType && symbol.nameType.flags & 384 /* StringOrNumberLiteral */) { + // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name + var result = getNameOfSymbolFromNameType(symbol, context); + if (result !== undefined) { + return result; + } + } + return ts.declarationNameToString(name_2); } if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -34788,16 +34905,8 @@ var ts; return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } - var nameType = symbol.nameType; - if (nameType) { - if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { - return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; - } - if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { - return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; - } - } - return ts.symbolName(symbol); + var name = getNameOfSymbolFromNameType(symbol, context); + return name !== undefined ? name : ts.symbolName(symbol); } function isDeclarationVisible(node) { if (node) { @@ -35017,6 +35126,9 @@ var ts; var prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } + function getTypeOfPropertyOrIndexSignature(type, name) { + return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType; + } function isTypeAny(type) { return type && (type.flags & 1 /* Any */) !== 0; } @@ -35063,6 +35175,64 @@ var ts; var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); } + // Determine the control flow type associated with a destructuring declaration or assignment. The following + // forms of destructuring are possible: + // let { x } = obj; // BindingElement + // let [ x ] = obj; // BindingElement + // { x } = obj; // ShorthandPropertyAssignment + // { x: v } = obj; // PropertyAssignment + // [ x ] = obj; // Expression + // We construct a synthetic element access expression corresponding to 'obj.x' such that the control + // flow analyzer doesn't have to handle all the different syntactic forms. + function getFlowTypeOfDestructuring(node, declaredType) { + var reference = getSyntheticElementAccess(node); + return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType; + } + function getSyntheticElementAccess(node) { + var parentAccess = getParentElementAccess(node); + if (parentAccess && parentAccess.flowNode) { + var propName = getDestructuringPropertyName(node); + if (propName) { + var result = ts.createNode(190 /* ElementAccessExpression */, node.pos, node.end); + result.parent = node; + result.expression = parentAccess; + var literal = ts.createNode(10 /* StringLiteral */, node.pos, node.end); + literal.parent = result; + literal.text = propName; + result.argumentExpression = literal; + result.flowNode = parentAccess.flowNode; + return result; + } + } + } + function getParentElementAccess(node) { + var ancestor = node.parent.parent; + switch (ancestor.kind) { + case 186 /* BindingElement */: + case 275 /* PropertyAssignment */: + return getSyntheticElementAccess(ancestor); + case 187 /* ArrayLiteralExpression */: + return getSyntheticElementAccess(node.parent); + case 237 /* VariableDeclaration */: + return ancestor.initializer; + case 204 /* BinaryExpression */: + return ancestor.right; + } + } + function getDestructuringPropertyName(node) { + var parent = node.parent; + if (node.kind === 186 /* BindingElement */ && parent.kind === 184 /* ObjectBindingPattern */) { + return getLiteralPropertyNameText(node.propertyName || node.name); + } + if (node.kind === 275 /* PropertyAssignment */ || node.kind === 276 /* ShorthandPropertyAssignment */) { + return getLiteralPropertyNameText(node.name); + } + return "" + parent.elements.indexOf(node); + } + function getLiteralPropertyNameText(name) { + var type = getLiteralTypeFromPropertyName(name); + return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined; + } /** Return the inferred type for a binding element */ function getTypeForBindingElement(declaration) { var pattern = declaration.parent; @@ -35103,9 +35273,9 @@ var ts; else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; - var exprType = getLiteralTypeFromPropertyName(name); - var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); - type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); + var indexType = getLiteralTypeFromPropertyName(name); + var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); } } else { @@ -35122,21 +35292,13 @@ var ts; mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } + else if (isArrayLikeType(parentType)) { + var indexType = getLiteralType(index_1); + var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, declaration.name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); + } else { - // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_2 = pattern.elements.indexOf(declaration); - type = everyType(parentType, isTupleLikeType) ? - getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : - elementType; - if (!type) { - if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); - } - else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); - } - return errorType; - } + type = elementType; } } // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -35587,12 +35749,11 @@ var ts; return anyType; } // Handle export default expressions - if (ts.isSourceFile(declaration)) { - var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - if (!jsonSourceFile.statements.length) { + if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) { + if (!declaration.statements.length) { return emptyObjectType; } - var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + var type_1 = getWidenedLiteralType(checkExpression(declaration.statements[0].expression)); if (type_1.flags & 524288 /* Object */) { return getRegularTypeOfObjectLiteral(type_1); } @@ -35603,6 +35764,10 @@ var ts; } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & 512 /* ValueModule */) { + return getTypeOfFuncClassEnumModule(symbol); + } return errorType; } var type; @@ -35616,7 +35781,8 @@ var ts; || ts.isClassDeclaration(declaration) || ts.isFunctionDeclaration(declaration) || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { + || ts.isMethodSignature(declaration) + || ts.isSourceFile(declaration)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { return getTypeOfFuncClassEnumModule(symbol); @@ -35656,6 +35822,10 @@ var ts; return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } if (!popTypeResolution()) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & 512 /* ValueModule */) { + return getTypeOfFuncClassEnumModule(symbol); + } type = reportCircularityError(symbol); } return type; @@ -35849,7 +36019,7 @@ var ts; if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } - if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) { + if (ts.getCheckFlags(symbol) & 4096 /* ReverseMapped */) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -36228,9 +36398,8 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(262144 /* TypeParameter */); + type.thisType = createTypeParameter(symbol); type.thisType.isThisType = true; - type.thisType.symbol = symbol; type.thisType.constraint = type; } } @@ -36366,19 +36535,11 @@ var ts; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var type = createType(262144 /* TypeParameter */); - type.symbol = symbol; - links.declaredType = type; - } - return links.declaredType; + return links.declaredType || (links.declaredType = createTypeParameter(symbol)); } function getDeclaredTypeOfAlias(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); - } - return links.declaredType; + return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol))); } function getDeclaredTypeOfSymbol(symbol) { return tryGetDeclaredTypeOfSymbol(symbol) || errorType; @@ -36575,7 +36736,7 @@ var ts; * members. */ function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { - ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol."); + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 2048 /* Late */), "Expected a late-bound symbol."); symbol.flags |= symbolFlags; getSymbolLinks(member.symbol).lateSymbol = symbol; if (!symbol.declarations) { @@ -36632,7 +36793,7 @@ var ts; // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations. var lateSymbol = lateSymbols.get(memberName); if (!lateSymbol) - lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */)); + lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 2048 /* Late */)); // Report an error if a late-bound member has the same name as an early-bound member, // or if we have another early-bound symbol declaration with the same name and // conflicting flags. @@ -36641,10 +36802,10 @@ var ts; // If we have an existing early-bound member, combine its declarations so that we can // report an error at each declaration. var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_2 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); - lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); + var name_3 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + lateSymbol = createSymbol(0 /* None */, memberName, 2048 /* Late */); } lateSymbol.nameType = type; addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); @@ -36820,8 +36981,8 @@ var ts; var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; var restParams = ts.map(elementTypes, function (t, i) { var name = getParameterNameAtPosition(sig, restIndex_1 + i); - var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ : - i >= minLength_1 ? 4096 /* OptionalParameter */ : 0; + var checkFlags = i === tupleRestIndex_1 ? 16384 /* RestParameter */ : + i >= minLength_1 ? 8192 /* OptionalParameter */ : 0; var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; return symbol; @@ -36894,7 +37055,13 @@ var ts; // type is the union of the constituent return types. function getUnionSignatures(signatureLists) { var result; + var indexWithLengthOverOne; for (var i = 0; i < signatureLists.length; i++) { + if (signatureLists[i].length === 0) + return ts.emptyArray; + if (signatureLists[i].length > 1) { + indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets + } for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { var signature = _a[_i]; // Only process signatures with parameter lists that aren't already in the result list @@ -36919,8 +37086,82 @@ var ts; } } } + if (!ts.length(result) && indexWithLengthOverOne !== -1) { + // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single + // signature that handles all over them. We only do this when there are overloads in only one constituent. + // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of + // signatures from the type, whose ordering would be non-obvious) + var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; + var results = masterList.slice(); + var _loop_5 = function (signatures) { + if (signatures !== masterList) { + var signature_1 = signatures[0]; + ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); + results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); + if (!results) { + return "break"; + } + } + }; + for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) { + var signatures = signatureLists_1[_b]; + var state_2 = _loop_5(signatures); + if (state_2 === "break") + break; + } + result = results; + } return result || ts.emptyArray; } + function combineUnionThisParam(left, right) { + if (!left || !right) { + return left || right; + } + // A signature `this` type might be a read or a write position... It's very possible that it should be invariant + // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be + // permissive when calling, for now, we'll union the `this` types just like the overlapping-union-signature check does + var thisType = getUnionType([getTypeOfSymbol(left), getTypeOfSymbol(right)], 2 /* Subtype */); + return createSymbolWithType(left, thisType); + } + function combineUnionParameters(left, right) { + var longest = getParameterCount(left) >= getParameterCount(right) ? left : right; + var shorter = longest === left ? right : left; + var longestCount = getParameterCount(longest); + var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (var i = 0; i < longestCount; i++) { + var longestParamType = tryGetTypeAtPosition(longest, i); + var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + var unionParamType = getIntersectionType([longestParamType, shorterParamType]); + var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + var leftName = getParameterNameAtPosition(left, i); + var rightName = getParameterNameAtPosition(right, i); + var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), leftName === rightName ? leftName : "arg" + i); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args"); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfUnionMembers(left, right) { + var declaration = left.declaration; + var params = combineUnionParameters(left, right); + var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); + var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + var hasRestParam = left.hasRestParameter || right.hasRestParameter; + var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; + var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); + return result; + } function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; @@ -36938,7 +37179,7 @@ var ts; function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union // type use getPropertiesOfType (only the language service uses this). - var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); })); var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); @@ -36974,7 +37215,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_5 = function (i) { + var _loop_6 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -36997,7 +37238,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_5(i); + _loop_6(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -37073,7 +37314,7 @@ var ts; var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { var prop = _a[_i]; - var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + var checkFlags = 4096 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); inferredProp.declarations = prop.declarations; inferredProp.nameType = prop.nameType; @@ -37084,6 +37325,37 @@ var ts; } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); } + // Return the lower bound of the key type in a mapped type. Intuitively, the lower + // bound includes those keys that are known to always be present, for example because + // because of constraints on type parameters (e.g. 'keyof T' for a constrained T). + function getLowerBoundOfKeyType(type) { + if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) { + return type; + } + if (type.flags & 4194304 /* Index */) { + return getIndexType(getApparentType(type.type)); + } + if (type.flags & 16777216 /* Conditional */) { + return getLowerBoundOfConditionalType(type); + } + if (type.flags & 1048576 /* Union */) { + return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); + } + if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); + } + return neverType; + } + function getLowerBoundOfConditionalType(type) { + if (type.root.isDistributive) { + var constraint = getLowerBoundOfKeyType(type.checkType); + if (constraint !== type.checkType) { + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** Resolve the members of a mapped type { [P in K]: T } */ function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); @@ -37113,10 +37385,7 @@ var ts; } } else { - // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Then iterate over the constituents of the key type. - var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; - forEachType(iterationType, addMemberForKeyType); + forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); function addMemberForKeyType(t) { @@ -37300,7 +37569,7 @@ var ts; return list.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); }); } function getAllPossiblePropertiesOfTypes(types) { @@ -37364,7 +37633,7 @@ var ts; if (type.root.isDistributive) { var simplified = getSimplifiedType(type.checkType); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; - if (constraint) { + if (constraint && constraint !== type.checkType) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); if (!(instantiated.flags & 131072 /* Never */)) { @@ -37609,10 +37878,10 @@ var ts; commonFlags &= prop.flags; props = ts.appendIfUnique(props, prop); checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | - (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | - (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | - (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | - (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 512 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 1024 /* ContainsStatic */ : 0); if (!isPrototypeProperty(prop)) { syntheticFlag = 2 /* SyntheticProperty */; } @@ -37636,39 +37905,38 @@ var ts; return props[0]; } var declarations; - var commonType; + var firstType; var nameType; var propTypes = []; - var first = true; - var commonValueDeclaration; + var firstValueDeclaration; var hasNonUniformValueDeclaration = false; for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { var prop = props_1[_b]; - if (!commonValueDeclaration) { - commonValueDeclaration = prop.valueDeclaration; + if (!firstValueDeclaration) { + firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== commonValueDeclaration) { + else if (prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = ts.addRange(declarations, prop.declarations); var type = getTypeOfSymbol(prop); - if (first) { - commonType = type; + if (!firstType) { + firstType = type; nameType = prop.nameType; - first = false; } - else { - if (type !== commonType) { - checkFlags |= 32 /* HasNonUniformType */; - } + else if (type !== firstType) { + checkFlags |= 32 /* HasNonUniformType */; + } + if (isLiteralType(type)) { + checkFlags |= 64 /* HasLiteralType */; } propTypes.push(type); } ts.addRange(propTypes, indexTypes); var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; - if (!hasNonUniformValueDeclaration && commonValueDeclaration) { - result.valueDeclaration = commonValueDeclaration; + if (!hasNonUniformValueDeclaration && firstValueDeclaration) { + result.valueDeclaration = firstValueDeclaration; } result.declarations = declarations; result.nameType = nameType; @@ -37868,21 +38136,17 @@ var ts; var numTypeArguments = ts.length(typeArguments); if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { var result = typeArguments ? typeArguments.slice() : []; - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + // Map invalid forward references in default types to the error type for (var i = numTypeArguments; i < numTypeParameters; i++) { - result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + result[i] = errorType; } + var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny); for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, result); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { defaultType = anyType; } - result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType; } result.length = typeParameters.length; return result; @@ -37971,7 +38235,7 @@ var ts; var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); - var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */); + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 16384 /* RestParameter */); syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; if (lastParamVariadicType) { // Replace the last parameter with a rest parameter. @@ -38842,7 +39106,7 @@ var ts; if (arity) { typeParameters = new Array(arity); for (var i = 0; i < arity; i++) { - var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); + var typeParameter = typeParameters[i] = createTypeParameter(); if (i < maxLength) { var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); property.type = typeParameter; @@ -38864,7 +39128,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(262144 /* TypeParameter */); + type.thisType = createTypeParameter(); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -39365,8 +39629,13 @@ var ts; if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { - var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + if (prop.escapedName === "default" /* Default */) { + type = getLiteralType("default"); + } + else { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + } } if (type && type.flags & include) { return type; @@ -39456,14 +39725,14 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = isTypeUsableAsLateBoundName(indexType) - ? getLateBoundNameFromType(indexType) - : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) - ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) - : accessNode && ts.isPropertyName(accessNode) + var propName = isTypeUsableAsLateBoundName(indexType) ? + getLateBoundNameFromType(indexType) : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? + ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : + accessNode && ts.isPropertyName(accessNode) ? // late bound names are handled in the first branch, so here we only need to handle normal names - ? ts.getPropertyNameForPropertyNameNode(accessNode) - : undefined; + ts.getPropertyNameForPropertyNameNode(accessNode) : + undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { @@ -39485,7 +39754,12 @@ var ts; if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { var indexNode = getIndexNodeForAccessExpression(accessNode); - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + if (isTupleType(objectType)) { + error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName)); + } + else { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } } return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } @@ -39610,24 +39884,14 @@ var ts; // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we - // construct the type Box. We do not further simplify the result because mapped types can be recursive - // and we might never terminate. + // construct the type Box. if (isGenericMappedType(objectType)) { - return type.simplified = substituteIndexedMappedType(objectType, type); - } - if (objectType.flags & 262144 /* TypeParameter */) { - var constraint = getConstraintOfTypeParameter(objectType); - if (constraint && isGenericMappedType(constraint)) { - return type.simplified = substituteIndexedMappedType(constraint, type); - } + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var templateMapper = combineTypeMappers(objectType.mapper, mapper); + return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType); } return type.simplified = type; } - function substituteIndexedMappedType(objectType, type) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); - } function getIndexedAccessType(objectType, indexType, accessNode, missingType) { if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { @@ -39715,14 +39979,11 @@ var ts; if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } - // If this is a distributive conditional type and the check type is generic we need to defer - // resolution of the conditional type such that a later instantiation will properly distribute - // over union types. - var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); + var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */); var combinedMapper; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); - if (!isDeferred) { + if (!checkTypeInstantiable) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. @@ -39730,28 +39991,30 @@ var ts; } combinedMapper = combineTypeMappers(mapper, context); } - if (!isDeferred) { - if (extendsType.flags & 3 /* AnyOrUnknown */) { + // Instantiate the extends type including inferences for 'infer T' type parameters + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // We attempt to resolve the conditional type only when the check and extends types are non-generic + if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */)) { + if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) { return instantiateType(root.trueType, mapper); } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & 1 /* Any */) { return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); } - // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; // Return falseType for a definitely false extends check. We check an instantations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instatiations will be and we can just return the false branch type. - if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { return instantiateType(root.falseType, mapper); } - // Return trueType for a definitely true extends check. The definitely assignable relation excludes - // type variable constraints from consideration. Without the definitely assignable relation, the type + // Return trueType for a definitely true extends check. We check instantiations of the two + // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter + // that has no constraint. This ensures that, for example, the type // type Foo = T extends { x: string } ? string : number - // would immediately resolve to 'string' instead of being deferred. - if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + // doesn't immediately resolve to 'string' instead of being deferred. + if (isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) { return instantiateType(root.trueType, combinedMapper || mapper); } } @@ -40300,12 +40563,17 @@ var ts; function createReplacementMapper(source, target, baseMapper) { return function (t) { return t === source ? target : baseMapper(t); }; } - function wildcardMapper(type) { + function permissiveMapper(type) { return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; } + function getRestrictiveTypeParameter(tp) { + return !tp.constraint ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol)); + } + function restrictiveMapper(type) { + return type.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(type) : type; + } function cloneTypeParameter(typeParameter) { - var result = createType(262144 /* TypeParameter */); - result.symbol = typeParameter.symbol; + var result = createTypeParameter(typeParameter.symbol); result.target = typeParameter; return result; } @@ -40364,7 +40632,7 @@ var ts; } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */)); + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */)); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -40636,9 +40904,13 @@ var ts; } return type; } - function getWildcardInstantiation(type) { + function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : - type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); + type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); + } + function getRestrictiveInstantiation(type) { + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : + type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); @@ -40702,8 +40974,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - var body = node.body; - return body.kind === 218 /* Block */ ? false : isContextSensitive(body); + return !!node.body && node.body.kind !== 218 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -40820,7 +41091,7 @@ var ts; case 187 /* ArrayLiteralExpression */: return elaborateArrayLiteral(node, source, target, relation); case 268 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target, relation); + return elaborateJsxComponents(node, source, target, relation); case 197 /* ArrowFunction */: return elaborateArrowFunction(node, source, target, relation); } @@ -40961,8 +41232,117 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target, relation) { - return elaborateElementwise(generateJsxAttributes(node), source, target, relation); + function generateJsxChildren(node, getInvalidTextDiagnostic) { + var memberOffset, i, child, nameType, elem; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!ts.length(node.children)) + return [2 /*return*/]; + memberOffset = 0; + i = 0; + _a.label = 1; + case 1: + if (!(i < node.children.length)) return [3 /*break*/, 5]; + child = node.children[i]; + nameType = getLiteralType(i - memberOffset); + elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic); + if (!elem) return [3 /*break*/, 3]; + return [4 /*yield*/, elem]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + memberOffset++; + _a.label = 4; + case 4: + i++; + return [3 /*break*/, 1]; + case 5: return [2 /*return*/]; + } + }); + } + function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { + switch (child.kind) { + case 270 /* JsxExpression */: + // child is of the type of the expression + return { errorNode: child, innerExpression: child.expression, nameType: nameType }; + case 11 /* JsxText */: + if (child.containsOnlyWhiteSpaces) { + break; // Whitespace only jsx text isn't real jsx text + } + // child is a string + return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + // child is of type JSX.Element + return { errorNode: child, innerExpression: child, nameType: nameType }; + default: + return ts.Debug.assertNever(child, "Found invalid jsx child"); + } + } + function elaborateJsxComponents(node, source, target, relation) { + var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation); + var invalidTextDiagnostic; + if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) { + var containingElement = node.parent.parent; + var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName); + var childrenNameType = getLiteralType(childrenPropName); + var childrenTargetType = getIndexedAccessType(target, childrenNameType); + var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; }); + if (!ts.length(validChildren)) { + return result; + } + var moreThanOneRealChildren = ts.length(validChildren) > 1; + var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType); + var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); }); + if (moreThanOneRealChildren) { + if (arrayLikeTargetParts !== neverType) { + var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */)); + result = elaborateElementwise(generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic), realSource, arrayLikeTargetParts, relation) || result; + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + // arity mismatch + result = true; + error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, typeToString(childrenTargetType)); + } + } + else { + if (nonArrayLikeTargetParts !== neverType) { + var child = validChildren[0]; + var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic); + if (elem_1) { + result = elaborateElementwise((function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, elem_1]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); })(), source, target, relation) || result; + } + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + // arity mismatch + result = true; + error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, typeToString(childrenTargetType)); + } + } + } + return result; + function getInvalidTextualChildDiagnostic() { + if (!invalidTextDiagnostic) { + var tagNameText = ts.getTextOfNode(node.parent.tagName); + var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName); + var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName)); + var diagnostic = ts.Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2; + invalidTextDiagnostic = __assign({}, diagnostic, { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) }); + } + return invalidTextDiagnostic; + } } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -41215,7 +41595,7 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & 67108864 /* NonPrimitive */ ? true : type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : @@ -41298,9 +41678,7 @@ var ts; return true; if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) return true; - if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) - return false; - if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { + if (relation === assignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) return true; // Type number or any numeric literal type is assignable to any numeric enum type or any @@ -41470,7 +41848,7 @@ var ts; target = target.regularType; } if (source.flags & 33554432 /* Substitution */) { - source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; + source = source.substitute; } if (target.flags & 33554432 /* Substitution */) { target = target.typeVariable; @@ -41645,9 +42023,9 @@ var ts; if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + if (isExcessPropertyCheckTarget(target)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && + if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } @@ -41655,9 +42033,12 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_6 = function (prop) { + var _loop_7 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { + // Report error in terms of object types in the target as those are the only ones + // we check in isKnownProperty. + var errorTarget = filterType(target, isExcessPropertyCheckTarget); // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. @@ -41667,7 +42048,7 @@ var ts; // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) - reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget)); } else { // use the property's value declaration if the property is assigned inside the literal itself @@ -41679,14 +42060,14 @@ var ts; errorNode = propDeclaration; var name = propDeclaration.name; if (ts.isIdentifier(name)) { - suggestion = getSuggestionForNonexistentProperty(name, target); + suggestion = getSuggestionForNonexistentProperty(name, errorTarget); } } if (suggestion !== undefined) { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion); } else { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget)); } } } @@ -41695,9 +42076,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_6(prop); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_7(prop); + if (typeof state_3 === "object") + return state_3.value; } } return false; @@ -41734,7 +42115,8 @@ var ts; var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || - findBestTypeForInvokable(source, target); + findBestTypeForInvokable(source, target) || + findMostOverlappyType(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -41769,6 +42151,34 @@ var ts; return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); } } + function findMostOverlappyType(source, unionTarget) { + var bestMatch; + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target_1 = _a[_i]; + var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]); + if (overlap.flags & 4194304 /* Index */) { + // perfect overlap of keys + bestMatch = target_1; + matchingCount = Infinity; + } + else if (overlap.flags & 1048576 /* Union */) { + // We only want to account for literal types otherwise. + // If we have a union of index types, it seems likely that we + // needed to elaborate between two generic mapped types anyway. + var len = ts.length(ts.filter(overlap.types, isUnitType)); + if (len >= matchingCount) { + bestMatch = target_1; + matchingCount = len; + } + } + else if (isUnitType(overlap) && 1 >= matchingCount) { + bestMatch = target_1; + matchingCount = 1; + } + } + return bestMatch; + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { if (target.flags & 1048576 /* Union */) { @@ -41942,30 +42352,27 @@ var ts; } return result; } - function getConstraintForRelation(type) { - return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); - } function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { var flags = source.flags & target.flags; if (relation === identityRelation && !(flags & 524288 /* Object */)) { if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_2 = 0 /* False */; + var result_3 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_2; + if (result_3 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_3; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_2; + if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_3; } } } @@ -42014,24 +42421,23 @@ var ts; } // A type S is assignable to keyof T if S is assignable to keyof C, where C is the // simplified form of T or, if T doesn't simplify, the constraint of T. - if (relation !== definitelyAssignableRelation) { - var simplified = getSimplifiedType(target.type); - var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); - if (constraint) { - // We require Ternary.True here such that circular constraints don't cause - // false positives. For example, given 'T extends { [K in keyof T]: string }', - // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when - // related to other types. - if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { - return -1 /* True */; - } + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } else if (target.flags & 8388608 /* IndexedAccess */) { // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, // where C is the base constraint of T[K] - if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + if (relation !== identityRelation && + !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { var constraint = getBaseConstraintOfType(target); if (constraint && constraint !== target) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -42072,8 +42478,8 @@ var ts; return result; } } - var constraint = getConstraintForRelation(source); - if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + var constraint = getConstraintOfType(source); + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { errorInfo = saveErrorInfo; @@ -42113,7 +42519,7 @@ var ts; } } } - else if (relation !== definitelyAssignableRelation) { + else { var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { @@ -42132,7 +42538,7 @@ var ts; } else { // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + if (isPartialMappedType(target) && isEmptyObjectType(source)) { return -1 /* True */; } if (isGenericMappedType(target)) { @@ -42144,9 +42550,6 @@ var ts; } return 0 /* False */; } - if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { - return 0 /* False */; - } var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); if (relation !== identityRelation) { source = getApparentType(source); @@ -42226,10 +42629,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_3; - if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_4; + if (result_4 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_4 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -42239,10 +42642,10 @@ var ts; return propertiesIdenticalTo(source, target); } var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); - var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false); if (unmatchedProperty) { if (reportErrors) { - var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false)); if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it @@ -42318,7 +42721,7 @@ var ts; var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; - if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */ && hasDifferingDeclarations) { + if (ts.getCheckFlags(sourceProp) & 512 /* ContainsPrivate */ && hasDifferingDeclarations) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -42994,6 +43397,9 @@ var ts; function isTupleLikeType(type) { return isTupleType(type) || !!getPropertyOfType(type, "0"); } + function isArrayOrTupleLikeType(type) { + return isArrayLikeType(type) || isTupleLikeType(type); + } function getTupleElementType(type, index) { var propType = getTypeOfPropertyOfType(type, "" + index); if (propType) { @@ -43283,6 +43689,9 @@ var ts; // union includes empty object types (e.g. reducing {} | string to just {}). return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); } + if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.sameMap(type.types, getWidenedType)); + } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); } @@ -43369,6 +43778,10 @@ var ts; break; case 186 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + if (!noImplicitAny) { + // Don't issue a suggestion for binding elements since the codefix doesn't yet support them. + return; + } break; case 289 /* JSDocFunctionType */: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); @@ -43566,8 +43979,8 @@ var ts; inferTypes([inference], sourceType, templateType); return getTypeFromInference(inference); } - function getUnmatchedProperties(source, target, requireOptionalProperties) { - var properties, _i, properties_4, targetProp, sourceProp; + function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) { + var properties, _i, properties_4, targetProp, sourceProp, targetType, sourceType; return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -43575,24 +43988,34 @@ var ts; _i = 0, properties_4 = properties; _a.label = 1; case 1: - if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + if (!(_i < properties_4.length)) return [3 /*break*/, 6]; targetProp = properties_4[_i]; - if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 5]; sourceProp = getPropertyOfType(source, targetProp.escapedName); if (!!sourceProp) return [3 /*break*/, 3]; return [4 /*yield*/, targetProp]; case 2: _a.sent(); - _a.label = 3; + return [3 /*break*/, 5]; case 3: + if (!matchDiscriminantProperties) return [3 /*break*/, 5]; + targetType = getTypeOfSymbol(targetProp); + if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5]; + sourceType = getTypeOfSymbol(sourceProp); + if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5]; + return [4 /*yield*/, targetProp]; + case 4: + _a.sent(); + _a.label = 5; + case 5: _i++; return [3 /*break*/, 1]; - case 4: return [2 /*return*/]; + case 6: return [2 /*return*/]; } }); } - function getUnmatchedProperty(source, target, requireOptionalProperties) { - return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; + function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next().value; } function tupleTypesDefinitelyUnrelated(source, target) { return target.target.minLength > source.target.minLength || @@ -43602,7 +44025,8 @@ var ts; // Two tuple types with incompatible arities are definitely unrelated. // Two object types that each have a property that is unmatched in the other are definitely unrelated. return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || - !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) && + !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true); } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : @@ -44207,48 +44631,31 @@ var ts; // occurring in an apparent type position with '@' because the control flow type // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { - if (node.kind === 72 /* Identifier */) { - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; - } - if (node.kind === 100 /* ThisKeyword */) { - return "0"; - } - if (node.kind === 189 /* PropertyAccessExpression */) { - var key = getFlowCacheKey(node.expression); - return key && key + "." + ts.idText(node.name); - } - if (node.kind === 186 /* BindingElement */) { - var container = node.parent.parent; - var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); - var text = getBindingElementNameText(node); - var result = key && text && (key + "." + text); - return result; + switch (node.kind) { + case 72 /* Identifier */: + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + case 100 /* ThisKeyword */: + return "0"; + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + return getFlowCacheKey(node.expression); + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + var propName = getAccessedPropertyName(node); + if (propName !== undefined) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + propName; + } } return undefined; } - function getBindingElementNameText(element) { - var parent = element.parent; - if (parent.kind === 184 /* ObjectBindingPattern */) { - var name = element.propertyName || element.name; - switch (name.kind) { - case 72 /* Identifier */: - return ts.idText(name); - case 149 /* ComputedPropertyName */: - return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; - case 10 /* StringLiteral */: - case 8 /* NumericLiteral */: - return name.text; - default: - // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined - ts.Debug.fail("Unexpected name kind for binding element name"); - } - } - else { - return "" + parent.elements.indexOf(element); - } - } function isMatchingReference(source, target) { + switch (target.kind) { + case 195 /* ParenthesizedExpression */: + case 213 /* NonNullExpression */: + return isMatchingReference(source, target.expression); + } switch (source.kind) { case 72 /* Identifier */: return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || @@ -44258,34 +44665,24 @@ var ts; return target.kind === 100 /* ThisKeyword */; case 98 /* SuperKeyword */: return target.kind === 98 /* SuperKeyword */; + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + return isMatchingReference(source.expression, target); case 189 /* PropertyAccessExpression */: case 190 /* ElementAccessExpression */: - return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 186 /* BindingElement */: - if (target.kind !== 189 /* PropertyAccessExpression */) - return false; - var t = target; - if (t.name.escapedText !== getBindingElementNameText(source)) - return false; - if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { - return true; - } - if (source.parent.parent.kind === 237 /* VariableDeclaration */) { - var maybeId = source.parent.parent.initializer; - return !!maybeId && isMatchingReference(maybeId, t.expression); - } } return false; } function getAccessedPropertyName(access) { - return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + return access.kind === 189 /* PropertyAccessExpression */ ? access.name.escapedText : ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : undefined; } function containsMatchingReference(source, target) { - while (source.kind === 189 /* PropertyAccessExpression */) { + while (ts.isAccessExpression(source)) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -44298,42 +44695,37 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 189 /* PropertyAccessExpression */ && + var name; + return ts.isAccessExpression(target) && containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + (name = getAccessedPropertyName(target)) !== undefined && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), name); } function getDeclaredTypeOfReference(expr) { if (expr.kind === 72 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 189 /* PropertyAccessExpression */) { + if (ts.isAccessExpression(expr)) { var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + if (type) { + var propName = getAccessedPropertyName(expr); + return propName !== undefined ? getTypeOfPropertyOfType(type, propName) : undefined; + } } return undefined; } function isDiscriminantType(type) { - if (type.flags & 1048576 /* Union */) { - if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { - return true; - } - var combined = 0; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - combined |= t.flags; - } - if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { - return true; - } - } - return false; + return !!(type.flags & 1048576 /* Union */ && + (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */) || !isGenericIndexType(type))); } function isDiscriminantProperty(type, name) { if (type && type.flags & 1048576 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = + (prop.checkFlags & 96 /* Discriminant */) === 96 /* Discriminant */ && + isDiscriminantType(getTypeOfSymbol(prop)); } return !!prop.isDiscriminantProperty; } @@ -45192,25 +45584,23 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 1048576 /* Union */) || - expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { return false; } - var access = expr; - var name = getAccessedPropertyName(access); - if (!name) { + var name = getAccessedPropertyName(expr); + if (name === undefined) { return false; } - return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); - if (!propName) { + if (propName === undefined) { return type; } var propType = getTypeOfPropertyOfType(type, propName); var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOrIndexSignature(t, propName), narrowedPropType); }); } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { @@ -45555,9 +45945,8 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { - var accessExpression = invokedExpression; - var possibleReference = ts.skipParentheses(accessExpression.expression); + if (ts.isAccessExpression(invokedExpression)) { + var possibleReference = ts.skipParentheses(invokedExpression.expression); if (isMatchingReference(reference, possibleReference)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } @@ -45974,7 +46363,7 @@ var ts; } function checkThisBeforeSuper(node, container, diagnosticMessage) { var containingClassDecl = container.parent; - var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); + var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl); // If a containing class does not have extends clause or the class extends null // skip checking whether super statement is called before "this" accessing. if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { @@ -46295,7 +46684,7 @@ var ts; } // at this point the only legal case for parent is ClassLikeDeclaration var classLikeDeclaration = container.parent; - if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { + if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); return errorType; } @@ -46452,6 +46841,30 @@ var ts; tryGetTypeAtPosition(contextualSignature, index); } } + function getContextualTypeForVariableLikeDeclaration(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + switch (declaration.kind) { + case 151 /* Parameter */: + return getContextuallyTypedParameterType(declaration); + case 186 /* BindingElement */: + return getContextualTypeForBindingElement(declaration); + // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent + } + } + function getContextualTypeForBindingElement(declaration) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + var parentType = getContextualTypeForVariableLikeDeclaration(parentDeclaration); + if (parentType && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text !== undefined) { + return getTypeOfPropertyOfType(parentType, text); + } + } + } // In a variable, parameter or property declaration with a type annotation, // the contextual type of an initializer expression is the type of the variable, parameter or property. // Otherwise, in a parameter declaration of a contextually typed function expression, @@ -46463,32 +46876,13 @@ var ts; function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; if (ts.hasInitializer(declaration) && node === declaration.initializer) { - var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - return getTypeFromTypeNode(typeNode); + var result = getContextualTypeForVariableLikeDeclaration(declaration); + if (result) { + return result; } - if (declaration.kind === 151 /* Parameter */) { - var type = getContextuallyTypedParameterType(declaration); - if (type) { - return type; - } - } - if (ts.isBindingPattern(declaration.name)) { + if (ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } - if (ts.isBindingPattern(declaration.parent)) { - var parentDeclaration = declaration.parent.parent; - var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 186 /* BindingElement */) { - var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); - if (parentTypeNode && !ts.isBindingPattern(name)) { - var text = ts.getTextOfPropertyName(name); - if (text) { - return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); - } - } - } - } } return undefined; } @@ -46741,18 +47135,30 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForChildJsxExpression(node) { + function getContextualTypeForChildJsxExpression(node, child) { var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); - return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { + return undefined; + } + var childIndex = node.children.indexOf(child); + var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName); + return childFieldType && mapType(childFieldType, function (t) { + if (isArrayLikeType(t)) { + return getIndexedAccessType(t, getLiteralType(childIndex)); + } + else { + return t; + } + }, /*noReductions*/ true); } function getContextualTypeForJsxExpression(node) { var exprParent = node.parent; return ts.isJsxAttributeLike(exprParent) ? getContextualType(node) : ts.isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent, node) : undefined; } function getContextualTypeForJsxAttribute(attribute) { @@ -46919,6 +47325,27 @@ var ts; return propsType; } function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + if (sig.unionSignatures) { + // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input + // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature, + // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur + // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input. + // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane. + var results = []; + for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + var instance = getReturnTypeOfSignature(signature); + if (isTypeAny(instance)) { + return instance; + } + var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation); + if (!propType) { + return; + } + results.push(propType); + } + return getIntersectionType(results); + } var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } @@ -47310,7 +47737,7 @@ var ts; var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? computedNameType : undefined; var prop = nameType ? - createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : + createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 2048 /* Late */) : createSymbol(4 /* Property */ | member.flags, member.escapedName); if (nameType) { prop.nameType = nameType; @@ -47910,7 +48337,7 @@ var ts; return true; } } - else if (targetType.flags & 3145728 /* UnionOrIntersection */) { + else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -47918,12 +48345,14 @@ var ts; } } } - else if (targetType.flags & 16777216 /* Conditional */) { - return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || - isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); - } return false; } + function isExcessPropertyCheckTarget(type) { + return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) || + type.flags & 67108864 /* NonPrimitive */ || + type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) || + type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget)); + } function checkJsxExpression(node, checkMode) { if (node.expression) { var type = checkExpression(node.expression, checkMode); @@ -47964,7 +48393,7 @@ var ts; function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; - if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(prop) & 512 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; @@ -48328,7 +48757,7 @@ var ts; } } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (nodeForCheckWriteOnly && isInTypeQuery(nodeForCheckWriteOnly) || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { @@ -48354,7 +48783,7 @@ var ts; } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind === 189 /* PropertyAccessExpression */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -49039,15 +49468,32 @@ var ts; return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { - var min = Infinity; - var max = -Infinity; + var argCount = typeArguments.length; + // No overloads exist + if (signatures.length === 1) { + var sig = signatures[0]; + var min_1 = getMinTypeArgumentCount(sig.typeParameters); + var max = ts.length(sig.typeParameters); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, min_1 < max ? min_1 + "-" + max : min_1, argCount); + } + // Overloads exist + var belowArgCount = -Infinity; + var aboveArgCount = Infinity; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, ts.length(sig.typeParameters)); + var min_2 = getMinTypeArgumentCount(sig.typeParameters); + var max = ts.length(sig.typeParameters); + if (min_2 > argCount) { + aboveArgCount = Math.min(aboveArgCount, min_2); + } + else if (max < argCount) { + belowArgCount = Math.max(belowArgCount, max); + } } - var paramCount = min === max ? min : min + "-" + max; - return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) { + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; @@ -49276,7 +49722,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_7 = function (i) { + var _loop_8 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -49287,7 +49733,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_7(i); + _loop_8(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -49444,7 +49890,7 @@ var ts; */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { @@ -49952,6 +50398,7 @@ var ts; if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.nameType = getLiteralType("default"); newSymbol.target = resolveSymbol(symbol); memberTable.set("default" /* Default */, newSymbol); var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); @@ -50945,20 +51392,18 @@ var ts; if (rightIsThis === void 0) { rightIsThis = false; } if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 149 /* ComputedPropertyName */) { - checkComputedPropertyName(name); - } - if (isComputedNonLiteralName(name)) { - return undefined; - } - var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); - if (type) { - // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); - } - else { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + var text = ts.getTextOfPropertyName(name); + if (text) { + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + } } + var exprType = getLiteralTypeFromPropertyName(name); + var elementType = getIndexedAccessType(objectLiteralType, exprType, name); + var type = getFlowTypeOfDestructuring(property, elementType); + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else if (property.kind === 277 /* SpreadAssignment */) { if (languageVersion < 6 /* ESNext */) { @@ -50978,23 +51423,6 @@ var ts; error(property, ts.Diagnostics.Property_assignment_expected); } } - function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { - if (isTypeAny(objectLiteralType)) { - return objectLiteralType; - } - var type; - var text = ts.getTextOfPropertyName(name); - if (text) { // TODO: GH#26379 - var prop = getPropertyOfType(objectLiteralType, text); - if (prop) { - markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); - type = getTypeOfSymbol(prop); - } - type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); - } - return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); - } function checkArrayLiteralAssignment(node, sourceType, checkMode) { var elements = node.elements; if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { @@ -51014,39 +51442,30 @@ var ts; var element = elements[elementIndex]; if (element.kind !== 210 /* OmittedExpression */) { if (element.kind !== 208 /* SpreadElement */) { - var propName = "" + elementIndex; - var type = isTypeAny(sourceType) ? sourceType : - everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : - elementType; - if (type) { + var indexType = getLiteralType(elementIndex); + if (isArrayLikeType(sourceType)) { + // We create a synthetic expression so that getIndexedAccessType doesn't get confused + // when the element is a SyntaxKind.ElementAccessExpression. + var elementType_2 = getIndexedAccessType(sourceType, indexType, createSyntheticExpression(element, indexType)); + var type = getFlowTypeOfDestructuring(element, elementType_2); return checkDestructuringAssignment(element, type, checkMode); } - // We still need to check element expression here because we may need to set appropriate flag on the expression - // such as NodeCheckFlags.LexicalThis on "this"expression. - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } + return checkDestructuringAssignment(element, elementType, checkMode); + } + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { - if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + var restExpression = element.expression; + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { - var restExpression = element.expression; - if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { - error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - else { - checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = everyType(sourceType, isTupleType) ? - mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : - createArrayType(elementType); - return checkDestructuringAssignment(restExpression, type, checkMode); - } + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); } } } @@ -51567,7 +51986,8 @@ var ts; var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) || - isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + isTypeAssertion(initializer) || + isLiteralOfContextualType(type, getContextualType(initializer)) ? type : getWidenedLiteralType(type); if (ts.isInJSFile(declaration)) { if (widened.flags & 98304 /* Nullable */) { reportImplicitAny(declaration, anyType); @@ -52250,7 +52670,7 @@ var ts; // Constructors of classes with no extends clause may not contain super calls, whereas // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; - if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { + if (ts.getClassExtendsHeritageElement(containingClassDecl)) { captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); @@ -52444,7 +52864,6 @@ var ts; break; } } - checkGrammarForDisallowedTrailingComma(node.elementTypes); ts.forEach(node.elementTypes, checkSourceElement); } function checkUnionOrIntersectionType(node) { @@ -52813,10 +53232,10 @@ var ts; case 248 /* ImportEqualsDeclaration */: case 251 /* NamespaceImport */: case 250 /* ImportClause */: - var result_4 = 0 /* None */; + var result_5 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); - return result_4; + ts.forEach(target.declarations, function (d) { result_5 |= getDeclarationSpaces(d); }); + return result_5; case 237 /* VariableDeclaration */: case 186 /* BindingElement */: case 239 /* FunctionDeclaration */: @@ -53304,7 +53723,12 @@ var ts; return; } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + if (ts.isQualifiedName(node.name)) { + error(node.name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(node.name), ts.entityNameToString(node.name.left)); + } + else { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name)); + } } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && @@ -54842,6 +55266,7 @@ var ts; if (produceDiagnostics) { if (node.default) { seenDefault = true; + checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i); } else if (seenDefault) { error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); @@ -54855,6 +55280,23 @@ var ts; } } } + /** Check that type parameter defaults only reference previously declared type parameters */ + function checkTypeParametersNotReferenced(root, typeParameters, index) { + visit(root); + function visit(node) { + if (node.kind === 164 /* TypeReference */) { + var type = getTypeFromTypeReference(node); + if (type.flags & 262144 /* TypeParameter */) { + for (var i = index; i < typeParameters.length; i++) { + if (type.symbol === getSymbolOfNode(typeParameters[i])) { + error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters); + } + } + } + } + ts.forEachChild(node, visit); + } + } /** Check that type parameter lists are identical across multiple declarations */ function checkTypeParameterListsIdentical(symbol) { if (symbol.declarations.length === 1) { @@ -55045,7 +55487,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_8 = function (member) { + var _loop_9 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -55064,7 +55506,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_8(member); + _loop_9(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -55338,7 +55780,7 @@ var ts; return 0; } else if (isConstEnum) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values); } else if (member.parent.flags & 4194304 /* Ambient */) { error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); @@ -57420,7 +57862,7 @@ var ts; isLateBound: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); var symbol = node && getSymbolOfNode(node); - return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); + return !!(symbol && ts.getCheckFlags(symbol) & 2048 /* Late */); }, getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { @@ -58012,9 +58454,6 @@ var ts; if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070 checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); } - if (ts.isBindingPattern(parameter.name)) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } if (parameter.questionToken) { return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); } @@ -59000,9 +59439,6 @@ var ts; JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; // tslint:enable variable-name })(JsxNames || (JsxNames = {})); - function typeIsLiteralType(type) { - return !!(type.flags & 2944 /* Literal */); - } })(ts || (ts = {})); var ts; (function (ts) { @@ -64566,15 +65002,19 @@ var ts; // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + function getLineInfo(text, lineStarts) { + return { + getLineCount: function () { return lineStarts.length; }, + getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); } + }; + } + ts.getLineInfo = getLineInfo; /** * Tries to find the sourceMappingURL comment at the end of a file. - * @param text The source text of the file. - * @param lineStarts The line starts of the file. */ - function tryGetSourceMappingURL(text, lineStarts) { - if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } - for (var index = lineStarts.length - 1; index >= 0; index--) { - var line = text.substring(lineStarts[index], lineStarts[index + 1]); + function tryGetSourceMappingURL(lineInfo) { + for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) { + var line = lineInfo.getLineText(index); var comment = sourceMapCommentRegExp.exec(line); if (comment) { return comment[1]; @@ -64818,7 +65258,10 @@ var ts; && left.sourcePosition === right.sourcePosition; } function compareSourcePositions(left, right) { - return ts.compareValues(left.sourceIndex, right.sourceIndex); + // Compares sourcePosition without comparing sourceIndex + // since the mappings are grouped by sourceIndex + ts.Debug.assert(left.sourceIndex === right.sourceIndex); + return ts.compareValues(left.sourcePosition, right.sourcePosition); } function compareGeneratedPositions(left, right) { return ts.compareValues(left.generatedPosition, right.generatedPosition); @@ -64833,11 +65276,9 @@ var ts; var mapDirectory = ts.getDirectoryPath(mapPath); var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); - var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); - var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath); var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); - var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); - var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; })); var decodedMappings; var generatedMappings; var sourceMappings; @@ -64847,16 +65288,15 @@ var ts; }; function processMapping(mapping) { var generatedPosition = generatedFile !== undefined - ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true) : -1; var source; var sourcePosition; if (isSourceMapping(mapping)) { - var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; - var sourceFile = host.getSourceFileLike(sourceFilePath); + var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]); source = map.sources[mapping.sourceIndex]; sourcePosition = sourceFile !== undefined - ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true) : -1; } return { @@ -67274,6 +67714,7 @@ var ts; switch (node.literal.kind) { case 10 /* StringLiteral */: return ts.createIdentifier("String"); + case 202 /* PrefixUnaryExpression */: case 8 /* NumericLiteral */: return ts.createIdentifier("Number"); case 9 /* BigIntLiteral */: @@ -71044,7 +71485,7 @@ var ts; if (node.name) { enableSubstitutionsForBlockScopedBindings(); } - var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + var extendsClauseElement = ts.getClassExtendsHeritageElement(node); var classFunction = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -71453,7 +71894,7 @@ var ts; * synthesized call to `super` */ function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; + return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper); } /** * Adds statements to the body of a function-like node if it contains a rest parameter. @@ -71470,10 +71911,10 @@ var ts; return; } // `declarationName` is the name of the local declaration for the parameter. - var declarationName = ts.getMutableClone(parameter.name); + var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined); ts.setEmitFlags(declarationName, 48 /* NoSourceMap */); // `expressionName` is the name of the parameter used in expressions. - var expressionName = ts.getSynthesizedClone(parameter.name); + var expressionName = parameter.name.kind === 72 /* Identifier */ ? ts.getSynthesizedClone(parameter.name) : declarationName; var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; @@ -71497,6 +71938,11 @@ var ts; ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); statements.push(forStatement); + if (parameter.name.kind !== 72 /* Identifier */) { + // do the actual destructuring of the rest parameter if necessary + statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */)); + } } /** * Adds a statement to capture the `this` of a function declaration if it is needed. @@ -79732,6 +80178,7 @@ var ts; case 241 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; + case 166 /* ConstructorType */: case 161 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; @@ -79750,6 +80197,7 @@ var ts; diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; + case 165 /* FunctionType */: case 239 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; @@ -80327,7 +80775,10 @@ var ts; if (!ts.isLateVisibilityPaintedStatement(i)) { return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); } + var priorNeedsDeclare = needsDeclare; + needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + needsDeclare = priorNeedsDeclare; lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); } // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list @@ -80690,7 +81141,8 @@ var ts; var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression - var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 + var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default"; + var newId_1 = ts.createOptimisticUniqueName(oldId + "_base"); getSymbolAccessibilityDiagnostic = function () { return ({ diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: extendsClause_1, @@ -80844,7 +81296,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_9 = function (range) { + var _loop_10 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -80858,7 +81310,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_9(range); + _loop_10(range); } } return prop; @@ -82748,18 +83200,22 @@ var ts; function emitPropertyAccessExpression(node) { var indentBeforeDot = false; var indentAfterDot = false; + var dotRangeFirstCommentStart = ts.skipTrivia(currentSourceFile.text, node.expression.end, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ true); + var dotRangeStart = ts.skipTrivia(currentSourceFile.text, dotRangeFirstCommentStart); + var dotRangeEnd = dotRangeStart + 1; if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { - var dotRangeStart = node.expression.end; - var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; var dotToken = ts.createToken(24 /* DotToken */); - dotToken.pos = dotRangeStart; + dotToken.pos = node.expression.end; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } emitExpression(node.expression); increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + var dotHasCommentTrivia = dotRangeFirstCommentStart !== dotRangeStart; + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression, dotHasCommentTrivia); if (shouldEmitDotDot) { writePunctuation("."); } @@ -82770,13 +83226,15 @@ var ts; } // 1..toString is a valid property access, emit a dot after the literal // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal - function needsDotDotForPropertyAccess(expression) { + function needsDotDotForPropertyAccess(expression, dotHasTrivia) { expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); - return !expression.numericLiteralFlags - && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); + // If he number will be printed verbatim and it doesn't already contain a dot, add one + // if the expression doesn't have any comments that will be emitted. + return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)) && + (!dotHasTrivia || printerOptions.removeComments); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -83527,6 +83985,7 @@ var ts; function emitJsxSelfClosingElement(node) { writePunctuation("<"); emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); writeSpace(); emit(node.attributes); writePunctuation("/>"); @@ -83540,6 +83999,7 @@ var ts; writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } @@ -85145,7 +85605,7 @@ var ts; if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { return; } - var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character; sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, /*nameIndex*/ undefined); } @@ -85554,7 +86014,7 @@ var ts; }, flags); } function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { - return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2); } function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); @@ -85635,7 +86095,7 @@ var ts; var text; try { ts.performance.mark("beforeIORead"); - text = system.readFile(fileName, options.charset); + text = compilerHost.readFile(fileName); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -85661,7 +86121,12 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - system.createDirectory(directoryPath); + if (compilerHost.createDirectory) { + compilerHost.createDirectory(directoryPath); + } + else { + system.createDirectory(directoryPath); + } } } var outputFingerprints; @@ -85713,7 +86178,7 @@ var ts; } var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); var realpath = system.realpath && (function (path) { return system.realpath(path); }); - return { + var compilerHost = { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -85729,10 +86194,112 @@ var ts; getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }, + createDirectory: function (d) { return system.createDirectory(d); } }; + return compilerHost; } ts.createCompilerHostWorker = createCompilerHostWorker; + /*@internal*/ + function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) { + var originalReadFile = host.readFile; + var originalFileExists = host.fileExists; + var originalDirectoryExists = host.directoryExists; + var originalCreateDirectory = host.createDirectory; + var originalWriteFile = host.writeFile; + var readFileCache = ts.createMap(); + var fileExistsCache = ts.createMap(); + var directoryExistsCache = ts.createMap(); + var sourceFileCache = ts.createMap(); + var readFileWithCache = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value || undefined; + return setReadFileCache(key, fileName); + }; + var setReadFileCache = function (key, fileName) { + var newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue || false); + return newValue; + }; + host.readFile = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value; // could be .d.ts from output + if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) { + return originalReadFile.call(host, fileName); + } + return setReadFileCache(key, fileName); + }; + var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { + var key = toPath(fileName); + var value = sourceFileCache.get(key); + if (value) + return value; + var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile); + if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) { + sourceFileCache.set(key, sourceFile); + } + return sourceFile; + } : undefined; + // fileExists for any kind of extension + host.fileExists = function (fileName) { + var key = toPath(fileName); + var value = fileExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + if (originalWriteFile) { + host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) { + var key = toPath(fileName); + fileExistsCache.delete(key); + var value = readFileCache.get(key); + if (value && value !== data) { + readFileCache.delete(key); + sourceFileCache.delete(key); + } + else if (getSourceFileWithCache) { + var sourceFile = sourceFileCache.get(key); + if (sourceFile && sourceFile.text !== data) { + sourceFileCache.delete(key); + } + } + originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles); + }; + } + // directoryExists + if (originalDirectoryExists && originalCreateDirectory) { + host.directoryExists = function (directory) { + var key = toPath(directory); + var value = directoryExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + return { + originalReadFile: originalReadFile, + originalFileExists: originalFileExists, + originalDirectoryExists: originalDirectoryExists, + originalCreateDirectory: originalCreateDirectory, + originalWriteFile: originalWriteFile, + getSourceFileWithCache: getSourceFileWithCache, + readFileWithCache: readFileWithCache + }; + } + ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (ts.getEmitDeclarations(program.getCompilerOptions())) { @@ -86065,7 +86632,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); - var configParsingHost = parseConfigHostFromCompilerHost(host); + var configParsingHost = parseConfigHostFromCompilerHostLike(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); @@ -86111,6 +86678,12 @@ var ts; var sourceFileToPackageName = ts.createMap(); // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. var redirectTargetsMap = ts.createMultiMap(); + /** + * map with + * - SourceFile if present + * - false if sourceFile missing for source of project reference redirect + * - undefined otherwise + */ var filesByName = ts.createMap(); var missingFilePaths; // stores 'filename -> file association' ignoring case @@ -86171,7 +86744,10 @@ var ts; }); } } - missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) { + var path = _a[0], file = _a[1]; + return file === undefined ? path : undefined; + })); files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); processingDefaultLibFiles = undefined; processingOtherFiles = undefined; @@ -86317,13 +86893,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_5 = []; + var result_6 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_5.push(resolvedModule); + result_6.push(resolvedModule); } - return result_5; + return result_6; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -86779,7 +87355,7 @@ var ts; return getSourceFileByPath(toPath(fileName)); } function getSourceFileByPath(path) { - return filesByName.get(path); + return filesByName.get(path) || undefined; } function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { if (sourceFile) { @@ -87257,7 +87833,7 @@ var ts; } /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ function getSourceFileFromReference(referencingFile, ref) { - return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; }); } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { @@ -87363,7 +87939,9 @@ var ts; processReferencedFiles(file_1, isDefaultLib); processTypeReferenceDirectives(file_1); } - processLibReferenceDirectives(file_1); + if (!options.noLib) { + processLibReferenceDirectives(file_1); + } modulesWithElidedImports.set(file_1.path, false); processImportedModules(file_1); } @@ -87374,7 +87952,7 @@ var ts; processImportedModules(file_1); } } - return file_1; + return file_1 || undefined; } var redirectedPath; if (refFile) { @@ -87440,7 +88018,9 @@ var ts; processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } - processLibReferenceDirectives(file); + if (!options.noLib) { + processLibReferenceDirectives(file); + } // always process imported modules to record module name resolutions processImportedModules(file); if (isDefaultLib) { @@ -87453,9 +88033,12 @@ var ts; return file; } function addFileToFilesByName(file, path, redirectedPath) { - filesByName.set(path, file); if (redirectedPath) { filesByName.set(redirectedPath, file); + filesByName.set(path, file || false); + } + else { + filesByName.set(path, file); } } function getProjectReferenceRedirect(fileName) { @@ -88118,21 +88701,22 @@ var ts; } ts.createProgram = createProgram; /* @internal */ - function parseConfigHostFromCompilerHost(host) { + function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) { + if (directoryStructureHost === void 0) { directoryStructureHost = host; } return { - fileExists: function (f) { return host.fileExists(f); }, + fileExists: function (f) { return directoryStructureHost.fileExists(f); }, readDirectory: function (root, extensions, excludes, includes, depth) { - ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(root, extensions, excludes, includes, depth); + ts.Debug.assertDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); }, - readFile: function (f) { return host.readFile(f); }, + readFile: function (f) { return directoryStructureHost.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, - onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }), trace: host.trace ? function (s) { return host.trace(s); } : undefined }; } - ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike; function resolveProjectReferencePath(hostOrRef, ref) { var passedInRef = ref ? ref : hostOrRef; return ts.resolveConfigFileProjectName(passedInRef.path); @@ -88199,6 +88783,10 @@ var ts; } } ts.getFileEmitOutput = getFileEmitOutput; + function cloneMapOrUndefined(map) { + return map ? ts.cloneMap(map) : undefined; + } + ts.cloneMapOrUndefined = cloneMapOrUndefined; })(ts || (ts = {})); /*@internal*/ (function (ts) { @@ -88346,12 +88934,35 @@ var ts; fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, - allFilesExcludingDefaultLibraryFile: undefined, - allFileNames: undefined + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature }; } BuilderState.create = create; + /** + * Releases needed properties + */ + function releaseCache(state) { + state.allFilesExcludingDefaultLibraryFile = undefined; + state.allFileNames = undefined; + } + BuilderState.releaseCache = releaseCache; + /** + * Creates a clone of the state + */ + function clone(state) { + var fileInfos = ts.createMap(); + state.fileInfos.forEach(function (value, key) { + fileInfos.set(key, __assign({}, value)); + }); + // Dont need to backup allFiles info since its cache anyway + return { + fileInfos: fileInfos, + referencedMap: ts.cloneMapOrUndefined(state.referencedMap), + exportedModulesMap: ts.cloneMapOrUndefined(state.exportedModulesMap), + hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature), + }; + } + BuilderState.clone = clone; /** * Gets the files affected by the path from the program */ @@ -88600,7 +89211,7 @@ var ts; var seenFileNamesMap = ts.createMap(); // Start with the paths this file was referenced by seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); - var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath); while (queue.length > 0) { var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { @@ -88608,7 +89219,7 @@ var ts; seenFileNamesMap.set(currentPath, currentSourceFile); if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 queue.push.apply(// TODO: GH#18217 - queue, getReferencedByPaths(state, currentPath)); + queue, getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } } @@ -88632,24 +89243,32 @@ var ts; var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); - if (!compilerOptions.outFile && !compilerOptions.out) { + state.compilerOptions = compilerOptions; + // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them + // With --isolatedModules, emitting changed file doesnt emit dependent files so we cant know of dependent files to retrieve errors so dont cache the errors + if (!compilerOptions.outFile && !compilerOptions.out && !compilerOptions.isolatedModules) { state.semanticDiagnosticsPerFile = ts.createMap(); } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; + var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { - ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + var affectedSignatures = oldState.currentAffectedFilesSignatures; + ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); } if (canCopySemanticDiagnostics) { ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); } // Copy old state's changed files set ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit; + state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; + } } // Update changed files and copy semantic diagnostics if we can var referencedMap = state.referencedMap; @@ -88673,7 +89292,7 @@ var ts; state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { - var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + var sourceFile = newProgram.getSourceFileByPath(sourceFilePath); if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { return; } @@ -88693,6 +89312,36 @@ var ts; }); return state; } + /** + * Releases program and other related not needed properties + */ + function releaseCache(state) { + ts.BuilderState.releaseCache(state); + state.program = undefined; + } + /** + * Creates a clone of the state + */ + function cloneBuilderProgramState(state) { + var newState = ts.BuilderState.clone(state); + newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile); + newState.changedFilesSet = ts.cloneMap(state.changedFilesSet); + newState.affectedFiles = state.affectedFiles; + newState.affectedFilesIndex = state.affectedFilesIndex; + newState.currentChangedFilePath = state.currentChangedFilePath; + newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures); + newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap); + newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles); + newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; + newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState); + newState.program = state.program; + newState.compilerOptions = state.compilerOptions; + newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit; + newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; + newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles); + newState.programEmitComplete = state.programEmitComplete; + return newState; + } /** * Verifies that source file is ok to be used in calls that arent handled by next */ @@ -88739,22 +89388,43 @@ var ts; } // With --out or --outFile all outputs go into single file // so operations are performed directly on program, return program - var compilerOptions = state.program.getCompilerOptions(); + var program = ts.Debug.assertDefined(state.program); + var compilerOptions = program.getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); - return state.program; + return program; } // Get next batch of affected files state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); if (state.exportedModulesMap) { state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); } - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); } } + /** + * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet + */ + function getNextAffectedFilePendingEmit(state) { + var affectedFilesPendingEmit = state.affectedFilesPendingEmit; + if (affectedFilesPendingEmit) { + var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap()); + for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) { + var affectedFile = ts.Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]); + if (affectedFile && !seenEmittedFiles.has(affectedFile.path)) { + // emit this file + state.affectedFilesPendingEmitIndex = i; + return affectedFile; + } + } + state.affectedFilesPendingEmit = undefined; + state.affectedFilesPendingEmitIndex = undefined; + } + return undefined; + } /** * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file */ @@ -88766,9 +89436,10 @@ var ts; // Clean lib file diagnostics if its all files excluding default files to emit if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { state.cleanedDiagnosticsOfLibFiles = true; - var options_2 = state.program.getCompilerOptions(); - if (ts.forEach(state.program.getSourceFiles(), function (f) { - return state.program.isSourceFileDefaultLibrary(f) && + var program_1 = ts.Debug.assertDefined(state.program); + var options_2 = program_1.getCompilerOptions(); + if (ts.forEach(program_1.getSourceFiles(), function (f) { + return program_1.isSourceFileDefaultLibrary(f) && !ts.skipTypeChecking(f, options_2) && removeSemanticDiagnosticsOf(state, f.path); })) { @@ -88829,11 +89500,20 @@ var ts; return true; } // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected - return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(filePath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); - }); + })) { + return true; + } + // Remove diagnostics of files that import this file (without going to exports of referencing files) + return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) { + return referencesInFile.has(filePath) && + !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file + removeSemanticDiagnosticsOf(state, referencingFilePath); + } // Dont add to seen since this is not yet done with the export removal + ); } /** * Removes semantic diagnostics for path and @@ -88851,20 +89531,26 @@ var ts; * This is called after completing operation on the next affected file. * The operations here are postponed to ensure that cancellation during the iteration is handled correctly */ - function doneWithAffectedFile(state, affected) { + function doneWithAffectedFile(state, affected, isPendingEmit) { if (affected === state.program) { state.changedFilesSet.clear(); + state.programEmitComplete = true; } else { state.seenAffectedFiles.set(affected.path, true); - state.affectedFilesIndex++; + if (isPendingEmit) { + state.affectedFilesPendingEmitIndex++; + } + else { + state.affectedFilesIndex++; + } } } /** * Returns the result with affected file */ - function toAffectedFileResult(state, result, affected) { - doneWithAffectedFile(state, affected); + function toAffectedFileResult(state, result, affected, isPendingEmit) { + doneWithAffectedFile(state, affected, isPendingEmit); return { result: result, affected: affected }; } /** @@ -88873,14 +89559,18 @@ var ts; */ function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { var path = sourceFile.path; - var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - return cachedDiagnostics; + if (state.semanticDiagnosticsPerFile) { + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } } // Diagnostics werent cached, get them from program, and cache the result - var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); - state.semanticDiagnosticsPerFile.set(path, diagnostics); + var diagnostics = ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); + if (state.semanticDiagnosticsPerFile) { + state.semanticDiagnosticsPerFile.set(path, diagnostics); + } return diagnostics; } var BuilderProgramKind; @@ -88905,7 +89595,7 @@ var ts; rootNames: newProgramOrRootNames, options: hostOrOptions, host: oldProgramOrHost, - oldProgram: oldProgram && oldProgram.getProgram(), + oldProgram: oldProgram && oldProgram.getProgramOrUndefined(), configFileParsingDiagnostics: configFileParsingDiagnostics, projectReferences: projectReferences }); @@ -88936,26 +89626,29 @@ var ts; /** * Computing hash to for signature verification */ - var computeHash = host.createHash || ts.identity; + var computeHash = host.createHash || ts.generateDjb2Hash; var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + var backupState; // To ensure that we arent storing any references to old program or new program without state newProgram = undefined; // TODO: GH#18217 oldProgram = undefined; oldState = undefined; - var result = { - getState: function () { return state; }, - getProgram: function () { return state.program; }, - getCompilerOptions: function () { return state.program.getCompilerOptions(); }, - getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, - getSourceFiles: function () { return state.program.getSourceFiles(); }, - getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, - getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, - getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, - getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, - getSemanticDiagnostics: getSemanticDiagnostics, - emit: emit, - getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, - getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + var result = createRedirectedBuilderProgram(state, configFileParsingDiagnostics); + result.getState = function () { return state; }; + result.backupState = function () { + ts.Debug.assert(backupState === undefined); + backupState = cloneBuilderProgramState(state); + }; + result.restoreState = function () { + state = ts.Debug.assertDefined(backupState); + backupState = undefined; + }; + result.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.assertDefined(state.program), sourceFile); }; + result.getSemanticDiagnostics = getSemanticDiagnostics; + result.emit = emit; + result.releaseProgram = function () { + releaseCache(state); + backupState = undefined; }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; @@ -88974,14 +89667,33 @@ var ts; */ function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { var affected = getNextAffectedFile(state, cancellationToken, computeHash); + var isPendingEmitFile = false; if (!affected) { - // Done - return undefined; + if (!state.compilerOptions.out && !state.compilerOptions.outFile) { + affected = getNextAffectedFilePendingEmit(state); + if (!affected) { + return undefined; + } + isPendingEmitFile = true; + } + else { + var program = ts.Debug.assertDefined(state.program); + // Check if program uses any prepend project references, if thats the case we cant track of the js files of those, so emit even though there are no changes + if (state.programEmitComplete || !ts.some(program.getProjectReferences(), function (ref) { return !!ref.prepend; })) { + state.programEmitComplete = true; + return undefined; + } + affected = program; + } + } + // Mark seen emitted files if there are pending files to be emitted + if (state.affectedFilesPendingEmit && state.program !== affected) { + (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.path, true); } return toAffectedFileResult(state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file - state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + ts.Debug.assertDefined(state.program).emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected, isPendingEmitFile); } /** * Emits the JavaScript and declaration files. @@ -89018,7 +89730,7 @@ var ts; }; } } - return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return ts.Debug.assertDefined(state.program).emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); } /** * Return the semantic diagnostics for the next affected file or undefined if iteration is complete @@ -89054,25 +89766,38 @@ var ts; */ function getSemanticDiagnostics(sourceFile, cancellationToken) { assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); - var compilerOptions = state.program.getCompilerOptions(); + var compilerOptions = ts.Debug.assertDefined(state.program).getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); // We dont need to cache the diagnostics just return them from program - return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + return ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); } if (sourceFile) { return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); } - if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { - // When semantic builder asks for diagnostics of the whole program, - // ensure that all the affected files are handled - var affected = void 0; - while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { - doneWithAffectedFile(state, affected); + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected; + var affectedFilesPendingEmit; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + if (affected !== state.program && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push(affected.path); + } + doneWithAffectedFile(state, affected); + } + // In case of emit builder, cache the files to be emitted + if (affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, affectedFilesPendingEmit); + // affectedFilesPendingEmitIndex === undefined + // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files + // so start from 0 as array would be affectedFilesPendingEmit + // else, continue to iterate from existing index, the current set is appended to existing files + if (state.affectedFilesPendingEmitIndex === undefined) { + state.affectedFilesPendingEmitIndex = 0; } } var diagnostics; - for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { var sourceFile_2 = _a[_i]; diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); } @@ -89080,6 +89805,32 @@ var ts; } } ts.createBuilderProgram = createBuilderProgram; + function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { + return { + getState: ts.notImplemented, + backupState: ts.noop, + restoreState: ts.noop, + getProgram: getProgram, + getProgramOrUndefined: function () { return state.program; }, + releaseProgram: function () { return state.program = undefined; }, + getCompilerOptions: function () { return state.compilerOptions; }, + getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); }, + getSourceFiles: function () { return getProgram().getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); }, + emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); }, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); } + }; + function getProgram() { + return ts.Debug.assertDefined(state.program); + } + } + ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram; })(ts || (ts = {})); (function (ts) { function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { @@ -89091,23 +89842,8 @@ var ts; } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; - return { - // Only return program, all other methods are not implemented - getProgram: function () { return program; }, - getState: ts.notImplemented, - getCompilerOptions: ts.notImplemented, - getSourceFile: ts.notImplemented, - getSourceFiles: ts.notImplemented, - getOptionsDiagnostics: ts.notImplemented, - getGlobalDiagnostics: ts.notImplemented, - getConfigFileParsingDiagnostics: ts.notImplemented, - getSyntacticDiagnostics: ts.notImplemented, - getSemanticDiagnostics: ts.notImplemented, - emit: ts.notImplemented, - getAllDependencies: ts.notImplemented, - getCurrentDirectory: ts.notImplemented - }; + var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics; + return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics); } ts.createAbstractBuilder = createAbstractBuilder; })(ts || (ts = {})); @@ -89911,7 +90647,7 @@ var ts; if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { return; // Don't want to a package to globally import from itself } - var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); if (target === undefined) return; var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); @@ -90286,37 +91022,103 @@ var ts; var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); return { onWatchStatusChange: onWatchStatusChange, - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + watchFile: ts.maybeBind(system, system.watchFile) || (function () { return noopFileWatcher; }), + watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return noopFileWatcher; }), + setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop, + clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop }; } ts.createWatchHost = createWatchHost; + var WatchType; + (function (WatchType) { + WatchType["ConfigFile"] = "Config file"; + WatchType["SourceFile"] = "Source file"; + WatchType["MissingFile"] = "Missing file"; + WatchType["WildcardDirectory"] = "Wild card directory"; + WatchType["FailedLookupLocations"] = "Failed Lookup Locations"; + WatchType["TypeRoots"] = "Type roots"; + })(WatchType = ts.WatchType || (ts.WatchType = {})); + function createWatchFactory(host, options) { + var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop; + var result = ts.getWatchFactory(watchLogLevel, writeLog); + result.writeLog = writeLog; + return result; + } + ts.createWatchFactory = createWatchFactory; + function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) { + if (directoryStructureHost === void 0) { directoryStructureHost = host; } + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); }); + return { + getSourceFile: function (fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, getCompilerOptions().charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + }, + getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); }, + fileExists: function (f) { return host.fileExists(f); }, + readFile: function (f) { return host.readFile(f); }, + trace: ts.maybeBind(host, host.trace), + directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: ts.maybeBind(host, host.realpath), + getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }), + createHash: ts.maybeBind(host, host.createHash), + readDirectory: ts.maybeBind(host, host.readDirectory), + }; + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + if (host.createDirectory) + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ - function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { - if (system === void 0) { system = ts.sys; } - if (!createProgram) { - createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; - } + function createProgramHost(system, createProgram) { + var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); }); var host = system; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) - var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; - var writeFileName = function (s) { return system.write(s + system.newLine); }; - var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getNewLine: function () { return system.newLine; }, - getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, fileExists: function (path) { return system.fileExists(path); }, @@ -90324,29 +91126,31 @@ var ts; directoryExists: function (path) { return system.directoryExists(path); }, getDirectories: function (path) { return system.getDirectories(path); }, readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, - realpath: system.realpath && (function (path) { return system.realpath(path); }), - getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: watchFile, - watchDirectory: watchDirectory, - setTimeout: setTimeout, - clearTimeout: clearTimeout, - trace: function (s) { return system.write(s); }, - onWatchStatusChange: onWatchStatusChange, + realpath: ts.maybeBind(system, system.realpath), + getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable), + trace: function (s) { return system.write(s + system.newLine); }, createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, - createHash: system.createHash && (function (s) { return system.createHash(s); }), - createProgram: createProgram, - afterProgramCreate: emitFilesAndReportErrorUsingBuilder + createHash: ts.maybeBind(system, system.createHash), + createProgram: createProgram }; - function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); - } - function emitFilesAndReportErrorUsingBuilder(builderProgram) { + } + ts.createProgramHost = createProgramHost; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var writeFileName = function (s) { return system.write(s + system.newLine); }; + var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram); + ts.copyProperties(result, createWatchHost(system, reportWatchStatus)); + result.afterProgramCreate = function (builderProgram) { var compilerOptions = builderProgram.getCompilerOptions(); var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); - } + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); + }; + return result; } /** * Report error and exit @@ -90402,8 +91206,6 @@ var ts; var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); var currentDirectory = host.getCurrentDirectory(); - var getCurrentDirectory = function () { return currentDirectory; }; - var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; @@ -90415,15 +91217,7 @@ var ts; host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } var directoryStructureHost = cachedDirectoryStructureHost || host; - var parseConfigFileHost = { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, - fileExists: function (path) { return host.fileExists(path); }, - readFile: readFile, - getCurrentDirectory: getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, - trace: host.trace ? function (s) { return host.trace(s); } : undefined - }; + var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost); // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); if (configFileName && host.configFileParsingResult) { @@ -90437,52 +91231,40 @@ var ts; parseConfigFile(); newLine = updateNewLine(); } - var trace = host.trace && (function (s) { host.trace(s + newLine); }); - var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : - compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; - var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 - var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; + var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); } - var compilerHost = { - // Members for CompilerHost - getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, - getSourceFileByPath: getVersionedSourceFileByPath, - getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), - getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, - writeFile: writeFile, - getCurrentDirectory: getCurrentDirectory, - useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, - getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return newLine; }, - fileExists: fileExists, - readFile: readFile, - trace: trace, - directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), - getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), - realpath: host.realpath && (function (s) { return host.realpath(s); }), - getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), - onReleaseOldSourceFile: onReleaseOldSourceFile, - createHash: host.createHash && (function (data) { return host.createHash(data); }), - // Members for ResolutionCacheHost - toPath: toPath, - getCompilationSettings: function () { return compilerOptions; }, - watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, - watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, - getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, - onInvalidatedResolution: scheduleProgramUpdate, - onChangedAutomaticTypeDirectiveNames: function () { - hasChangedAutomaticTypeDirectiveNames = true; - scheduleProgramUpdate(); - }, - maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, - getCurrentProgram: getCurrentProgram, - writeLog: writeLog, - readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost); + // Members for CompilerHost + var getNewSourceFile = compilerHost.getSourceFile; + compilerHost.getSourceFile = function (fileName) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return getVersionedSourceFileByPath.apply(void 0, [fileName, toPath(fileName)].concat(args)); }; + compilerHost.getSourceFileByPath = getVersionedSourceFileByPath; + compilerHost.getNewLine = function () { return newLine; }; + compilerHost.fileExists = fileExists; + compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + // Members for ResolutionCacheHost + compilerHost.toPath = toPath; + compilerHost.getCompilationSettings = function () { return compilerOptions; }; + compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations" /* FailedLookupLocations */); }; + compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots" /* TypeRoots */); }; + compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; + compilerHost.onInvalidatedResolution = scheduleProgramUpdate; + compilerHost.onChangedAutomaticTypeDirectiveNames = function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }; + compilerHost.maxNumberOfFilesToIterateForInvalidation = host.maxNumberOfFilesToIterateForInvalidation; + compilerHost.getCurrentProgram = getCurrentProgram; + compilerHost.writeLog = writeLog; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -90535,11 +91317,9 @@ var ts; } function createNewProgram(program, hasInvalidatedResolution) { // Compile the program - if (watchLogLevel !== ts.WatchLogLevel.None) { - writeLog("CreatingProgramWith::"); - writeLog(" roots: " + JSON.stringify(rootFileNames)); - writeLog(" options: " + JSON.stringify(compilerOptions)); - } + writeLog("CreatingProgramWith::"); + writeLog(" roots: " + JSON.stringify(rootFileNames)); + writeLog(" options: " + JSON.stringify(compilerOptions)); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -90602,7 +91382,7 @@ var ts; } // Create new source file if requested or the versions dont match if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { - var sourceFile = getNewSourceFile(); + var sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { if (shouldCreateNewSourceFile) { hostSourceFile.version++; @@ -90612,7 +91392,7 @@ var ts; hostSourceFile.sourceFile = sourceFile; sourceFile.version = hostSourceFile.version.toString(); if (!hostSourceFile.fileWatcher) { - hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); } } else { @@ -90626,7 +91406,7 @@ var ts; else { if (sourceFile) { sourceFile.version = initialVersion.toString(); - var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); } else { @@ -90636,21 +91416,6 @@ var ts; return sourceFile; } return hostSourceFile.sourceFile; - function getNewSourceFile() { - var text; - try { - ts.performance.mark("beforeIORead"); - text = host.readFile(fileName, compilerOptions.charset); - ts.performance.mark("afterIORead"); - ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; - } } function nextSourceFileVersion(path) { var hostSourceFile = sourceFilesCache.get(path); @@ -90777,7 +91542,7 @@ var ts; } } function watchMissingFilePath(missingFilePath) { - return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file"); + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file" /* MissingFile */); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -90821,28 +91586,7 @@ var ts; // Schedule Update the program scheduleProgramUpdate(); } - }, flags, "Wild card directories"); - } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - host.createDirectory(directoryPath); - } - } - function writeFile(fileName, text, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } + }, flags, "Wild card directory" /* WildcardDirectory */); } } ts.createWatchProgram = createWatchProgram; @@ -91011,9 +91755,8 @@ var ts; }; } ts.createBuilderStatusReporter = createBuilderStatusReporter; - function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { - if (system === void 0) { system = ts.sys; } - var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) { + var host = ts.createProgramHost(system, createProgram); host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; @@ -91021,21 +91764,18 @@ var ts; host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); return host; } - function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { if (system === void 0) { system = ts.sys; } - var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus); host.reportErrorSummary = reportErrorSummary; return host; } ts.createSolutionBuilderHost = createSolutionBuilderHost; - function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { - var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus); var watchHost = ts.createWatchHost(system, reportWatchStatus); - host.onWatchStatusChange = watchHost.onWatchStatusChange; - host.watchFile = watchHost.watchFile; - host.watchDirectory = watchHost.watchDirectory; - host.setTimeout = watchHost.setTimeout; - host.clearTimeout = watchHost.clearTimeout; + ts.copyProperties(host, watchHost); return host; } ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; @@ -91050,7 +91790,7 @@ var ts; var hostWithWatch = host; var currentDirectory = host.getCurrentDirectory(); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host); // State of the solution var options = defaultOptions; var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); @@ -91062,7 +91802,14 @@ var ts; var missingRoots = ts.createMap(); var globalDependencyGraph; var writeFileName = function (s) { return host.trace && host.trace(s); }; + var readFileWithCache = function (f) { return host.readFile(f); }; + var projectCompilerOptions = baseCompilerOptions; + var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; }); + var originalGetSourceFile = compilerHost.getSourceFile; + var computeHash = host.createHash || ts.generateDjb2Hash; + updateGetSourceFile(); // Watch state + var builderPrograms = createFileMap(toPath); var diagnostics = createFileMap(toPath); var projectPendingBuild = createFileMap(toPath); var projectErrorsReported = createFileMap(toPath); @@ -91070,6 +91817,7 @@ var ts; var nextProjectToBuild = 0; var timerToBuildInvalidatedProject; var reportFileChangeDetected = false; + var _a = ts.createWatchFactory(host, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; // Watches for the solution var allWatchedWildcardDirectories = createFileMap(toPath); var allWatchedInputFiles = createFileMap(toPath); @@ -91110,6 +91858,30 @@ var ts; ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + builderPrograms.clear(); + updateGetSourceFile(); + } + function updateGetSourceFile() { + if (options.watch) { + if (compilerHost.getSourceFile === originalGetSourceFile) { + compilerHost.getSourceFile = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); + if (result && options.watch) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + } + else { + if (compilerHost.getSourceFile !== originalGetSourceFile) { + compilerHost.getSourceFile = originalGetSourceFile; + } + } } function isParsedCommandLine(entry) { return !!entry.options; @@ -91159,36 +91931,34 @@ var ts; } function watchConfigFile(resolved) { if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { - allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + allWatchedConfigFiles.setValue(resolved, watchFile(hostWithWatch, resolved, function () { invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); - })); + }, ts.PollingInterval.High, "Config file" /* ConfigFile */, resolved)); } } function watchWildCardDirectories(resolved, parsed) { if (!options.watch) return; ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { - return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + return watchDirectory(hostWithWatch, dir, function (fileOrDirectory) { var fileOrDirectoryPath = toPath(fileOrDirectory); if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { - // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory); return; } if (isOutputFile(fileOrDirectory, parsed)) { - // writeLog(`${fileOrDirectory} is output file`); + writeLog(fileOrDirectory + " is output file"); return; } invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); - }, !!(flags & 1 /* Recursive */)); + }, flags, "Wild card directory" /* WildcardDirectory */, resolved); }); } function watchInputFiles(resolved, parsed) { if (!options.watch) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { - createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); - }); }, + createNewValue: function (path, input) { return watchFilePath(hostWithWatch, input, function () { return invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, path, "Source file" /* SourceFile */, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -91508,18 +92278,39 @@ var ts; reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); return; } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes) { + // Fake that files have been built by updating output file stamps + updateOutputTimestamps(proj); + return; + } var buildResult = buildSingleProject(resolved); - var dependencyGraph = getGlobalDependencyGraph(); - var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (buildResult & BuildResultFlags.AnyErrors) + return; + var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue; + var referencingProjects = referencingProjectsMap.getValue(resolved); if (!referencingProjects) return; // Always use build order to queue projects - for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { - var project = _a[_i]; + for (var index = buildQueue.indexOf(resolved) + 1; index < buildQueue.length; index++) { + var project = buildQueue[index]; var prepend = referencingProjects.getValue(project); - // If the project is referenced with prepend, always build downstream projectm, - // otherwise queue it only if declaration output changed - if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + if (prepend !== undefined) { + // If the project is referenced with prepend, always build downstream projects, + // If declaration output is changed, build the project + // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps + var status_1 = projectStatus.getValue(project); + if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { + if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) { + projectStatus.setValue(project, { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: status_1.oldestOutputFileName, + newerProjectName: resolved + }); + } + } + else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) { + status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes; + } addProjToQueue(project); } } @@ -91590,98 +92381,118 @@ var ts; // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } - var programOptions = { - projectReferences: configFile.projectReferences, - host: host, - rootNames: configFile.fileNames, - options: configFile.options, - configFileParsingDiagnostics: configFile.errors - }; - if (host.beforeCreateProgram) { - host.beforeCreateProgram(options); - } - var program = ts.createProgram(programOptions); + // TODO: handle resolve module name to cache result in project reference redirect + projectCompilerOptions = configFile.options; + var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences); + projectCompilerOptions = baseCompilerOptions; // Don't emit anything in the presence of syntactic errors or options diagnostics - var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } - // Don't emit .d.ts if there are decl file errors - if (ts.getEmitDeclarations(program.getCompilerOptions())) { - var declDiagnostics = program.getDeclarationDiagnostics(); - if (declDiagnostics.length) { - return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); - } - } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } + // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly + program.backupState(); var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - var emitDiagnostics; - var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; - ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { + var declDiagnostics; + var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; + var outputFiles = []; + ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }); + // Don't emit .d.ts if there are decl file errors + if (declDiagnostics) { + program.restoreState(); + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); + } + // Actual Emit + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emittedOutputs = createFileMap(toPath); + outputFiles.forEach(function (_a) { + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName)) { + if (!anyDtsChanged && isDeclarationFile(name)) { // Check for unchanged .d.ts files - if (host.fileExists(fileName) && host.readFile(fileName) === content) { - priorChangeTime = host.getModifiedTime(fileName); + if (host.fileExists(name) && readFileWithCache(name) === text) { + priorChangeTime = host.getModifiedTime(name); } else { resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + emittedOutputs.setValue(name, true); + ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(name, priorChangeTime); } }); - if (emitDiagnostics) { + var emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); } + // Update time stamps for rest of the outputs + newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(configFile, newestDeclarationFileContentChangedTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); var status = { type: UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime, + oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile) }; diagnostics.removeKey(proj); projectStatus.setValue(proj, status); - if (host.afterProgramEmitAndDiagnostics) { - host.afterProgramEmitAndDiagnostics(program); - } + afterProgramCreate(proj, program); return resultFlags; function buildErrors(diagnostics, errorFlags, errorType) { resultFlags |= errorFlags; reportAndStoreErrors(proj, diagnostics); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); - if (host.afterProgramEmitAndDiagnostics) { - host.afterProgramEmitAndDiagnostics(program); - } + afterProgramCreate(proj, program); return resultFlags; } } + function afterProgramCreate(proj, program) { + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + if (options.watch) { + program.releaseProgram(); + builderPrograms.setValue(proj, program); + } + } function updateOutputTimestamps(proj) { if (options.dry) { return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (options.verbose) { - reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); - } - var now = new Date(); - var outputs = getAllProjectOutputs(proj); - var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { - var file = outputs_2[_i]; - if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); - } - host.setModifiedTime(file, now); - } + var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } + function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { + var outputs = getAllProjectOutputs(proj); + if (!skipOutputs || outputs.length !== skipOutputs.getSize()) { + if (options.verbose) { + reportStatus(verboseMessage, proj.options.configFilePath); + } + var now = host.now ? host.now() : new Date(); + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; + if (skipOutputs && skipOutputs.hasKey(file)) { + continue; + } + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + } + host.setModifiedTime(file, now); + if (proj.options.listEmittedFiles) { + writeFileName("TSFILE: " + file); + } + } + } + return priorNewestUpdateTime; + } function getFilesToClean() { // Get the same graph for cleaning we'd use for building var graph = getGlobalDependencyGraph(); @@ -91726,11 +92537,24 @@ var ts; if (options.watch) { reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); } + // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api + // Override readFile for json files and output .d.ts to cache the text + var savedReadFileWithCache = readFileWithCache; + var savedGetSourceFile = compilerHost.getSourceFile; + var _a = ts.changeCompilerHostLikeToUseCache(host, toPath, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return savedGetSourceFile.call.apply(savedGetSourceFile, [compilerHost].concat(args)); + }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, newReadFileWithCache = _a.readFileWithCache; + readFileWithCache = newReadFileWithCache; + compilerHost.getSourceFile = getSourceFileWithCache; var graph = getGlobalDependencyGraph(); reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; + for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) { + var next = _b[_i]; var proj = parseConfigFile(next); if (proj === undefined) { reportParseConfigFileDiagnostic(next); @@ -91772,6 +92596,13 @@ var ts; anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } reportErrorSummary(); + host.readFile = originalReadFile; + host.fileExists = originalFileExists; + host.directoryExists = originalDirectoryExists; + host.createDirectory = originalCreateDirectory; + host.writeFile = originalWriteFile; + compilerHost.getSourceFile = savedGetSourceFile; + readFileWithCache = savedReadFileWithCache; return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } function reportParseConfigFileDiagnostic(proj) { @@ -91794,7 +92625,7 @@ var ts; } } function relName(path) { - return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode @@ -91827,6 +92658,19 @@ var ts; } } ts.getAllProjectOutputs = getAllProjectOutputs; + function getFirstProjectOutput(project) { + if (project.options.outFile || project.options.out) { + return ts.first(getOutFileOutputs(project)); + } + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + var outputs = getOutputFileNames(inputFile, project); + if (outputs.length) { + return ts.first(outputs); + } + } + return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output"); + } function formatUpToDateStatus(configFileName, status, relName, formatMessage) { switch (status.type) { case UpToDateStatusType.OutOfDateWithSelf: @@ -91879,17 +92723,17 @@ var ts; } ts.inspectValue = inspectValue; function getRecurser() { - var seen = new Set(); + var seen = []; var nameStack = []; return function (obj, name, cbOk, cbFail) { - if (seen.has(obj) || nameStack.length > 4) { - return cbFail(seen.has(obj), nameStack); + if (seen.indexOf(obj) !== -1 || nameStack.length > 4) { + return cbFail(seen.indexOf(obj) !== -1, nameStack); } - seen.add(obj); + seen.push(obj); nameStack.push(name); var res = cbOk(); nameStack.pop(); - seen.delete(obj); + seen.pop(); return res; }; } @@ -91947,8 +92791,8 @@ var ts; return key === "constructor" ? undefined : getValueInfo(key, value, recurser); }); } - var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); - var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + var ignoredProperties = ["arguments", "caller", "constructor", "eval", "super_"]; + var reservedFunctionProperties = Object.getOwnPropertyNames(ts.noop); function getEntriesOfObject(obj) { var seen = ts.createMap(); var entries = []; @@ -91957,8 +92801,8 @@ var ts; for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { var key = _a[_i]; if (!isJsPrivate(key) && - !ignoredProperties.has(key) && - (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + ignoredProperties.indexOf(key) === -1 && + (typeof obj !== "function" || reservedFunctionProperties.indexOf(key) === -1) && // Don't add property from a higher prototype if it already exists in a lower one ts.addToSeen(seen, key)) { var value = safeGetPropertyOfObject(chain, key); @@ -91986,7 +92830,7 @@ var ts; return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; } function isJsPrivate(name) { - return name.startsWith("_"); + return ts.startsWith(name, "_"); } ts.isJsPrivate = isJsPrivate; function tryRequire(fileNameToRequire) { @@ -92247,8 +93091,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_6.config; + var result_7 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_7.config; // npm 3's package.json contains a "_requiredBy" field // we should include all the top level module names for npm 2, and only module names whose // "_requiredBy" field starts with "#" or equals "/" for npm 3. @@ -95680,7 +96524,7 @@ var ts; continue; var patterns = paths[path]; if (patterns) { - var _loop_10 = function (name, kind, extension) { + var _loop_11 = function (name, kind, extension) { // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. if (!result.some(function (entry) { return entry.name === name; })) { result.push(nameAndKind(name, kind, extension)); @@ -95688,7 +96532,7 @@ var ts; }; for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseDirectory, fileExtensions, host); _i < _a.length; _i++) { var _b = _a[_i], name = _b.name, kind = _b.kind, extension = _b.extension; - _loop_10(name, kind, extension); + _loop_11(name, kind, extension); } } } @@ -95723,7 +96567,7 @@ var ts; // (But do if we didn't find anything, e.g. 'package.json' missing.) var foundGlobal = false; if (fragmentDirectory === undefined) { - var _loop_11 = function (moduleName) { + var _loop_12 = function (moduleName) { if (!result.some(function (entry) { return entry.name === moduleName; })) { foundGlobal = true; result.push(nameAndKind(moduleName, "external module name" /* externalModuleName */, /*extension*/ undefined)); @@ -95731,7 +96575,7 @@ var ts; }; for (var _b = 0, _c = enumerateNodeModulesVisibleToScript(host, scriptPath); _b < _c.length; _b++) { var moduleName = _c[_b]; - _loop_11(moduleName); + _loop_12(moduleName); } } if (!foundGlobal) { @@ -96085,7 +96929,7 @@ var ts; getJSCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); // TODO: GH#18217 } else { - if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { + if (!isNewIdentifierLocation && (!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, preferences, propertyAccessToConvert, isJsxInitializer, recommendedCompletion, symbolToOriginInfoMap); @@ -96285,7 +97129,8 @@ var ts; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && originIsExport(origin) && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + return origin && originIsExport(origin) && ((origin.isDefaultExport && symbol.escapedName === "default" /* Default */) || + (symbol.escapedName === "export=" /* ExportEquals */)) // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) @@ -96855,14 +97700,11 @@ var ts; // If already using commonjs, don't introduce ES6. if (sourceFile.commonJsModuleIndicator) return false; - // For JS, stay on the safe side. - if (isUncheckedFile) - return false; - // If some file is using ES6 modules, assume that it's OK to add more. - if (ts.programContainsEs6Modules(program)) - return true; // If module transpilation is enabled or we're targeting es6 or above, or not emitting, OK. - return ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions()); + if (ts.compilerOptionsIndicateEs6Modules(program.getCompilerOptions())) + return true; + // If some file is using ES6 modules, assume that it's OK to add more. + return ts.programContainsEs6Modules(program); } function isSnippetScope(scopeNode) { switch (scopeNode.kind) { @@ -97661,7 +98503,7 @@ var ts; } } function isFunctionLikeBodyKeyword(kind) { - return kind === 121 /* AsyncKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); + return kind === 121 /* AsyncKeyword */ || kind === 122 /* AwaitKeyword */ || !ts.isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind); } function keywordForNode(node) { return ts.isIdentifier(node) ? node.originalKeywordKind || 0 /* Unknown */ : node.kind; @@ -98949,9 +99791,9 @@ var ts; // If invoked directly on a shorthand property assignment, then return // the declaration of the symbol being assigned (not the symbol being assigned to). if (node.parent.kind === 276 /* ShorthandPropertyAssignment */) { - var result_7 = []; - FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_7.push(nodeEntry(node)); }); - return result_7; + var result_8 = []; + FindAllReferences.Core.getReferenceEntriesForShorthandPropertyAssignment(node, checker, function (node) { return result_8.push(nodeEntry(node)); }); + return result_8; } else if (node.kind === 98 /* SuperKeyword */ || ts.isSuperProperty(node.parent)) { // References to and accesses on the super keyword only have one possible implementation, so no @@ -98983,8 +99825,8 @@ var ts; case 0 /* Symbol */: { var symbol = def.symbol; var _a = getDefinitionKindAndDisplayParts(symbol, checker, originalNode), displayParts_1 = _a.displayParts, kind_1 = _a.kind; - var name_3 = displayParts_1.map(function (p) { return p.text; }).join(""); - return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_3, kind: kind_1, displayParts: displayParts_1 }; + var name_4 = displayParts_1.map(function (p) { return p.text; }).join(""); + return { node: symbol.declarations ? ts.getNameOfDeclaration(ts.first(symbol.declarations)) || ts.first(symbol.declarations) : originalNode, name: name_4, kind: kind_1, displayParts: displayParts_1 }; } case 1 /* Label */: { var node_3 = def.node; @@ -98992,8 +99834,8 @@ var ts; } case 2 /* Keyword */: { var node_4 = def.node; - var name_4 = ts.tokenToString(node_4.kind); - return { node: node_4, name: name_4, kind: "keyword" /* keyword */, displayParts: [{ text: name_4, kind: "keyword" /* keyword */ }] }; + var name_5 = ts.tokenToString(node_4.kind); + return { node: node_4, name: name_5, kind: "keyword" /* keyword */, displayParts: [{ text: name_5, kind: "keyword" /* keyword */ }] }; } case 3 /* This */: { var node_5 = def.node; @@ -99019,8 +99861,8 @@ var ts; var _a = ts.SymbolDisplay.getSymbolDisplayPartsDocumentationAndSymbolKind(checker, symbol, enclosingDeclaration.getSourceFile(), enclosingDeclaration, enclosingDeclaration, meaning), displayParts = _a.displayParts, symbolKind = _a.symbolKind; return { displayParts: displayParts, kind: symbolKind }; } - function toRenameLocation(entry, originalNode, checker) { - return __assign({}, entryToDocumentSpan(entry), getPrefixAndSuffixText(entry, originalNode, checker)); + function toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixText) { + return __assign({}, entryToDocumentSpan(entry), (providePrefixAndSuffixText && getPrefixAndSuffixText(entry, originalNode, checker))); } FindAllReferences.toRenameLocation = toRenameLocation; function toReferenceEntry(entry) { @@ -99325,12 +100167,12 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(originalSymbol, node, sourceFiles, sourceFilesSet, checker, cancellationToken, options) { - var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, !!options.isForRename) || originalSymbol; + var symbol = node && skipPastExportOrImportSpecifierOrUnion(originalSymbol, node, checker, /*useLocalSymbolForExportSpecifier*/ !isForRenameWithPrefixAndSuffixText(options)) || originalSymbol; // Compute the meaning from the location and the symbol it references var searchMeaning = node ? getIntersectingMeaningFromDeclarations(node, symbol) : 7 /* All */; var result = []; var state = new State(sourceFiles, sourceFilesSet, node ? getSpecialSearchKind(node) : 0 /* None */, checker, cancellationToken, searchMeaning, options, result); - var exportSpecifier = !options.isForRename ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); + var exportSpecifier = !isForRenameWithPrefixAndSuffixText(options) ? undefined : ts.find(symbol.declarations, ts.isExportSpecifier); if (exportSpecifier) { // When renaming at an export specifier, rename the export and not the thing being exported. getReferencesAtExportSpecifier(exportSpecifier.name, symbol, exportSpecifier, state.createSearch(node, originalSymbol, /*comingFrom*/ undefined), state, /*addReferencesHere*/ true, /*alwaysGetReferences*/ true); @@ -99340,7 +100182,7 @@ var ts; searchForImportsOfExport(node, symbol, { exportingModuleSymbol: ts.Debug.assertDefined(symbol.parent, "Expected export symbol to have a parent"), exportKind: 1 /* Default */ }, state); } else { - var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.implementations) : [symbol] }); + var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); // Try to get the smallest valid scope that we can limit our search to; // otherwise we'll need to search globally (i.e. include each file). var scope = getSymbolScope(symbol); @@ -99373,9 +100215,9 @@ var ts; } } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, isForRename) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker, useLocalSymbolForExportSpecifier) { var parent = node.parent; - if (ts.isExportSpecifier(parent) && !isForRename) { + if (ts.isExportSpecifier(parent) && useLocalSymbolForExportSpecifier) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); } // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. @@ -99837,6 +100679,7 @@ var ts; getImportOrExportReferences(referenceLocation, referenceSymbol, search, state); } function getReferencesAtExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, search, state, addReferencesHere, alwaysGetReferences) { + ts.Debug.assert(!alwaysGetReferences || !!state.options.providePrefixAndSuffixTextForRename, "If alwaysGetReferences is true, then prefix/suffix text must be enabled"); var parent = exportSpecifier.parent, propertyName = exportSpecifier.propertyName, name = exportSpecifier.name; var exportDeclaration = parent.parent; var localSymbol = getLocalSymbolForExportSpecifier(referenceLocation, referenceSymbol, exportSpecifier, state.checker); @@ -99865,14 +100708,14 @@ var ts; } } // For `export { foo as bar }`, rename `foo`, but not `bar`. - if (!state.options.isForRename || alwaysGetReferences) { + if (!isForRenameWithPrefixAndSuffixText(state.options) || alwaysGetReferences) { var exportKind = referenceLocation.originalKeywordKind === 80 /* DefaultKeyword */ ? 1 /* Default */ : 0 /* Named */; var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. - if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !state.options.isForRename) { + if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { var imported = state.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); if (imported) searchForImportedSymbol(imported, state); @@ -99904,7 +100747,7 @@ var ts; return; var symbol = importOrExport.symbol; if (importOrExport.kind === 0 /* Import */) { - if (!state.options.isForRename) { + if (!(isForRenameWithPrefixAndSuffixText(state.options))) { searchForImportedSymbol(symbol, state); } } @@ -100166,6 +101009,9 @@ var ts; }); return [{ definition: { type: 0 /* Symbol */, symbol: searchSpaceNode.symbol }, references: references }]; } + function isParameterName(node) { + return node.kind === 72 /* Identifier */ && node.parent.kind === 151 /* Parameter */ && node.parent.name === node; + } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles, cancellationToken) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. @@ -100186,7 +101032,7 @@ var ts; searchSpaceNode = searchSpaceNode.parent; // re-assign to be the owning class break; case 279 /* SourceFile */: - if (ts.isExternalModule(searchSpaceNode)) { + if (ts.isExternalModule(searchSpaceNode) || isParameterName(thisOrSuperKeyword)) { return undefined; } // falls through @@ -100218,7 +101064,7 @@ var ts; // and has the appropriate static modifier from the original container. return container.parent && searchSpaceNode.symbol === container.parent.symbol && (ts.getModifierFlags(container) & 32 /* Static */) === staticFlag; case 279 /* SourceFile */: - return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container); + return container.kind === 279 /* SourceFile */ && !ts.isExternalModule(container) && !isParameterName(node); } }); }).map(function (n) { return FindAllReferences.nodeEntry(n); }); @@ -100242,13 +101088,13 @@ var ts; } // For certain symbol kinds, we need to include other symbols in the search set. // This is not needed when searching for re-exports. - function populateSearchSymbolSet(symbol, location, checker, isForRename, implementations) { + function populateSearchSymbolSet(symbol, location, checker, isForRename, providePrefixAndSuffixText, implementations) { var result = []; - forEachRelatedSymbol(symbol, location, checker, isForRename, function (sym, root, base) { result.push(base || root || sym); }, + forEachRelatedSymbol(symbol, location, checker, isForRename, !(isForRename && providePrefixAndSuffixText), function (sym, root, base) { result.push(base || root || sym); }, /*allowBaseTypes*/ function () { return !implementations; }); return result; } - function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, cbSymbol, allowBaseTypes) { + function forEachRelatedSymbol(symbol, location, checker, isForRenamePopulateSearchSymbolSet, onlyIncludeBindingElementAtReferenceLocation, cbSymbol, allowBaseTypes) { var containingObjectLiteralElement = ts.getContainingObjectLiteralElement(location); if (containingObjectLiteralElement) { /* Because in short-hand property assignment, location has two meaning : property name and as value of the property @@ -100295,9 +101141,23 @@ var ts; return fromRoot(symbol.flags & 1 /* FunctionScopedVariable */ ? paramProps[1] : paramProps[0]); } // symbolAtLocation for a binding element is the local symbol. See if the search symbol is the property. - // Don't do this when populating search set for a rename -- just rename the local. + // Don't do this when populating search set for a rename when prefix and suffix text will be provided -- just rename the local. if (!isForRenamePopulateSearchSymbolSet) { - var bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + var bindingElementPropertySymbol = void 0; + if (onlyIncludeBindingElementAtReferenceLocation) { + bindingElementPropertySymbol = ts.isObjectBindingElementWithoutPropertyName(location.parent) ? ts.getPropertySymbolFromBindingElement(checker, location.parent) : undefined; + } + else { + bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); + } + return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); + } + ts.Debug.assert(isForRenamePopulateSearchSymbolSet); + // due to the above assert and the arguments at the uses of this function, + // (onlyIncludeBindingElementAtReferenceLocation <=> !providePrefixAndSuffixTextForRename) holds + var includeOriginalSymbolOfBindingElement = onlyIncludeBindingElementAtReferenceLocation; + if (includeOriginalSymbolOfBindingElement) { + var bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker); return bindingElementPropertySymbol && fromRoot(bindingElementPropertySymbol, 4 /* SearchedPropertyFoundLocal */); } function fromRoot(sym, kind) { @@ -100315,10 +101175,17 @@ var ts; : undefined); }); } + function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol, checker) { + var bindingElement = ts.getDeclarationOfKind(symbol, 186 /* BindingElement */); + if (bindingElement && ts.isObjectBindingElementWithoutPropertyName(bindingElement)) { + return ts.getPropertySymbolFromBindingElement(checker, bindingElement); + } + } } function getRelatedSymbol(search, referenceSymbol, referenceLocation, state) { var checker = state.checker; - return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) + return forEachRelatedSymbol(referenceSymbol, referenceLocation, checker, /*isForRenamePopulateSearchSymbolSet*/ false, + /*onlyIncludeBindingElementAtReferenceLocation*/ !state.options.isForRename || !!state.options.providePrefixAndSuffixTextForRename, function (sym, rootSymbol, baseSymbol, kind) { return search.includes(baseSymbol || rootSymbol || sym) // For a base type, use the symbol for the derived type. For a synthetic (e.g. union) property, use the union symbol. ? { symbol: rootSymbol && !(ts.getCheckFlags(sym) & 6 /* Synthetic */) ? rootSymbol : sym, kind: kind } : undefined; }, @@ -100403,6 +101270,9 @@ var ts; }); return res.length === 0 ? undefined : res; } + function isForRenameWithPrefixAndSuffixText(options) { + return options.isForRename && options.providePrefixAndSuffixTextForRename; + } })(Core = FindAllReferences.Core || (FindAllReferences.Core = {})); })(FindAllReferences = ts.FindAllReferences || (ts.FindAllReferences = {})); })(ts || (ts = {})); @@ -100515,7 +101385,7 @@ var ts; } function updateImports(program, changeTracker, oldToNew, newToOld, host, getCanonicalFileName) { var allFiles = program.getSourceFiles(); - var _loop_12 = function (sourceFile) { + var _loop_13 = function (sourceFile) { var newFromOld = oldToNew(sourceFile.path); var newImportFromPath = newFromOld !== undefined ? newFromOld : sourceFile.path; var newImportFromDirectory = ts.getDirectoryPath(newImportFromPath); @@ -100537,7 +101407,7 @@ var ts; var toImport = oldFromNew !== undefined // If we're at the new location (file was already renamed), need to redo module resolution starting from the old location. // TODO:GH#18217 - ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew, host) + ? getSourceFileToImportFromResolved(ts.resolveModuleName(importLiteral.text, oldImportFromPath, program.getCompilerOptions(), host), oldToNew) : getSourceFileToImport(importedModuleSymbol, importLiteral, sourceFile, program, host, oldToNew); // Need an update if the imported file moved, or the importing file moved and was using a relative path. return toImport !== undefined && (toImport.updated || (importingSourceFileMoved && ts.pathIsRelative(importLiteral.text))) @@ -100547,7 +101417,7 @@ var ts; }; for (var _i = 0, allFiles_1 = allFiles; _i < allFiles_1.length; _i++) { var sourceFile = allFiles_1[_i]; - _loop_12(sourceFile); + _loop_13(sourceFile); } } function combineNormal(pathA, pathB) { @@ -100567,23 +101437,32 @@ var ts; var resolved = host.resolveModuleNames ? host.getResolvedModuleWithFailedLookupLocationsFromCache && host.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName) : program.getResolvedModuleWithFailedLookupLocationsFromCache(importLiteral.text, importingSourceFile.fileName); - return getSourceFileToImportFromResolved(resolved, oldToNew, host); + return getSourceFileToImportFromResolved(resolved, oldToNew); } } - function getSourceFileToImportFromResolved(resolved, oldToNew, host) { + function getSourceFileToImportFromResolved(resolved, oldToNew) { // Search through all locations looking for a moved file, and only then test already existing files. // This is because if `a.ts` is compiled to `a.js` and `a.ts` is moved, we don't want to resolve anything to `a.js`, but to `a.ts`'s new location. - return tryEach(tryGetNewFile) || tryEach(tryGetOldFile); - function tryEach(cb) { - return resolved && ((resolved.resolvedModule && cb(resolved.resolvedModule.resolvedFileName)) || ts.firstDefined(resolved.failedLookupLocations, cb)); + if (!resolved) + return undefined; + // First try resolved module + if (resolved.resolvedModule) { + var result_9 = tryChange(resolved.resolvedModule.resolvedFileName); + if (result_9) + return result_9; } - function tryGetNewFile(oldFileName) { - var newFileName = oldToNew(oldFileName); - return newFileName !== undefined && host.fileExists(newFileName) ? { newFileName: newFileName, updated: true } : undefined; // TODO: GH#18217 + // Then failed lookups except package.json since we dont want to touch them (only included ts/js files) + var result = ts.forEach(resolved.failedLookupLocations, tryChangeWithIgnoringPackageJson); + if (result) + return result; + // If nothing changed, then result is resolved module file thats not updated + return resolved.resolvedModule && { newFileName: resolved.resolvedModule.resolvedFileName, updated: false }; + function tryChangeWithIgnoringPackageJson(oldFileName) { + return !ts.endsWith(oldFileName, "/package.json") ? tryChange(oldFileName) : undefined; } - function tryGetOldFile(oldFileName) { + function tryChange(oldFileName) { var newFileName = oldToNew(oldFileName); - return host.fileExists(oldFileName) ? newFileName !== undefined ? { newFileName: newFileName, updated: true } : { newFileName: oldFileName, updated: false } : undefined; // TODO: GH#18217 + return newFileName && { newFileName: newFileName, updated: true }; } } function updateImportsWorker(sourceFile, changeTracker, updateRef, updateImport) { @@ -100680,10 +101559,10 @@ var ts; // bar(({pr/*goto*/op1})=>{}); if (ts.isPropertyName(node) && ts.isBindingElement(parent) && ts.isObjectBindingPattern(parent.parent) && (node === (parent.propertyName || parent.name))) { - var name_5 = ts.getNameFromPropertyName(node); + var name_6 = ts.getNameFromPropertyName(node); var type = typeChecker.getTypeAtLocation(parent.parent); - return name_5 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { - var prop = t.getProperty(name_5); + return name_6 === undefined ? ts.emptyArray : ts.flatMap(type.isUnion() ? type.types : [type], function (t) { + var prop = t.getProperty(name_6); return prop && getDefinitionFromSymbol(typeChecker, prop, node); }); } @@ -101328,7 +102207,7 @@ var ts; if (!patternMatcher) return ts.emptyArray; var rawItems = []; - var _loop_13 = function (sourceFile) { + var _loop_14 = function (sourceFile) { cancellationToken.throwIfCancellationRequested(); if (excludeDtsFiles && sourceFile.isDeclarationFile) { return "continue"; @@ -101340,7 +102219,7 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { var sourceFile = sourceFiles_6[_i]; - _loop_13(sourceFile); + _loop_14(sourceFile); } rawItems.sort(compareNavigateToItems); return (maxResultCount === undefined ? rawItems : rawItems.slice(0, maxResultCount)).map(createNavigateToItem); @@ -102032,7 +102911,7 @@ var ts; else if (ts.isCallExpression(parent)) { var name = getCalledExpressionName(parent.expression); if (name !== undefined) { - var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteral(a) ? a.getText(curSourceFile) : undefined; }).join(", "); + var args = ts.mapDefined(parent.arguments, function (a) { return ts.isStringLiteralLike(a) ? a.getText(curSourceFile) : undefined; }).join(", "); return name + "(" + args + ") callback"; } } @@ -102085,10 +102964,12 @@ var ts; organizeImportsWorker(topLevelExportDecls, coalesceExports); for (var _i = 0, _a = sourceFile.statements.filter(ts.isAmbientModule); _i < _a.length; _i++) { var ambientModule = _a[_i]; - var ambientModuleBody = getModuleBlock(ambientModule); // TODO: GH#18217 - var ambientModuleImportDecls = ambientModuleBody.statements.filter(ts.isImportDeclaration); + if (!ambientModule.body) { + continue; + } + var ambientModuleImportDecls = ambientModule.body.statements.filter(ts.isImportDeclaration); organizeImportsWorker(ambientModuleImportDecls, coalesceAndOrganizeImports); - var ambientModuleExportDecls = ambientModuleBody.statements.filter(ts.isExportDeclaration); + var ambientModuleExportDecls = ambientModule.body.statements.filter(ts.isExportDeclaration); organizeImportsWorker(ambientModuleExportDecls, coalesceExports); } return changeTracker.getChanges(); @@ -102128,13 +103009,9 @@ var ts; } } OrganizeImports.organizeImports = organizeImports; - function getModuleBlock(moduleDecl) { - var body = moduleDecl.body; - return body && !ts.isIdentifier(body) ? (ts.isModuleBlock(body) ? body : getModuleBlock(body)) : undefined; - } function removeUnusedImports(oldImports, sourceFile, program) { var typeChecker = program.getTypeChecker(); - var jsxNamespace = typeChecker.getJsxNamespace(); + var jsxNamespace = typeChecker.getJsxNamespace(sourceFile); var jsxElementsPresent = !!(sourceFile.transformFlags & 4 /* ContainsJsx */); var usedImports = []; for (var _i = 0, oldImports_1 = oldImports; _i < oldImports_1.length; _i++) { @@ -102394,6 +103271,9 @@ var ts; if (ts.isDeclaration(n)) { addOutliningForLeadingCommentsForNode(n, sourceFile, cancellationToken, out); } + if (isFunctionExpressionAssignedToVariable(n)) { + addOutliningForLeadingCommentsForNode(n.parent.parent.parent, sourceFile, cancellationToken, out); + } var span = getOutliningSpanForNode(n, sourceFile); if (span) out.push(span); @@ -102411,6 +103291,13 @@ var ts; } depthRemaining++; } + function isFunctionExpressionAssignedToVariable(n) { + if (!ts.isFunctionExpression(n) && !ts.isArrowFunction(n)) { + return false; + } + var ancestor = ts.findAncestor(n, ts.isVariableStatement); + return !!ancestor && ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration(ancestor) === n; + } } function addRegionOutliningSpans(sourceFile, out) { var regions = []; @@ -102526,6 +103413,7 @@ var ts; case 245 /* ModuleBlock */: return spanForNode(n.parent); case 240 /* ClassDeclaration */: + case 209 /* ClassExpression */: case 241 /* InterfaceDeclaration */: case 243 /* EnumDeclaration */: case 246 /* CaseBlock */: @@ -102554,10 +103442,10 @@ var ts; } function spanForObjectOrArrayLiteral(node, open) { if (open === void 0) { open = 18 /* OpenBraceToken */; } - // If the block has no leading keywords and is inside an array literal, + // If the block has no leading keywords and is inside an array literal or call expression, // we only want to collapse the span of the block. // Otherwise, the collapsed section will include the end of the previous line. - return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent), open); + return spanForNode(node, /*autoCollapse*/ false, /*useFullStart*/ !ts.isArrayLiteralExpression(node.parent) && !ts.isCallExpression(node.parent), open); } function spanForNode(hintSpanNode, autoCollapse, useFullStart, open) { if (autoCollapse === void 0) { autoCollapse = false; } @@ -102859,15 +103747,15 @@ var ts; // Assumes 'value' is already lowercase. function indexOfIgnoringCase(str, value) { var n = str.length - value.length; - var _loop_14 = function (start) { + var _loop_15 = function (start) { if (every(value, function (valueChar, i) { return toLowerCase(str.charCodeAt(i + start)) === valueChar; })) { return { value: start }; } }; for (var start = 0; start <= n; start++) { - var state_3 = _loop_14(start); - if (typeof state_3 === "object") - return state_3.value; + var state_4 = _loop_15(start); + if (typeof state_4 === "object") + return state_4.value; } return -1; } @@ -103381,15 +104269,15 @@ var ts; (function (ts) { var Rename; (function (Rename) { - function getRenameInfo(program, sourceFile, position) { + function getRenameInfo(program, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position); var renameInfo = node && nodeIsEligibleForRename(node) - ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }) + ? getRenameInfoForNode(node, program.getTypeChecker(), sourceFile, function (declaration) { return program.isSourceFileDefaultLibrary(declaration.getSourceFile()); }, options) : undefined; return renameInfo || getRenameInfoError(ts.Diagnostics.You_cannot_rename_this_element); } Rename.getRenameInfo = getRenameInfo; - function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) { + function getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile, options) { var symbol = typeChecker.getSymbolAtLocation(node); if (!symbol) return; @@ -103406,7 +104294,7 @@ var ts; return undefined; } if (ts.isStringLiteralLike(node) && ts.tryGetImportFromModuleSpecifier(node)) { - return getRenameInfoForModule(node, sourceFile, symbol); + return options && options.allowRenameOfImportPath ? getRenameInfoForModule(node, sourceFile, symbol) : undefined; } var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteralLike(node) && node.parent.kind === 149 /* ComputedPropertyName */) @@ -103423,7 +104311,7 @@ var ts; var moduleSourceFile = ts.find(moduleSymbol.declarations, ts.isSourceFile); if (!moduleSourceFile) return undefined; - var withoutIndex = node.text.endsWith("/index") || node.text.endsWith("/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); + var withoutIndex = ts.endsWith(node.text, "/index") || ts.endsWith(node.text, "/index.js") ? undefined : ts.tryRemoveSuffix(ts.removeFileExtension(moduleSourceFile.fileName), "/index"); var name = withoutIndex === undefined ? moduleSourceFile.fileName : withoutIndex; var kind = withoutIndex === undefined ? "module" /* moduleElement */ : "directory" /* directory */; var indexAfterLastSlash = node.text.lastIndexOf("/") + 1; @@ -103878,7 +104766,7 @@ var ts; return ts.createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart); } function getContainingArgumentInfo(node, position, sourceFile, checker, isManuallyInvoked) { - var _loop_15 = function (n) { + var _loop_16 = function (n) { // If the node is not a subspan of its parent, this is a big problem. // There have been crashes that might be caused by this violation. ts.Debug.assert(ts.rangeContainsRange(n.parent, n), "Not a subspan", function () { return "Child: " + ts.Debug.showSyntaxKind(n) + ", parent: " + ts.Debug.showSyntaxKind(n.parent); }); @@ -103888,9 +104776,9 @@ var ts; } }; for (var n = node; isManuallyInvoked || (!ts.isBlock(n) && !ts.isSourceFile(n)); n = n.parent) { - var state_4 = _loop_15(n); - if (typeof state_4 === "object") - return state_4.value; + var state_5 = _loop_16(n); + if (typeof state_5 === "object") + return state_5.value; } return undefined; } @@ -104003,86 +104891,47 @@ var ts; var ts; (function (ts) { var base64UrlRegExp = /^data:(?:application\/json(?:;charset=[uU][tT][fF]-8);base64,([A-Za-z0-9+\/=]+)$)?/; - function getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, getProgram) { - var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var sourcemappedFileCache; + function getSourceMapper(host) { + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var currentDirectory = host.getCurrentDirectory(); + var sourceFileLike = ts.createMap(); + var documentPositionMappers = ts.createMap(); return { tryGetSourcePosition: tryGetSourcePosition, tryGetGeneratedPosition: tryGetGeneratedPosition, toLineColumnOffset: toLineColumnOffset, clearCache: clearCache }; function toPath(fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } - function scanForSourcemapURL(fileName) { - var mappedFile = sourcemappedFileCache.get(toPath(fileName)); - if (!mappedFile) { - return; + function getDocumentPositionMapper(generatedFileName, sourceFileName) { + var path = toPath(generatedFileName); + var value = documentPositionMappers.get(path); + if (value) + return value; + var mapper; + if (host.getDocumentPositionMapper) { + mapper = host.getDocumentPositionMapper(generatedFileName, sourceFileName); } - return ts.tryGetSourceMappingURL(mappedFile.text, ts.getLineStarts(mappedFile)); - } - function convertDocumentToSourceMapper(file, contents, mapFileName) { - var map = ts.tryParseRawSourceMap(contents); - if (!map || !map.sources || !map.file || !map.mappings) { - // obviously invalid map - return file.sourceMapper = ts.identitySourceMapConsumer; + else if (host.readFile) { + var file = getSourceFileLike(generatedFileName); + mapper = file && ts.getDocumentPositionMapper({ getSourceFileLike: getSourceFileLike, getCanonicalFileName: getCanonicalFileName, log: function (s) { return host.log(s); } }, generatedFileName, ts.getLineInfo(file.text, ts.getLineStarts(file)), function (f) { return !host.fileExists || host.fileExists(f) ? host.readFile(f) : undefined; }); } - var program = getProgram(); - return file.sourceMapper = ts.createDocumentPositionMapper({ - getSourceFileLike: function (s) { - // Lookup file in program, if provided - var file = program && program.getSourceFileByPath(s); - // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file - if (file === undefined || file.resolvedPath !== s) { - // Otherwise check the cache (which may hit disk) - return sourcemappedFileCache.get(s); - } - return file; - }, - getCanonicalFileName: getCanonicalFileName, - log: log, - }, map, mapFileName); - } - function getSourceMapper(fileName, file) { - if (!host.readFile || !host.fileExists) { - return file.sourceMapper = ts.identitySourceMapConsumer; - } - if (file.sourceMapper) { - return file.sourceMapper; - } - var mapFileName = scanForSourcemapURL(fileName); - if (mapFileName) { - var match = base64UrlRegExp.exec(mapFileName); - if (match) { - if (match[1]) { - var base64Object = match[1]; - return convertDocumentToSourceMapper(file, ts.base64decode(ts.sys, base64Object), fileName); - } - // Not a data URL we can parse, skip it - mapFileName = undefined; - } - } - var possibleMapLocations = []; - if (mapFileName) { - possibleMapLocations.push(mapFileName); - } - possibleMapLocations.push(fileName + ".map"); - for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { - var location = possibleMapLocations_1[_i]; - var mapPath = ts.toPath(location, ts.getDirectoryPath(fileName), getCanonicalFileName); - if (host.fileExists(mapPath)) { - return convertDocumentToSourceMapper(file, host.readFile(mapPath), mapPath); // TODO: GH#18217 - } - } - return file.sourceMapper = ts.identitySourceMapConsumer; + documentPositionMappers.set(path, mapper || ts.identitySourceMapConsumer); + return mapper || ts.identitySourceMapConsumer; } function tryGetSourcePosition(info) { if (!ts.isDeclarationFileName(info.fileName)) return undefined; - var file = getFile(info.fileName); + var file = getSourceFile(info.fileName); if (!file) return undefined; - var newLoc = getSourceMapper(info.fileName, file).getSourcePosition(info); - return newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; + var newLoc = getDocumentPositionMapper(info.fileName).getSourcePosition(info); + return !newLoc || newLoc === info ? undefined : tryGetSourcePosition(newLoc) || newLoc; } function tryGetGeneratedPosition(info) { - var program = getProgram(); + if (ts.isDeclarationFileName(info.fileName)) + return undefined; + var sourceFile = getSourceFile(info.fileName); + if (!sourceFile) + return undefined; + var program = host.getProgram(); var options = program.getCompilerOptions(); var outPath = options.outFile || options.out; var declarationPath = outPath ? @@ -104090,49 +104939,96 @@ var ts; ts.getDeclarationEmitOutputFilePathWorker(info.fileName, program.getCompilerOptions(), currentDirectory, program.getCommonSourceDirectory(), getCanonicalFileName); if (declarationPath === undefined) return undefined; - var declarationFile = getFile(declarationPath); - if (!declarationFile) - return undefined; - var newLoc = getSourceMapper(declarationPath, declarationFile).getGeneratedPosition(info); + var newLoc = getDocumentPositionMapper(declarationPath, info.fileName).getGeneratedPosition(info); return newLoc === info ? undefined : newLoc; } - function getFile(fileName) { + function getSourceFile(fileName) { + var program = host.getProgram(); + if (!program) + return undefined; var path = toPath(fileName); - var file = getProgram().getSourceFileByPath(path); - if (file && file.resolvedPath === path) { - return file; + // file returned here could be .d.ts when asked for .ts file if projectReferences and module resolution created this source file + var file = program.getSourceFileByPath(path); + return file && file.resolvedPath === path ? file : undefined; + } + function getOrCreateSourceFileLike(fileName) { + var path = toPath(fileName); + var fileFromCache = sourceFileLike.get(path); + if (fileFromCache !== undefined) + return fileFromCache ? fileFromCache : undefined; + if (!host.readFile || host.fileExists && !host.fileExists(path)) { + sourceFileLike.set(path, false); + return undefined; } - return sourcemappedFileCache.get(path); + // And failing that, check the disk + var text = host.readFile(path); + var file = text ? createSourceFileLike(text) : false; + sourceFileLike.set(path, file); + return file ? file : undefined; + } + // This can be called from source mapper in either source program or program that includes generated file + function getSourceFileLike(fileName) { + return !host.getSourceFileLike ? + getSourceFile(fileName) || getOrCreateSourceFileLike(fileName) : + host.getSourceFileLike(fileName); } function toLineColumnOffset(fileName, position) { - var file = getFile(fileName); // TODO: GH#18217 + var file = getSourceFileLike(fileName); // TODO: GH#18217 return file.getLineAndCharacterOfPosition(position); } function clearCache() { - sourcemappedFileCache = createSourceFileLikeCache(host); + sourceFileLike.clear(); + documentPositionMappers.clear(); } } ts.getSourceMapper = getSourceMapper; - function createSourceFileLikeCache(host) { - var cached = ts.createMap(); - return { - get: function (path) { - if (cached.has(path)) { - return cached.get(path); + function getDocumentPositionMapper(host, generatedFileName, generatedFileLineInfo, readMapFile) { + var mapFileName = ts.tryGetSourceMappingURL(generatedFileLineInfo); + if (mapFileName) { + var match = base64UrlRegExp.exec(mapFileName); + if (match) { + if (match[1]) { + var base64Object = match[1]; + return convertDocumentToSourceMapper(host, ts.base64decode(ts.sys, base64Object), generatedFileName); } - if (!host.fileExists || !host.readFile || !host.fileExists(path)) - return; - // And failing that, check the disk - var text = host.readFile(path); // TODO: GH#18217 - var file = { - text: text, - lineMap: undefined, - getLineAndCharacterOfPosition: function (pos) { - return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); - } - }; - cached.set(path, file); - return file; + // Not a data URL we can parse, skip it + mapFileName = undefined; + } + } + var possibleMapLocations = []; + if (mapFileName) { + possibleMapLocations.push(mapFileName); + } + possibleMapLocations.push(generatedFileName + ".map"); + var originalMapFileName = mapFileName && ts.getNormalizedAbsolutePath(mapFileName, ts.getDirectoryPath(generatedFileName)); + for (var _i = 0, possibleMapLocations_1 = possibleMapLocations; _i < possibleMapLocations_1.length; _i++) { + var location = possibleMapLocations_1[_i]; + var mapFileName_1 = ts.getNormalizedAbsolutePath(location, ts.getDirectoryPath(generatedFileName)); + var mapFileContents = readMapFile(mapFileName_1, originalMapFileName); + if (ts.isString(mapFileContents)) { + return convertDocumentToSourceMapper(host, mapFileContents, mapFileName_1); + } + if (mapFileContents !== undefined) { + return mapFileContents || undefined; + } + } + return undefined; + } + ts.getDocumentPositionMapper = getDocumentPositionMapper; + function convertDocumentToSourceMapper(host, contents, mapFileName) { + var map = ts.tryParseRawSourceMap(contents); + if (!map || !map.sources || !map.file || !map.mappings) { + // obviously invalid map + return undefined; + } + return ts.createDocumentPositionMapper(host, map, mapFileName); + } + function createSourceFileLike(text, lineMap) { + return { + text: text, + lineMap: lineMap, + getLineAndCharacterOfPosition: function (pos) { + return ts.computeLineAndCharacterOfPosition(ts.getLineStarts(this), pos); } }; } @@ -104140,6 +105036,7 @@ var ts; /* @internal */ var ts; (function (ts) { + var visitedNestedConvertibleFunctions = ts.createMap(); function computeSuggestionDiagnostics(sourceFile, program, cancellationToken) { program.getSemanticDiagnostics(sourceFile, cancellationToken); var diags = []; @@ -104150,6 +105047,7 @@ var ts; diags.push(ts.createDiagnosticForNode(getErrorNodeFromCommonJsIndicator(sourceFile.commonJsModuleIndicator), ts.Diagnostics.File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module)); } var isJsFile = ts.isSourceFileJS(sourceFile); + visitedNestedConvertibleFunctions.clear(); check(sourceFile); if (ts.getAllowSyntheticDefaultImports(program.getCompilerOptions())) { for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { @@ -104247,13 +105145,17 @@ var ts; } } function addConvertToAsyncFunctionDiagnostics(node, checker, diags) { - if (!ts.isAsyncFunction(node) && + // need to check function before checking map so that deeper levels of nested callbacks are checked + if (isConvertibleFunction(node, checker) && !visitedNestedConvertibleFunctions.has(getKeyFromNode(node))) { + diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); + } + } + function isConvertibleFunction(node, checker) { + return !ts.isAsyncFunction(node) && node.body && ts.isBlock(node.body) && hasReturnStatementWithPromiseHandler(node.body) && - returnsPromise(node, checker)) { - diags.push(ts.createDiagnosticForNode(!node.name && ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name) ? node.parent.name : node, ts.Diagnostics.This_may_be_converted_to_an_async_function)); - } + returnsPromise(node, checker); } function returnsPromise(node, checker) { var functionType = checker.getTypeAtLocation(node); @@ -104294,16 +105196,21 @@ var ts; // should be kept up to date with getTransformationBody in convertToAsyncFunction.ts function isFixablePromiseArgument(arg) { switch (arg.kind) { - case 96 /* NullKeyword */: - case 72 /* Identifier */: // identifier includes undefined case 239 /* FunctionDeclaration */: case 196 /* FunctionExpression */: case 197 /* ArrowFunction */: + visitedNestedConvertibleFunctions.set(getKeyFromNode(arg), true); + /* falls through */ + case 96 /* NullKeyword */: + case 72 /* Identifier */: // identifier includes undefined return true; default: return false; } } + function getKeyFromNode(exp) { + return exp.pos.toString() + ":" + exp.end.toString(); + } })(ts || (ts = {})); /* @internal */ var ts; @@ -105026,7 +105933,7 @@ var ts; return typeof o.type === "object" && !ts.forEachEntry(o.type, function (v) { return typeof v !== "number"; }); }); options = ts.cloneCompilerOptions(options); - var _loop_16 = function (opt) { + var _loop_17 = function (opt) { if (!ts.hasProperty(options, opt.name)) { return "continue"; } @@ -105045,7 +105952,7 @@ var ts; }; for (var _i = 0, commandLineOptionsStringToEnum_1 = commandLineOptionsStringToEnum; _i < commandLineOptionsStringToEnum_1.length; _i++) { var opt = commandLineOptionsStringToEnum_1[_i]; - _loop_16(opt); + _loop_17(opt); } return options; } @@ -106958,10 +107865,7 @@ var ts; * Trimming will be done for lines after the previous range */ function trimTrailingWhitespacesForRemainingRange() { - if (!previousRange) { - return; - } - var startPosition = previousRange.end; + var startPosition = previousRange ? previousRange.end : originalRange.pos; var startLine = sourceFile.getLineAndCharacterOfPosition(startPosition).line; var endLine = sourceFile.getLineAndCharacterOfPosition(originalRange.end).line; trimTrailingWhitespacesForLines(startLine, endLine + 1, previousRange); @@ -108220,7 +109124,7 @@ var ts; ChangeTracker.prototype.finishDeleteDeclarations = function () { var _this = this; var deletedNodesInLists = new ts.NodeSet(); // Stores nodes in lists that we already deleted. Used to avoid deleting `, ` twice in `a, b`. - var _loop_17 = function (sourceFile, node) { + var _loop_18 = function (sourceFile, node) { if (!this_1.deletedNodes.some(function (d) { return d.sourceFile === sourceFile && ts.rangeContainsRangeExclusive(d.node, node); })) { if (ts.isArray(node)) { this_1.deleteRange(sourceFile, ts.rangeOfTypeParameters(node)); @@ -108233,7 +109137,7 @@ var ts; var this_1 = this; for (var _i = 0, _a = this.deletedNodes; _i < _a.length; _i++) { var _b = _a[_i], sourceFile = _b.sourceFile, node = _b.node; - _loop_17(sourceFile, node); + _loop_18(sourceFile, node); } deletedNodesInLists.forEach(function (node) { var sourceFile = node.getSourceFile(); @@ -108290,14 +109194,14 @@ var ts; // order changes by start position // If the start position is the same, put the shorter range first, since an empty range (x, x) may precede (x, y) but not vice-versa. var normalized = ts.stableSort(changesInFile, function (a, b) { return (a.range.pos - b.range.pos) || (a.range.end - b.range.end); }); - var _loop_18 = function (i) { + var _loop_19 = function (i) { ts.Debug.assert(normalized[i].range.end <= normalized[i + 1].range.pos, "Changes overlap", function () { return JSON.stringify(normalized[i].range) + " and " + JSON.stringify(normalized[i + 1].range); }); }; // verify that change intervals do not overlap, except possibly at end points. for (var i = 0; i < normalized.length - 1; i++) { - _loop_18(i); + _loop_19(i); } var textChanges = normalized.map(function (c) { return ts.createTextChange(ts.createTextSpanFromRange(c.range), computeNewText(c, sourceFile, newLineCharacter, formatContext, validate)); @@ -108901,6 +109805,40 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addNameToNamelessParameter"; + var errorCodes = [ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return makeChange(t, context.sourceFile, context.span.start); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_parameter_name, fixId, ts.Diagnostics.Add_names_to_all_parameters_without_names)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { return makeChange(changes, diag.file, diag.start); }); }, + }); + function makeChange(changeTracker, sourceFile, pos) { + var token = ts.getTokenAtPosition(sourceFile, pos); + if (!ts.isIdentifier(token)) { + return ts.Debug.fail("add-name-to-nameless-parameter operates on identifiers, but got a " + ts.formatSyntaxKind(token.kind)); + } + var param = token.parent; + if (!ts.isParameter(param)) { + return ts.Debug.fail("Tried to add a parameter name to a non-parameter: " + ts.formatSyntaxKind(token.kind)); + } + var i = param.parent.parameters.indexOf(param); + ts.Debug.assert(!param.type, "Tried to add a parameter name to a parameter that already had one."); + ts.Debug.assert(i > -1, "Parameter not found in parent parameter list."); + var replacement = ts.createParameter( + /*decorators*/ undefined, param.modifiers, param.dotDotDotToken, "arg" + i, param.questionToken, ts.createTypeReferenceNode(token, /*typeArguments*/ undefined), param.initializer); + changeTracker.replaceNode(sourceFile, token, replacement); + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -109228,20 +110166,8 @@ var ts; annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); } } - function isApplicableFunctionForInference(declaration) { - switch (declaration.kind) { - case 239 /* FunctionDeclaration */: - case 156 /* MethodDeclaration */: - case 157 /* Constructor */: - return true; - case 196 /* FunctionExpression */: - var parent = declaration.parent; - return ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) || !!declaration.name; - } - return false; - } function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { - if (!ts.isIdentifier(parameterDeclaration.name) || !isApplicableFunctionForInference(containingFunction)) { + if (!ts.isIdentifier(parameterDeclaration.name)) { return; } var parameterInferences = inferTypeForParametersFromUsage(containingFunction, sourceFile, program, cancellationToken) || @@ -109254,12 +110180,17 @@ var ts; annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host); } else { + var needParens = ts.isArrowFunction(containingFunction) && !ts.findChildOfKind(containingFunction, 20 /* OpenParenToken */, sourceFile); + if (needParens) + changes.insertNodeBefore(sourceFile, ts.first(containingFunction.parameters), ts.createToken(20 /* OpenParenToken */)); for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; if (declaration && !declaration.type && !declaration.initializer) { annotate(changes, sourceFile, declaration, type, program, host); } } + if (needParens) + changes.insertNodeAfter(sourceFile, ts.last(containingFunction.parameters), ts.createToken(21 /* CloseParenToken */)); } } function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { @@ -109380,6 +110311,7 @@ var ts; case 157 /* Constructor */: searchToken = ts.findChildOfKind(containingFunction, 124 /* ConstructorKeyword */, sourceFile); break; + case 197 /* ArrowFunction */: case 196 /* FunctionExpression */: var parent = containingFunction.parent; searchToken = ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name) ? @@ -110057,7 +110989,7 @@ var ts; var newNodes = transformExpression(node, transformer, node); changes.replaceNodeWithNodes(sourceFile, nodeToReplace, newNodes); } - var _loop_19 = function (statement) { + var _loop_20 = function (statement) { ts.forEachChild(statement, function visit(node) { if (ts.isCallExpression(node)) { startTransformation(node, statement); @@ -110069,7 +111001,7 @@ var ts; }; for (var _i = 0, returnStatements_1 = returnStatements; _i < returnStatements_1.length; _i++) { var statement = returnStatements_1[_i]; - _loop_19(statement); + _loop_20(statement); } } function getReturnStatementsWithPromiseHandlers(body) { @@ -110977,11 +111909,10 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var program = context.program, sourceFile = context.sourceFile, span = context.span; + var sourceFile = context.sourceFile, span = context.span; var classDeclaration = getClass(sourceFile, span.start); - var checker = program.getTypeChecker(); return ts.mapDefined(ts.getClassImplementsHeritageClauseElements(classDeclaration), function (implementedTypeNode) { - var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, t, context.preferences); }); return changes.length === 0 ? undefined : codefix.createCodeFixAction(fixId, changes, [ts.Diagnostics.Implement_interface_0, implementedTypeNode.getText(sourceFile)], fixId, ts.Diagnostics.Implement_all_unimplemented_interfaces); }); }, @@ -110993,7 +111924,7 @@ var ts; if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { for (var _i = 0, _a = ts.getClassImplementsHeritageClauseElements(classDeclaration); _i < _a.length; _i++) { var implementedTypeNode = _a[_i]; - addMissingDeclarations(context.program.getTypeChecker(), implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); + addMissingDeclarations(context, implementedTypeNode, diag.file, classDeclaration, changes, context.preferences); } } }); @@ -111005,7 +111936,8 @@ var ts; function symbolPointsToNonPrivateMember(symbol) { return !(ts.getModifierFlags(symbol.valueDeclaration) & 8 /* Private */); } - function addMissingDeclarations(checker, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + function addMissingDeclarations(context, implementedTypeNode, sourceFile, classDeclaration, changeTracker, preferences) { + var checker = context.program.getTypeChecker(); var maybeHeritageClauseSymbol = getHeritageClauseSymbolTable(classDeclaration, checker); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. @@ -111019,11 +111951,11 @@ var ts; if (!classType.getStringIndexType()) { createMissingIndexSignatureDeclaration(implementedType, 0 /* String */); } - codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, nonPrivateAndNotExistedInHeritageClauseMembers, context, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); function createMissingIndexSignatureDeclaration(type, kind) { var indexInfoOfKind = checker.getIndexInfoOfType(type, kind); if (indexInfoOfKind) { - changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration)); + changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration, /*flags*/ undefined, codefix.getNoopSymbolTrackerWithResolver(context))); } } } @@ -111349,7 +112281,7 @@ var ts; var symbolName = ts.isJsxOpeningLikeElement(symbolToken.parent) && symbolToken.parent.tagName === symbolToken && (ts.isIntrinsicJsxName(symbolToken.text) || checker.resolveName(symbolToken.text, symbolToken, 67108863 /* All */, /*excludeGlobals*/ false)) - ? checker.getJsxNamespace() + ? checker.getJsxNamespace(sourceFile) : symbolToken.text; // "default" is a keyword and not a legal identifier for the import, so we don't expect it here ts.Debug.assert(symbolName !== "default" /* Default */); @@ -111721,7 +112653,7 @@ var ts; }); typeDeclToMembers.forEach(function (infos, classDeclaration) { var supers = getAllSupers(classDeclaration, checker); - var _loop_20 = function (info) { + var _loop_21 = function (info) { // If some superclass added this property, don't add it again. if (supers.some(function (superClassOrInterface) { var superInfos = typeDeclToMembers.get(superClassOrInterface); @@ -111748,7 +112680,7 @@ var ts; }; for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { var info = infos_1[_i]; - _loop_20(info); + _loop_21(info); } }); })); @@ -111897,7 +112829,7 @@ var ts; return codefix.createCodeFixAction(fixName, changes, [makeStatic ? ts.Diagnostics.Declare_static_method_0 : ts.Diagnostics.Declare_method_0, token.text], fixId, ts.Diagnostics.Add_all_missing_members); } function addMethodDeclaration(context, changeTracker, declSourceFile, typeDecl, token, callExpression, makeStatic, inJs, preferences) { - var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, !ts.isInterfaceDeclaration(typeDecl)); + var methodDeclaration = codefix.createMethodFromCallExpression(context, callExpression, token.text, inJs, makeStatic, preferences, typeDecl); var containingMethodDeclaration = ts.getAncestor(callExpression, 156 /* MethodDeclaration */); if (containingMethodDeclaration && containingMethodDeclaration.parent === typeDecl) { changeTracker.insertNodeAfter(declSourceFile, containingMethodDeclaration, methodDeclaration); @@ -111923,6 +112855,40 @@ var ts; })(ts || (ts = {})); /* @internal */ var ts; +(function (ts) { + var codefix; + (function (codefix) { + var fixId = "addMissingNewOperator"; + var errorCodes = [ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new.code]; + codefix.registerCodeFix({ + errorCodes: errorCodes, + getCodeActions: function (context) { + var sourceFile = context.sourceFile, span = context.span; + var changes = ts.textChanges.ChangeTracker.with(context, function (t) { return addMissingNewOperator(t, sourceFile, span); }); + return [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Add_missing_new_operator_to_call, fixId, ts.Diagnostics.Add_missing_new_operator_to_all_calls)]; + }, + fixIds: [fixId], + getAllCodeActions: function (context) { return codefix.codeFixAll(context, errorCodes, function (changes, diag) { + return addMissingNewOperator(changes, context.sourceFile, diag); + }); }, + }); + function addMissingNewOperator(changes, sourceFile, span) { + var call = ts.cast(findAncestorMatchingSpan(sourceFile, span), ts.isCallExpression); + var newExpression = ts.createNew(call.expression, call.typeArguments, call.arguments); + changes.replaceNode(sourceFile, call, newExpression); + } + function findAncestorMatchingSpan(sourceFile, span) { + var token = ts.getTokenAtPosition(sourceFile, span.start); + var end = ts.textSpanEnd(span); + while (token.end < end) { + token = token.parent; + } + return token; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; (function (ts) { var codefix; (function (codefix) { @@ -112000,10 +112966,10 @@ var ts; var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); if (!tsconfigObjectLiteral) return undefined; - var compilerOptionsProperty = findProperty(tsconfigObjectLiteral, "compilerOptions"); + var compilerOptionsProperty = codefix.findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); if (!compilerOptionsProperty) { var newCompilerOptions = ts.createObjectLiteral([makeDefaultBaseUrl(), makeDefaultPaths()]); - changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); + changes.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, codefix.createJsonPropertyAssignment("compilerOptions", newCompilerOptions)); return defaultTypesDirectoryName; } var compilerOptions = compilerOptionsProperty.initializer; @@ -112015,10 +112981,10 @@ var ts; } var defaultBaseUrl = "."; function makeDefaultBaseUrl() { - return createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); + return codefix.createJsonPropertyAssignment("baseUrl", ts.createStringLiteral(defaultBaseUrl)); } function getOrAddBaseUrl(changes, tsconfig, compilerOptions) { - var baseUrlProp = findProperty(compilerOptions, "baseUrl"); + var baseUrlProp = codefix.findJsonProperty(compilerOptions, "baseUrl"); if (baseUrlProp) { return ts.isStringLiteral(baseUrlProp.initializer) ? baseUrlProp.initializer.text : defaultBaseUrl; } @@ -112029,13 +112995,13 @@ var ts; } var defaultTypesDirectoryName = "types"; function makeDefaultPathMapping() { - return createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); + return codefix.createJsonPropertyAssignment("*", ts.createArrayLiteral([ts.createStringLiteral(defaultTypesDirectoryName + "/*")])); } function makeDefaultPaths() { - return createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); + return codefix.createJsonPropertyAssignment("paths", ts.createObjectLiteral([makeDefaultPathMapping()])); } function getOrAddPathMapping(changes, tsconfig, compilerOptions) { - var paths = findProperty(compilerOptions, "paths"); + var paths = codefix.findJsonProperty(compilerOptions, "paths"); if (!paths || !ts.isObjectLiteralExpression(paths.initializer)) { changes.insertNodeAtObjectStart(tsconfig, compilerOptions, makeDefaultPaths()); return defaultTypesDirectoryName; @@ -112051,12 +113017,6 @@ var ts; changes.insertNodeAtObjectStart(tsconfig, paths.initializer, makeDefaultPathMapping()); return defaultTypesDirectoryName; } - function createJsonPropertyAssignment(name, initializer) { - return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); - } - function findProperty(obj, name) { - return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); - } function getInstallCommand(fileName, packageName) { return { type: "install package", file: fileName, packageName: packageName }; } @@ -112085,9 +113045,9 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var program = context.program, sourceFile = context.sourceFile, span = context.span; + var sourceFile = context.sourceFile, span = context.span; var changes = ts.textChanges.ChangeTracker.with(context, function (t) { - return addMissingMembers(getClass(sourceFile, span.start), sourceFile, program.getTypeChecker(), t, context.preferences); + return addMissingMembers(getClass(sourceFile, span.start), sourceFile, context, t, context.preferences); }); return changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, ts.Diagnostics.Implement_inherited_abstract_class, fixId, ts.Diagnostics.Implement_all_inherited_abstract_classes)]; }, @@ -112097,7 +113057,7 @@ var ts; return codefix.codeFixAll(context, errorCodes, function (changes, diag) { var classDeclaration = getClass(diag.file, diag.start); if (ts.addToSeen(seenClassDeclarations, ts.getNodeId(classDeclaration))) { - addMissingMembers(classDeclaration, context.sourceFile, context.program.getTypeChecker(), changes, context.preferences); + addMissingMembers(classDeclaration, context.sourceFile, context, changes, context.preferences); } }); }, @@ -112108,13 +113068,14 @@ var ts; var token = ts.getTokenAtPosition(sourceFile, pos); return ts.cast(token.parent, ts.isClassLike); } - function addMissingMembers(classDeclaration, sourceFile, checker, changeTracker, preferences) { + function addMissingMembers(classDeclaration, sourceFile, context, changeTracker, preferences) { var extendsNode = ts.getEffectiveBaseTypeNode(classDeclaration); + var checker = context.program.getTypeChecker(); var instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); // Note that this is ultimately derived from a map indexed by symbol names, // so duplicates cannot occur. var abstractAndNonPrivateExtendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType).filter(symbolPointsToNonPrivateAndAbstractMember); - codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); + codefix.createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, context, preferences, function (member) { return changeTracker.insertNodeAtClassStart(sourceFile, classDeclaration, member); }); } function symbolPointsToNonPrivateAndAbstractMember(symbol) { // See `codeFixClassExtendAbstractProtectedProperty.ts` in https://github.com/Microsoft/TypeScript/pull/11547/files @@ -112856,24 +113817,43 @@ var ts; * @param possiblyMissingSymbols The collection of symbols to filter and then get insertions for. * @returns Empty string iff there are no member insertions. */ - function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, checker, preferences, out) { + function createMissingMemberNodes(classDeclaration, possiblyMissingSymbols, context, preferences, out) { var classMembers = classDeclaration.symbol.members; for (var _i = 0, possiblyMissingSymbols_1 = possiblyMissingSymbols; _i < possiblyMissingSymbols_1.length; _i++) { var symbol = possiblyMissingSymbols_1[_i]; if (!classMembers.has(symbol.escapedName)) { - addNewNodeForMemberSymbol(symbol, classDeclaration, checker, preferences, out); + addNewNodeForMemberSymbol(symbol, classDeclaration, context, preferences, out); } } } codefix.createMissingMemberNodes = createMissingMemberNodes; + function getModuleSpecifierResolverHost(context) { + return { + directoryExists: context.host.directoryExists ? function (d) { return context.host.directoryExists(d); } : undefined, + fileExists: context.host.fileExists ? function (f) { return context.host.fileExists(f); } : undefined, + getCurrentDirectory: context.host.getCurrentDirectory ? function () { return context.host.getCurrentDirectory(); } : undefined, + readFile: context.host.readFile ? function (f) { return context.host.readFile(f); } : undefined, + useCaseSensitiveFileNames: context.host.useCaseSensitiveFileNames ? function () { return context.host.useCaseSensitiveFileNames(); } : undefined, + getSourceFiles: function () { return context.program.getSourceFiles(); }, + getCommonSourceDirectory: function () { return context.program.getCommonSourceDirectory(); }, + }; + } + function getNoopSymbolTrackerWithResolver(context) { + return { + trackSymbol: ts.noop, + moduleResolverHost: getModuleSpecifierResolverHost(context), + }; + } + codefix.getNoopSymbolTrackerWithResolver = getNoopSymbolTrackerWithResolver; /** * @returns Empty string iff there we can't figure out a representation for `symbol` in `enclosingDeclaration`. */ - function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, checker, preferences, out) { + function addNewNodeForMemberSymbol(symbol, enclosingDeclaration, context, preferences, out) { var declarations = symbol.getDeclarations(); if (!(declarations && declarations.length)) { return undefined; } + var checker = context.program.getTypeChecker(); var declaration = declarations[0]; var name = ts.getSynthesizedDeepClone(ts.getNameOfDeclaration(declaration), /*includeTrivia*/ false); var visibilityModifier = createVisibilityModifier(ts.getModifierFlags(declaration)); @@ -112885,7 +113865,7 @@ var ts; case 159 /* SetAccessor */: case 153 /* PropertySignature */: case 154 /* PropertyDeclaration */: - var typeNode = checker.typeToTypeNode(type, enclosingDeclaration); + var typeNode = checker.typeToTypeNode(type, enclosingDeclaration, /*flags*/ undefined, getNoopSymbolTrackerWithResolver(context)); out(ts.createProperty( /*decorators*/ undefined, modifiers, name, optional ? ts.createToken(56 /* QuestionToken */) : undefined, typeNode, /*initializer*/ undefined)); @@ -112925,13 +113905,14 @@ var ts; break; } function outputMethod(signature, modifiers, name, body) { - var method = signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body); + var method = signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body); if (method) out(method); } } - function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); + function signatureToMethodDeclaration(context, signature, enclosingDeclaration, modifiers, name, optional, body) { + var program = context.program; + var signatureDeclaration = program.getTypeChecker().signatureToSignatureDeclaration(signature, 156 /* MethodDeclaration */, enclosingDeclaration, 1 /* NoTruncation */ | 256 /* SuppressAnyReturnType */, getNoopSymbolTrackerWithResolver(context)); if (!signatureDeclaration) { return undefined; } @@ -112942,19 +113923,21 @@ var ts; signatureDeclaration.body = body; return signatureDeclaration; } - function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, body) { + function createMethodFromCallExpression(context, call, methodName, inJs, makeStatic, preferences, contextNode) { + var body = !ts.isInterfaceDeclaration(contextNode); var typeArguments = call.typeArguments, args = call.arguments, parent = call.parent; var checker = context.program.getTypeChecker(); + var tracker = getNoopSymbolTrackerWithResolver(context); var types = ts.map(args, function (arg) { // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" - return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg))); + return checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(arg)), contextNode, /*flags*/ undefined, tracker); }); var names = ts.map(args, function (arg) { return ts.isIdentifier(arg) ? arg.text : ts.isPropertyAccessExpression(arg) ? arg.name.text : undefined; }); var contextualType = checker.getContextualType(call); - var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, call) || ts.createKeywordTypeNode(120 /* AnyKeyword */); + var returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker) || ts.createKeywordTypeNode(120 /* AnyKeyword */); return ts.createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [ts.createToken(116 /* StaticKeyword */)] : undefined, @@ -113035,6 +114018,38 @@ var ts; } return undefined; } + function setJsonCompilerOptionValue(changeTracker, configFile, optionName, optionValue) { + var tsconfigObjectLiteral = ts.getTsConfigObjectLiteralExpression(configFile); + if (!tsconfigObjectLiteral) + return undefined; + var compilerOptionsProperty = findJsonProperty(tsconfigObjectLiteral, "compilerOptions"); + if (compilerOptionsProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, tsconfigObjectLiteral, createJsonPropertyAssignment("compilerOptions", ts.createObjectLiteral([ + createJsonPropertyAssignment(optionName, optionValue), + ]))); + return; + } + var compilerOptions = compilerOptionsProperty.initializer; + if (!ts.isObjectLiteralExpression(compilerOptions)) { + return; + } + var optionProperty = findJsonProperty(compilerOptions, optionName); + if (optionProperty === undefined) { + changeTracker.insertNodeAtObjectStart(configFile, compilerOptions, createJsonPropertyAssignment(optionName, optionValue)); + } + else { + changeTracker.replaceNode(configFile, optionProperty.initializer, optionValue); + } + } + codefix.setJsonCompilerOptionValue = setJsonCompilerOptionValue; + function createJsonPropertyAssignment(name, initializer) { + return ts.createPropertyAssignment(ts.createStringLiteral(name), initializer); + } + codefix.createJsonPropertyAssignment = createJsonPropertyAssignment; + function findJsonProperty(obj, name) { + return ts.find(obj.properties, function (p) { return ts.isPropertyAssignment(p) && !!p.name && ts.isStringLiteral(p.name) && p.name.text === name; }); + } + codefix.findJsonProperty = findJsonProperty; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); /* @internal */ @@ -113396,9 +114411,9 @@ var ts; forEachOwnNodeOfFunction(fnAst, function (node) { if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true) && ts.isPropertyAccessExpression(node.left) && node.left.expression.kind === 100 /* ThisKeyword */) { - var name_6 = node.left.name.text; - if (!ts.isJsPrivate(name_6)) { - ts.getOrUpdate(members, name_6, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_6, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); + var name_7 = node.left.name.text; + if (!ts.isJsPrivate(name_7)) { + ts.getOrUpdate(members, name_7, function () { return ts.createProperty(/*decorators*/ undefined, /*modifiers*/ undefined, name_7, /*questionOrExclamationToken*/ undefined, anyType(), /*initializer*/ undefined); }); } } }); @@ -113913,7 +114928,7 @@ var ts; }); var namespaceImportName = namespaceNameConflicts ? ts.getUniqueName(preferredName, sourceFile) : preferredName; var neededNamedImports = []; - var _loop_21 = function (element) { + var _loop_22 = function (element) { var propertyName = (element.propertyName || element.name).text; ts.FindAllReferences.Core.eachSymbolReferenceInFile(element.name, checker, sourceFile, function (id) { var access = ts.createPropertyAccess(ts.createIdentifier(namespaceImportName), propertyName); @@ -113932,7 +114947,7 @@ var ts; }; for (var _i = 0, _a = toConvert.elements; _i < _a.length; _i++) { var element = _a[_i]; - _loop_21(element); + _loop_22(element); } changes.replaceNode(sourceFile, toConvert, ts.createNamespaceImport(ts.createIdentifier(namespaceImportName))); if (neededNamedImports.length) { @@ -114327,32 +115342,30 @@ var ts; case 100 /* ThisKeyword */: rangeFacts |= RangeFacts.UsesThis; break; - case 233 /* LabeledStatement */: - { - var label = node.label; - (seenLabels || (seenLabels = [])).push(label.escapedText); - ts.forEachChild(node, visit); - seenLabels.pop(); - break; - } + case 233 /* LabeledStatement */: { + var label = node.label; + (seenLabels || (seenLabels = [])).push(label.escapedText); + ts.forEachChild(node, visit); + seenLabels.pop(); + break; + } case 229 /* BreakStatement */: - case 228 /* ContinueStatement */: - { - var label = node.label; - if (label) { - if (!ts.contains(seenLabels, label.escapedText)) { - // attempts to jump to label that is not in range to be extracted - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); - } + case 228 /* ContinueStatement */: { + var label = node.label; + if (label) { + if (!ts.contains(seenLabels, label.escapedText)) { + // attempts to jump to label that is not in range to be extracted + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingLabeledBreakOrContinueStatementWithTargetOutsideOfTheRange)); } - else { - if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { - // attempt to break or continue in a forbidden context - (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); - } - } - break; } + else { + if (!(permittedJumps & (node.kind === 229 /* BreakStatement */ ? 1 /* Break */ : 2 /* Continue */))) { + // attempt to break or continue in a forbidden context + (errors || (errors = [])).push(ts.createDiagnosticForNode(node, Messages.cannotExtractRangeContainingConditionalBreakOrContinueStatements)); + } + } + break; + } case 201 /* AwaitExpression */: rangeFacts |= RangeFacts.IsAsyncFunction; break; @@ -115164,7 +116177,7 @@ var ts; : ts.getEnclosingBlockScopeContainer(scopes[0]); ts.forEachChild(containingLexicalScopeOfExtraction, checkForUsedDeclarations); } - var _loop_22 = function (i) { + var _loop_23 = function (i) { var scopeUsages = usagesPerScope[i]; // Special case: in the innermost scope, all usages are available. // (The computed value reflects the value at the top-level of the scope, but the @@ -115204,7 +116217,7 @@ var ts; } }; for (var i = 0; i < scopes.length; i++) { - _loop_22(i); + _loop_23(i); } return { target: target, usagesPerScope: usagesPerScope, functionErrorsPerScope: functionErrorsPerScope, constantErrorsPerScope: constantErrorsPerScope, exposedVariableDeclarations: exposedVariableDeclarations }; function isInGenericContext(node) { @@ -115755,10 +116768,10 @@ var ts; } function updateImportsInOtherFiles(changes, program, oldFile, movedSymbols, newModuleName) { var checker = program.getTypeChecker(); - var _loop_23 = function (sourceFile) { + var _loop_24 = function (sourceFile) { if (sourceFile === oldFile) return "continue"; - var _loop_24 = function (statement) { + var _loop_25 = function (statement) { forEachImportInStatement(statement, function (importNode) { if (checker.getSymbolAtLocation(moduleSpecifierFromImport(importNode)) !== oldFile.symbol) return; @@ -115780,12 +116793,12 @@ var ts; }; for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; - _loop_24(statement); + _loop_25(statement); } }; for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - _loop_23(sourceFile); + _loop_24(sourceFile); } } function getNamespaceLikeImport(node) { @@ -116835,8 +117848,8 @@ var ts; SourceFileObject.prototype.getLineStarts = function () { return ts.getLineStarts(this); }; - SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character) { - return ts.getPositionOfLineAndCharacter(this, line, character); + SourceFileObject.prototype.getPositionOfLineAndCharacter = function (line, character, allowEdits) { + return ts.computePositionOfLineAndCharacter(ts.getLineStarts(this), line, character, this.text, allowEdits); }; SourceFileObject.prototype.getLineEndOfPosition = function (pos) { var line = this.getLineAndCharacterOfPosition(pos).line; @@ -117286,7 +118299,16 @@ var ts; } var useCaseSensitiveFileNames = ts.hostUsesCaseSensitiveFileNames(host); var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); - var sourceMapper = ts.getSourceMapper(useCaseSensitiveFileNames, currentDirectory, log, host, function () { return program; }); + var sourceMapper = ts.getSourceMapper({ + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCurrentDirectory: function () { return currentDirectory; }, + getProgram: getProgram, + fileExists: host.fileExists && (function (f) { return host.fileExists(f); }), + readFile: host.readFile && (function (f, encoding) { return host.readFile(f, encoding); }), + getDocumentPositionMapper: host.getDocumentPositionMapper && (function (generatedFileName, sourceFileName) { return host.getDocumentPositionMapper(generatedFileName, sourceFileName); }), + getSourceFileLike: host.getSourceFileLike && (function (f) { return host.getSourceFileLike(f); }), + log: log + }); function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { @@ -117339,15 +118361,7 @@ var ts; writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, fileExists: fileExists, - readFile: function (fileName) { - // stub missing host functionality - var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); - var entry = hostCache && hostCache.getEntryByPath(path); - if (entry) { - return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); - } - return host.readFile && host.readFile(fileName); - }, + readFile: readFile, realpath: host.realpath && (function (path) { return host.realpath(path); }), directoryExists: function (directoryName) { return ts.directoryProbablyExists(directoryName, host); @@ -117401,6 +118415,15 @@ var ts; !ts.isString(entry) : (!!host.fileExists && host.fileExists(fileName)); } + function readFile(fileName) { + // stub missing host functionality + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = hostCache && hostCache.getEntryByPath(path); + if (entry) { + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); + } + return host.readFile && host.readFile(fileName); + } // Release any files we have acquired in the old program but are // not part of the new program. function onReleaseOldSourceFile(oldSourceFile, oldOptions) { @@ -117612,7 +118635,7 @@ var ts; var sourceFile = getValidSourceFile(fileName); return ts.DocumentHighlights.getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch); } - function findRenameLocations(fileName, position, findInStrings, findInComments) { + function findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var node = ts.getTouchingPropertyName(sourceFile, position); @@ -117623,7 +118646,7 @@ var ts; }); } else { - return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, isForRename: true }, ts.FindAllReferences.toRenameLocation); + return getReferencesWorker(node, position, { findInStrings: findInStrings, findInComments: findInComments, providePrefixAndSuffixTextForRename: providePrefixAndSuffixTextForRename, isForRename: true }, function (entry, originalNode, checker) { return ts.FindAllReferences.toRenameLocation(entry, originalNode, checker, providePrefixAndSuffixTextForRename || false); }); } } function getReferencesAtPosition(fileName, position) { @@ -118047,9 +119070,9 @@ var ts; return ts.stringContains(path, "/node_modules/"); } } - function getRenameInfo(fileName, position) { + function getRenameInfo(fileName, position, options) { synchronizeHostData(); - return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position); + return ts.Rename.getRenameInfo(program, getValidSourceFile(fileName), position, options); } function getRefactorContext(file, positionOrRange, preferences, formatOptions) { var _a = typeof positionOrRange === "number" ? [positionOrRange, undefined] : [positionOrRange.pos, positionOrRange.end], startPosition = _a[0], endPosition = _a[1]; @@ -119307,13 +120330,13 @@ var ts; var _this = this; return this.forwardJSONCall("getImplementationAtPosition('" + fileName + "', " + position + ")", function () { return _this.languageService.getImplementationAtPosition(fileName, position); }); }; - LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { + LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position, options) { var _this = this; - return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position); }); + return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { return _this.languageService.getRenameInfo(fileName, position, options); }); }; - LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments) { + LanguageServiceShimObject.prototype.findRenameLocations = function (fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename) { var _this = this; - return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments); }); + return this.forwardJSONCall("findRenameLocations('" + fileName + "', " + position + ", " + findInStrings + ", " + findInComments + ", " + providePrefixAndSuffixTextForRename + ")", function () { return _this.languageService.findRenameLocations(fileName, position, findInStrings, findInComments, providePrefixAndSuffixTextForRename); }); }; /// GET BRACE MATCHING LanguageServiceShimObject.prototype.getBraceMatchingAtPosition = function (fileName, position) { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index f3a4bfc0f58..8954d9a4a6d 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -88,7 +88,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.3"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-dev"; + ts.version = ts.versionMajorMinor + ".0-rc"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -1280,6 +1280,18 @@ var ts; return result; } ts.extend = extend; + function copyProperties(first, second) { + for (var id in second) { + if (hasOwnProperty.call(second, id)) { + first[id] = second[id]; + } + } + } + ts.copyProperties = copyProperties; + function maybeBind(obj, fn) { + return fn ? fn.bind(obj) : undefined; + } + ts.maybeBind = maybeBind; function createMultiMap() { var map = createMap(); map.add = multiMapAdd; @@ -1998,7 +2010,11 @@ var ts; } ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes; function fill(length, cb) { - return new Array(length).fill(0).map(function (_, i) { return cb(i); }); + var result = Array(length); + for (var i = 0; i < length; i++) { + result[i] = cb(i); + } + return result; } ts.fill = fill; })(ts || (ts = {})); @@ -3255,15 +3271,17 @@ var ts; CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly"; CheckFlags[CheckFlags["Partial"] = 16] = "Partial"; CheckFlags[CheckFlags["HasNonUniformType"] = 32] = "HasNonUniformType"; - CheckFlags[CheckFlags["ContainsPublic"] = 64] = "ContainsPublic"; - CheckFlags[CheckFlags["ContainsProtected"] = 128] = "ContainsProtected"; - CheckFlags[CheckFlags["ContainsPrivate"] = 256] = "ContainsPrivate"; - CheckFlags[CheckFlags["ContainsStatic"] = 512] = "ContainsStatic"; - CheckFlags[CheckFlags["Late"] = 1024] = "Late"; - CheckFlags[CheckFlags["ReverseMapped"] = 2048] = "ReverseMapped"; - CheckFlags[CheckFlags["OptionalParameter"] = 4096] = "OptionalParameter"; - CheckFlags[CheckFlags["RestParameter"] = 8192] = "RestParameter"; + CheckFlags[CheckFlags["HasLiteralType"] = 64] = "HasLiteralType"; + CheckFlags[CheckFlags["ContainsPublic"] = 128] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 256] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 512] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 1024] = "ContainsStatic"; + CheckFlags[CheckFlags["Late"] = 2048] = "Late"; + CheckFlags[CheckFlags["ReverseMapped"] = 4096] = "ReverseMapped"; + CheckFlags[CheckFlags["OptionalParameter"] = 8192] = "OptionalParameter"; + CheckFlags[CheckFlags["RestParameter"] = 16384] = "RestParameter"; CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic"; + CheckFlags[CheckFlags["Discriminant"] = 96] = "Discriminant"; })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); var InternalSymbolName; (function (InternalSymbolName) { @@ -4015,6 +4033,16 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + /** + * djb2 hashing algorithm + * http://www.cse.yorku.ca/~oz/hash.html + */ + /* @internal */ + function generateDjb2Hash(data) { + var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); + return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); + } + ts.generateDjb2Hash = generateDjb2Hash; /** * Set a high stack trace limit to provide more information in case of an error. * Called for command-line and server use cases. @@ -4891,14 +4919,6 @@ var ts; return; } } - /** - * djb2 hashing algorithm - * http://www.cse.yorku.ca/~oz/hash.html - */ - function generateDjb2Hash(data) { - var chars = data.split("").map(function (str) { return str.charCodeAt(0); }); - return "" + chars.reduce(function (prev, curr) { return ((prev << 5) + prev) + curr; }, 5381); - } function createMD5HashUsingNativeCrypto(data) { var hash = _crypto.createHash("md5"); hash.update(data); @@ -5252,6 +5272,9 @@ var ts; Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."), use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."), Print_the_final_configuration_instead_of_building: diag(1350, ts.DiagnosticCategory.Message, "Print_the_final_configuration_instead_of_building_1350", "Print the final configuration instead of building."), + An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal: diag(1351, ts.DiagnosticCategory.Error, "An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal_1351", "An identifier or keyword cannot immediately follow a numeric literal."), + A_bigint_literal_cannot_use_exponential_notation: diag(1352, ts.DiagnosticCategory.Error, "A_bigint_literal_cannot_use_exponential_notation_1352", "A bigint literal cannot use exponential notation."), + A_bigint_literal_must_be_an_integer: diag(1353, ts.DiagnosticCategory.Error, "A_bigint_literal_must_be_an_integer_1353", "A bigint literal must be an integer."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5407,8 +5430,6 @@ var ts; Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."), Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."), An_AMD_module_cannot_have_multiple_name_assignments: diag(2458, ts.DiagnosticCategory.Error, "An_AMD_module_cannot_have_multiple_name_assignments_2458", "An AMD module cannot have multiple name assignments."), - Type_0_has_no_property_1_and_no_string_index_signature: diag(2459, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_and_no_string_index_signature_2459", "Type '{0}' has no property '{1}' and no string index signature."), - Type_0_has_no_property_1: diag(2460, ts.DiagnosticCategory.Error, "Type_0_has_no_property_1_2460", "Type '{0}' has no property '{1}'."), Type_0_is_not_an_array_type: diag(2461, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_2461", "Type '{0}' is not an array type."), A_rest_element_must_be_last_in_a_destructuring_pattern: diag(2462, ts.DiagnosticCategory.Error, "A_rest_element_must_be_last_in_a_destructuring_pattern_2462", "A rest element must be last in a destructuring pattern."), A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: diag(2463, ts.DiagnosticCategory.Error, "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463", "A binding pattern parameter cannot be optional in an implementation signature."), @@ -5422,7 +5443,7 @@ var ts; A_computed_property_name_of_the_form_0_must_be_of_type_symbol: diag(2471, ts.DiagnosticCategory.Error, "A_computed_property_name_of_the_form_0_must_be_of_type_symbol_2471", "A computed property name of the form '{0}' must be of type 'symbol'."), Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), - In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), + const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values: diag(2474, ts.DiagnosticCategory.Error, "const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values_2474", "const enum member initializers can only contain literal values and other computed enum values."), 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: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'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."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), @@ -5438,11 +5459,11 @@ var ts; The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property: diag(2490, ts.DiagnosticCategory.Error, "The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property_2490", "The type returned by the 'next()' method of an iterator must have a 'value' property."), The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern: diag(2491, ts.DiagnosticCategory.Error, "The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern_2491", "The left-hand side of a 'for...in' statement cannot be a destructuring pattern."), Cannot_redeclare_identifier_0_in_catch_clause: diag(2492, ts.DiagnosticCategory.Error, "Cannot_redeclare_identifier_0_in_catch_clause_2492", "Cannot redeclare identifier '{0}' in catch clause."), - Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2_2493", "Tuple type '{0}' with length '{1}' cannot be assigned to tuple with length '{2}'."), + Tuple_type_0_of_length_1_has_no_element_at_index_2: diag(2493, ts.DiagnosticCategory.Error, "Tuple_type_0_of_length_1_has_no_element_at_index_2_2493", "Tuple type '{0}' of length '{1}' has no element at index '{2}'."), Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher: diag(2494, ts.DiagnosticCategory.Error, "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494", "Using a string in a 'for...of' statement is only supported in ECMAScript 5 and higher."), Type_0_is_not_an_array_type_or_a_string_type: diag(2495, ts.DiagnosticCategory.Error, "Type_0_is_not_an_array_type_or_a_string_type_2495", "Type '{0}' is not an array type or a string type."), The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression: diag(2496, ts.DiagnosticCategory.Error, "The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_stand_2496", "The 'arguments' object cannot be referenced in an arrow function in ES3 and ES5. Consider using a standard function expression."), - Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct: diag(2497, ts.DiagnosticCategory.Error, "Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct_2497", "Module '{0}' resolves to a non-module entity and cannot be imported using this construct."), + This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export: diag(2497, ts.DiagnosticCategory.Error, "This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_2497", "This module can only be referenced with ECMAScript imports/exports by turning on the '{0}' flag and referencing its default export."), Module_0_uses_export_and_cannot_be_used_with_export_Asterisk: diag(2498, ts.DiagnosticCategory.Error, "Module_0_uses_export_and_cannot_be_used_with_export_Asterisk_2498", "Module '{0}' uses 'export =' and cannot be used with 'export *'."), An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2499, ts.DiagnosticCategory.Error, "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499", "An interface can only extend an identifier/qualified-name with optional type arguments."), A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: diag(2500, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500", "A class can only implement an identifier/qualified-name with optional type arguments."), @@ -5631,6 +5652,11 @@ var ts; Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more: diag(2740, ts.DiagnosticCategory.Error, "Type_0_is_missing_the_following_properties_from_type_1_Colon_2_and_3_more_2740", "Type '{0}' is missing the following properties from type '{1}': {2}, and {3} more."), Property_0_is_missing_in_type_1_but_required_in_type_2: diag(2741, ts.DiagnosticCategory.Error, "Property_0_is_missing_in_type_1_but_required_in_type_2_2741", "Property '{0}' is missing in type '{1}' but required in type '{2}'."), The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_annotation_is_necessary: diag(2742, ts.DiagnosticCategory.Error, "The_inferred_type_of_0_cannot_be_named_without_a_reference_to_1_This_is_likely_not_portable_A_type_a_2742", "The inferred type of '{0}' cannot be named without a reference to '{1}'. This is likely not portable. A type annotation is necessary."), + No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments: diag(2743, ts.DiagnosticCategory.Error, "No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments_2743", "No overload expects {0} type arguments, but overloads do exist that expect either {1} or {2} type arguments."), + Type_parameter_defaults_can_only_reference_previously_declared_type_parameters: diag(2744, ts.DiagnosticCategory.Error, "Type_parameter_defaults_can_only_reference_previously_declared_type_parameters_2744", "Type parameter defaults can only reference previously declared type parameters."), + This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided: diag(2745, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_pr_2745", "This JSX tag's '{0}' prop expects type '{1}' which requires multiple children, but only a single child was provided."), + This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided: diag(2746, ts.DiagnosticCategory.Error, "This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided_2746", "This JSX tag's '{0}' prop expects a single child of type '{1}', but multiple children were provided."), + _0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2: diag(2747, ts.DiagnosticCategory.Error, "_0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_t_2747", "'{0}' components don't accept text as child elements. Text in JSX has the type 'string', but the expected type of '{1}' is '{2}'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5980,6 +6006,7 @@ var ts; Build_all_projects_including_those_that_appear_to_be_up_to_date: diag(6368, ts.DiagnosticCategory.Message, "Build_all_projects_including_those_that_appear_to_be_up_to_date_6368", "Build all projects, including those that appear to be up to date"), Option_build_must_be_the_first_command_line_argument: diag(6369, ts.DiagnosticCategory.Error, "Option_build_must_be_the_first_command_line_argument_6369", "Option '--build' must be the first command line argument."), Options_0_and_1_cannot_be_combined: diag(6370, ts.DiagnosticCategory.Error, "Options_0_and_1_cannot_be_combined_6370", "Options '{0}' and '{1}' cannot be combined."), + Updating_unchanged_output_timestamps_of_project_0: diag(6371, ts.DiagnosticCategory.Message, "Updating_unchanged_output_timestamps_of_project_0_6371", "Updating unchanged output timestamps of project '{0}'..."), The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), @@ -6058,6 +6085,7 @@ var ts; JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type: diag(8029, ts.DiagnosticCategory.Error, "JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_h_8029", "JSDoc '@param' tag has name '{0}', but there is no parameter with that name. It would match 'arguments' if it had an array type."), The_type_of_a_function_declaration_must_match_the_function_s_signature: diag(8030, ts.DiagnosticCategory.Error, "The_type_of_a_function_declaration_must_match_the_function_s_signature_8030", "The type of a function declaration must match the function's signature."), You_cannot_rename_a_module_via_a_global_import: diag(8031, ts.DiagnosticCategory.Error, "You_cannot_rename_a_module_via_a_global_import_8031", "You cannot rename a module via a global import."), + Qualified_name_0_is_not_allowed_without_a_leading_param_object_1: diag(8032, ts.DiagnosticCategory.Error, "Qualified_name_0_is_not_allowed_without_a_leading_param_object_1_8032", "Qualified name '{0}' is not allowed without a leading '@param {object} {1}'."), Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clause: diag(9002, ts.DiagnosticCategory.Error, "Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_clas_9002", "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clause."), class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."), Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."), @@ -6194,6 +6222,7 @@ var ts; Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"), Add_missing_new_operator_to_all_calls: diag(95072, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_all_calls_95072", "Add missing 'new' operator to all calls"), Add_names_to_all_parameters_without_names: diag(95073, ts.DiagnosticCategory.Message, "Add_names_to_all_parameters_without_names_95073", "Add names to all parameters without names"), + Enable_the_experimentalDecorators_option_in_your_configuration_file: diag(95074, ts.DiagnosticCategory.Message, "Enable_the_experimentalDecorators_option_in_your_configuration_file_95074", "Enable the 'experimentalDecorators' option in your configuration file"), }; })(ts || (ts = {})); var ts; @@ -6418,16 +6447,13 @@ var ts; return result; } ts.computeLineStarts = computeLineStarts; - function getPositionOfLineAndCharacter(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text); + function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) { + return sourceFile.getPositionOfLineAndCharacter ? + sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) : + computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits); } ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter; /* @internal */ - function getPositionOfLineAndCharacterWithEdits(sourceFile, line, character) { - return computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, /*allowEdits*/ true); - } - ts.getPositionOfLineAndCharacterWithEdits = getPositionOfLineAndCharacterWithEdits; - /* @internal */ function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) { if (line < 0 || line >= lineStarts.length) { if (allowEdits) { @@ -7003,6 +7029,7 @@ var ts; result = text.substring(start, end); // No need to use all the fragments; no _ removal needed } if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) { + checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */)); return { type: 8 /* NumericLiteral */, value: "" + +result // if value is not an integer, it can be safely coerced to a number @@ -7011,9 +7038,29 @@ var ts; else { tokenValue = result; var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint + checkForIdentifierStartAfterNumericLiteral(start); return { type: type, value: tokenValue }; } } + function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) { + if (!isIdentifierStart(text.charCodeAt(pos), languageVersion)) { + return; + } + var identifierStart = pos; + var length = scanIdentifierParts().length; + if (length === 1 && text[identifierStart] === "n") { + if (isScientific) { + error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1); + } + else { + error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1); + } + } + else { + error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length); + pos = identifierStart; + } + } function scanOctalDigits() { var start = pos; while (isOctalDigit(text.charCodeAt(pos))) { @@ -8922,7 +8969,7 @@ var ts; return getSpanOfTokenAtPosition(sourceFile, node.pos); } var isMissing = nodeIsMissing(errorNode); - var pos = isMissing + var pos = isMissing || ts.isJsxText(node) ? errorNode.pos : ts.skipTrivia(sourceFile.text, errorNode.pos); // These asserts should all be satisfied for a properly constructed `errorNode`. @@ -10117,6 +10164,7 @@ var ts; return node.initializer; } } + ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration; function getSingleVariableOfVariableStatement(node) { return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined; } @@ -12155,10 +12203,10 @@ var ts; } if (getCheckFlags(s) & 6 /* Synthetic */) { var checkFlags = s.checkFlags; - var accessModifier = checkFlags & 256 /* ContainsPrivate */ ? 8 /* Private */ : - checkFlags & 64 /* ContainsPublic */ ? 4 /* Public */ : + var accessModifier = checkFlags & 512 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 128 /* ContainsPublic */ ? 4 /* Public */ : 16 /* Protected */; - var staticModifier = checkFlags & 512 /* ContainsStatic */ ? 32 /* Static */ : 0; + var staticModifier = checkFlags & 1024 /* ContainsStatic */ ? 32 /* Static */ : 0; return accessModifier | staticModifier; } if (s.flags & 4194304 /* Prototype */) { @@ -12405,6 +12453,10 @@ var ts; || kind === 290 /* JSDocVariadicType */; } ts.isTypeNodeKind = isTypeNodeKind; + function isAccessExpression(node) { + return node.kind === 189 /* PropertyAccessExpression */ || node.kind === 190 /* ElementAccessExpression */; + } + ts.isAccessExpression = isAccessExpression; })(ts || (ts = {})); (function (ts) { function getDefaultLibFileName(options) { @@ -15283,6 +15335,8 @@ var ts; return path; } ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; function comparePathsWorker(a, b, componentComparer) { if (a === b) return 0 /* EqualTo */; @@ -15290,14 +15344,30 @@ var ts; return -1 /* LessThan */; if (b === undefined) return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, ts.getRootLength(a)); + var bRoot = b.substring(0, ts.getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var 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. var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 0; i < sharedLength; i++) { - var stringComparer = i === 0 ? ts.compareStringsCaseInsensitive : componentComparer; - var result = stringComparer(aComponents[i], bComponents[i]); - if (result !== 0 /* EqualTo */) { - return result; + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; } } return ts.compareValues(aComponents.length, bComponents.length); @@ -16789,15 +16859,15 @@ var ts; if (setParentNodes === void 0) { setParentNodes = false; } scriptKind = ts.ensureScriptKind(fileName, scriptKind); if (scriptKind === 6 /* JSON */) { - var result_1 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); - ts.convertToObjectWorker(result_1, result_1.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); - result_1.referencedFiles = ts.emptyArray; - result_1.typeReferenceDirectives = ts.emptyArray; - result_1.libReferenceDirectives = ts.emptyArray; - result_1.amdDependencies = ts.emptyArray; - result_1.hasNoDefaultLib = false; - result_1.pragmas = ts.emptyMap; - return result_1; + var result_2 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes); + ts.convertToObjectWorker(result_2, result_2.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined); + result_2.referencedFiles = ts.emptyArray; + result_2.typeReferenceDirectives = ts.emptyArray; + result_2.libReferenceDirectives = ts.emptyArray; + result_2.amdDependencies = ts.emptyArray; + result_2.hasNoDefaultLib = false; + result_2.pragmas = ts.emptyMap; + return result_2; } initializeState(sourceText, languageVersion, syntaxCursor, scriptKind); var result = parseSourceFileWorker(fileName, languageVersion, setParentNodes, scriptKind); @@ -17676,6 +17746,8 @@ var ts; return parseElement(); } function currentNode(parsingContext) { + // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse. + // // If there is an outstanding parse error that we've encountered, but not attached to // some node, then we cannot get a node from the old source tree. This is because we // want to mark the next node we encounter as being unusable. @@ -17683,25 +17755,15 @@ var ts; // Note: This may be too conservative. Perhaps we could reuse the node and set the bit // on it (or its leftmost child) as having the error. For now though, being conservative // is nice and likely won't ever affect perf. - if (parseErrorBeforeNextFinishedNode) { - return undefined; - } - if (!syntaxCursor) { - // if we don't have a cursor, we could never return a node from the old tree. + if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) { return undefined; } var node = syntaxCursor.currentNode(scanner.getStartPos()); // Can't reuse a missing node. - if (ts.nodeIsMissing(node)) { - return undefined; - } // Can't reuse a node that intersected the change range. - if (node.intersectsChange) { - return undefined; - } // Can't reuse a node that contains a parse error. This is necessary so that we // produce the same set of errors again. - if (ts.containsParseError(node)) { + if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) { return undefined; } // We can only reuse a node if it was parsed under the same strict mode that we're @@ -17736,6 +17798,22 @@ var ts; nextToken(); return node; } + function isReusableParsingContext(parsingContext) { + switch (parsingContext) { + case 5 /* ClassMembers */: + case 2 /* SwitchClauses */: + case 0 /* SourceElements */: + case 1 /* BlockStatements */: + case 3 /* SwitchClauseStatements */: + case 6 /* EnumMembers */: + case 4 /* TypeMembers */: + case 8 /* VariableDeclarations */: + case 17 /* JSDocParameters */: + case 16 /* Parameters */: + return true; + } + return false; + } function canReuseNode(node, parsingContext) { switch (parsingContext) { case 5 /* ClassMembers */: @@ -17755,22 +17833,20 @@ var ts; case 17 /* JSDocParameters */: case 16 /* Parameters */: return isReusableParameter(node); - case 18 /* RestProperties */: - return false; // Any other lists we do not care about reusing nodes in. But feel free to add if // you can do so safely. Danger areas involve nodes that may involve speculative // parsing. If speculative parsing is involved with the node, then the range the // parser reached while looking ahead might be in the edited range (see the example // in canReuseVariableDeclaratorNode for a good case of this). - case 22 /* HeritageClauses */: + // case ParsingContext.HeritageClauses: // This would probably be safe to reuse. There is no speculative parsing with // heritage clauses. - case 19 /* TypeParameters */: + // case ParsingContext.TypeParameters: // This would probably be safe to reuse. There is no speculative parsing with // type parameters. Note that that's because type *parameters* only occur in // unambiguous *type* contexts. While type *arguments* occur in very ambiguous // *expression* contexts. - case 21 /* TupleElementTypes */: + // case ParsingContext.TupleElementTypes: // This would probably be safe to reuse. There is no speculative parsing with // tuple types. // Technically, type argument list types are probably safe to reuse. While @@ -17778,24 +17854,24 @@ var ts; // produced from speculative parsing a < as a type argument list), we only have // the types because speculative parsing succeeded. Thus, the lookahead never // went past the end of the list and rewound. - case 20 /* TypeArguments */: + // case ParsingContext.TypeArguments: // Note: these are almost certainly not safe to ever reuse. Expressions commonly // need a large amount of lookahead, and we should not reuse them as they may // have actually intersected the edit. - case 11 /* ArgumentExpressions */: + // case ParsingContext.ArgumentExpressions: // This is not safe to reuse for the same reason as the 'AssignmentExpression' // cases. i.e. a property assignment may end with an expression, and thus might // have lookahead far beyond it's old node. - case 12 /* ObjectLiteralMembers */: + // case ParsingContext.ObjectLiteralMembers: // This is probably not safe to reuse. There can be speculative parsing with // type names in a heritage clause. There can be generic names in the type // name list, and there can be left hand side expressions (which can have type // arguments.) - case 7 /* HeritageClauseElement */: + // case ParsingContext.HeritageClauseElement: // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes // on any given element. Same for children. - case 13 /* JsxAttributes */: - case 14 /* JsxChildren */: + // case ParsingContext.JsxAttributes: + // case ParsingContext.JsxChildren: } return false; } @@ -23025,17 +23101,18 @@ var ts; var libReferenceDirectives_1 = context.libReferenceDirectives; ts.forEach(ts.toArray(entryOrList), function (arg) { // TODO: GH#18217 + var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path; if (arg.arguments["no-default-lib"]) { context.hasNoDefaultLib = true; } - else if (arg.arguments.types) { - typeReferenceDirectives_1.push({ pos: arg.arguments.types.pos, end: arg.arguments.types.end, fileName: arg.arguments.types.value }); + else if (types) { + typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value }); } - else if (arg.arguments.lib) { - libReferenceDirectives_1.push({ pos: arg.arguments.lib.pos, end: arg.arguments.lib.end, fileName: arg.arguments.lib.value }); + else if (lib) { + libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value }); } - else if (arg.arguments.path) { - referencedFiles_1.push({ pos: arg.arguments.path.pos, end: arg.arguments.path.end, fileName: arg.arguments.path.value }); + else if (path) { + referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value }); } else { reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax); @@ -24707,12 +24784,12 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, !configParseResult.configFileSpecs ? function (_) { return false; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), f, getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign({ compilerOptions: __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; return (__assign({}, prev, (_a = {}, _a[cur[0]] = cur[1], _a))); - }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { + }, {}), { showConfig: undefined, configFile: undefined, configFilePath: undefined, help: undefined, init: undefined, listFiles: undefined, listEmittedFiles: undefined, project: undefined, build: undefined, version: undefined }), references: ts.map(configParseResult.projectReferences, function (r) { return (__assign({}, r, { path: r.originalPath, originalPath: undefined })); }), files: ts.length(files) ? files : undefined }, (configParseResult.configFileSpecs ? { include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs), exclude: configParseResult.configFileSpecs.validatedExcludeSpecs } : {}), { compilerOnSave: !!configParseResult.compileOnSave ? true : undefined }); @@ -24730,23 +24807,23 @@ var ts; } function matchesSpecs(path, includeSpecs, excludeSpecs) { if (!includeSpecs) - return function (_) { return false; }; + return function (_) { return true; }; var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { - return function (path) { return includeRe.test(path) && !excludeRe.test(path); }; + return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; } - return function (path) { return includeRe.test(path); }; + return function (path) { return !includeRe.test(path); }; } if (excludeRe) { - return function (path) { return !excludeRe.test(path); }; + return function (path) { return excludeRe.test(path); }; } - return function (_) { return false; }; + return function (_) { return true; }; } function getCustomTypeMapOfCommandLineOption(optionDefinition) { - if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean") { + if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") { // this is of a type CommandLineOptionOfPrimitiveType return undefined; } @@ -24903,7 +24980,7 @@ var ts; result.push(tab + "}"); } result.push("}"); - return result.join(newLine); + return result.join(newLine) + newLine; } } ts.generateTSConfig = generateTSConfig; @@ -27188,6 +27265,10 @@ var ts; if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) { symbol.members = ts.createSymbolTable(); } + // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate) + if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) { + symbol.constEnumOnlyModule = false; + } if (symbolFlags & 67220415 /* Value */) { setValueDeclaration(symbol, node); } @@ -27676,7 +27757,7 @@ var ts; } function isNarrowableReference(expr) { return expr.kind === 72 /* Identifier */ || expr.kind === 100 /* ThisKeyword */ || expr.kind === 98 /* SuperKeyword */ || - ts.isPropertyAccessExpression(expr) && isNarrowableReference(expr.expression) || + (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || ts.isElementAccessExpression(expr) && expr.argumentExpression && (ts.isStringLiteral(expr.argumentExpression) || ts.isNumericLiteral(expr.argumentExpression)) && isNarrowableReference(expr.expression); @@ -31120,10 +31201,10 @@ var ts; var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined); - var markerSuperType = createType(262144 /* TypeParameter */); - var markerSubType = createType(262144 /* TypeParameter */); + var markerSuperType = createTypeParameter(); + var markerSubType = createTypeParameter(); markerSubType.constraint = markerSuperType; - var markerOtherType = createType(262144 /* TypeParameter */); + var markerOtherType = createTypeParameter(); var noTypePredicate = createIdentifierTypePredicate("<>", 0, anyType); var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); @@ -31313,7 +31394,6 @@ var ts; var _jsxFactoryEntity; var subtypeRelation = ts.createMap(); var assignableRelation = ts.createMap(); - var definitelyAssignableRelation = ts.createMap(); var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); @@ -32031,13 +32111,18 @@ var ts; } } break; + case 197 /* ArrowFunction */: + // when targeting ES6 or higher there is no 'arguments' in an arrow function + // for lower compile targets the resolved symbol is used to emit an error + if (compilerOptions.target >= 2 /* ES2015 */) { + break; + } + // falls through case 156 /* MethodDeclaration */: - case 155 /* MethodSignature */: case 157 /* Constructor */: case 158 /* GetAccessor */: case 159 /* SetAccessor */: case 239 /* FunctionDeclaration */: - case 197 /* ArrowFunction */: if (meaning & 3 /* Variable */ && name === "arguments") { result = argumentsSymbol; break loop; @@ -32093,7 +32178,7 @@ var ts; // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. - if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol) && !isInTypeQuery(originalLocation)) { + if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) { result.isReferenced |= meaning; } if (!result) { @@ -32171,7 +32256,8 @@ var ts; } // If we're in an external module, we can't reference value symbols created from UMD export declarations if (result && isInExternalModule && (meaning & 67220415 /* Value */) === 67220415 /* Value */ && !(originalLocation.flags & 2097152 /* JSDoc */)) { - if (ts.some(result.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { + var merged = getMergedSymbol(result); + if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) { error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, ts.unescapeLeadingUnderscores(name)); // TODO: GH#18217 } } @@ -32931,7 +33017,10 @@ var ts; var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); if (!dontResolveAlias && symbol) { if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 279 /* SourceFile */)) { - error(referencingLocation, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 + ? "allowSyntheticDefaultImports" + : "esModuleInterop"; + error(referencingLocation, ts.Diagnostics.This_module_can_only_be_referenced_with_ECMAScript_imports_Slashexports_by_turning_on_the_0_flag_and_referencing_its_default_export, compilerOptionName); return symbol; } if (compilerOptions.esModuleInterop) { @@ -33226,6 +33315,12 @@ var ts; function createTypeofType() { return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType)); } + function createTypeParameter(symbol) { + var type = createType(262144 /* TypeParameter */); + if (symbol) + type.symbol = symbol; + return type; + } // A reserved member name starts with two underscores, but the third character cannot be an underscore // or the @ symbol. A third underscore indicates an escaped form of an identifer that started // with at least two underscores. The @ character indicates that the name is denoted by a well known ES @@ -34179,12 +34274,12 @@ var ts; return ts.createKeywordTypeNode(120 /* AnyKeyword */); } function addPropertyToElementList(propertySymbol, context, typeElements) { - var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */); + var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 4096 /* ReverseMapped */); var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; - if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 2048 /* Late */) { var decl = ts.first(propertySymbol.declarations); if (hasLateBindableName(decl)) { trackComputedName(decl.name, saveEnclosingDeclaration, context); @@ -34357,7 +34452,7 @@ var ts; } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.getSynthesizedClone) : undefined; - var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* RestParameter */; + var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* RestParameter */; var dotDotDotToken = isRest ? ts.createToken(25 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -34366,7 +34461,7 @@ var ts; cloneBindingName(parameterDeclaration.name) : ts.symbolName(parameterSymbol) : ts.symbolName(parameterSymbol); - var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 4096 /* OptionalParameter */; + var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 8192 /* OptionalParameter */; var questionToken = isOptional ? ts.createToken(56 /* QuestionToken */) : undefined; var parameterNode = ts.createParameter( /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, @@ -34762,6 +34857,21 @@ var ts; function isDefaultBindingContext(location) { return location.kind === 279 /* SourceFile */ || ts.isAmbientModule(location); } + function getNameOfSymbolFromNameType(symbol, context) { + var nameType = symbol.nameType; + if (nameType) { + if (nameType.flags & 384 /* StringOrNumberLiteral */) { + var name = "" + nameType.value; + if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) { + return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\""; + } + return name; + } + if (nameType.flags & 8192 /* UniqueESSymbol */) { + return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; + } + } + } /** * Gets a human-readable name for a symbol. * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead. @@ -34781,12 +34891,19 @@ var ts; } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; - var name = ts.getNameOfDeclaration(declaration); - if (name) { + var name_2 = ts.getNameOfDeclaration(declaration); + if (name_2) { if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) { return ts.symbolName(symbol); } - return ts.declarationNameToString(name); + if (ts.isComputedPropertyName(name_2) && !(ts.getCheckFlags(symbol) & 2048 /* Late */) && symbol.nameType && symbol.nameType.flags & 384 /* StringOrNumberLiteral */) { + // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name + var result = getNameOfSymbolFromNameType(symbol, context); + if (result !== undefined) { + return result; + } + } + return ts.declarationNameToString(name_2); } if (declaration.parent && declaration.parent.kind === 237 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); @@ -34801,16 +34918,8 @@ var ts; return declaration.kind === 209 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)"; } } - var nameType = symbol.nameType; - if (nameType) { - if (nameType.flags & 128 /* StringLiteral */ && !ts.isIdentifierText(nameType.value, compilerOptions.target)) { - return "\"" + ts.escapeString(nameType.value, 34 /* doubleQuote */) + "\""; - } - if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) { - return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]"; - } - } - return ts.symbolName(symbol); + var name = getNameOfSymbolFromNameType(symbol, context); + return name !== undefined ? name : ts.symbolName(symbol); } function isDeclarationVisible(node) { if (node) { @@ -35030,6 +35139,9 @@ var ts; var prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } + function getTypeOfPropertyOrIndexSignature(type, name) { + return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType; + } function isTypeAny(type) { return type && (type.flags & 1 /* Any */) !== 0; } @@ -35076,6 +35188,64 @@ var ts; var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */); return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); } + // Determine the control flow type associated with a destructuring declaration or assignment. The following + // forms of destructuring are possible: + // let { x } = obj; // BindingElement + // let [ x ] = obj; // BindingElement + // { x } = obj; // ShorthandPropertyAssignment + // { x: v } = obj; // PropertyAssignment + // [ x ] = obj; // Expression + // We construct a synthetic element access expression corresponding to 'obj.x' such that the control + // flow analyzer doesn't have to handle all the different syntactic forms. + function getFlowTypeOfDestructuring(node, declaredType) { + var reference = getSyntheticElementAccess(node); + return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType; + } + function getSyntheticElementAccess(node) { + var parentAccess = getParentElementAccess(node); + if (parentAccess && parentAccess.flowNode) { + var propName = getDestructuringPropertyName(node); + if (propName) { + var result = ts.createNode(190 /* ElementAccessExpression */, node.pos, node.end); + result.parent = node; + result.expression = parentAccess; + var literal = ts.createNode(10 /* StringLiteral */, node.pos, node.end); + literal.parent = result; + literal.text = propName; + result.argumentExpression = literal; + result.flowNode = parentAccess.flowNode; + return result; + } + } + } + function getParentElementAccess(node) { + var ancestor = node.parent.parent; + switch (ancestor.kind) { + case 186 /* BindingElement */: + case 275 /* PropertyAssignment */: + return getSyntheticElementAccess(ancestor); + case 187 /* ArrayLiteralExpression */: + return getSyntheticElementAccess(node.parent); + case 237 /* VariableDeclaration */: + return ancestor.initializer; + case 204 /* BinaryExpression */: + return ancestor.right; + } + } + function getDestructuringPropertyName(node) { + var parent = node.parent; + if (node.kind === 186 /* BindingElement */ && parent.kind === 184 /* ObjectBindingPattern */) { + return getLiteralPropertyNameText(node.propertyName || node.name); + } + if (node.kind === 275 /* PropertyAssignment */ || node.kind === 276 /* ShorthandPropertyAssignment */) { + return getLiteralPropertyNameText(node.name); + } + return "" + parent.elements.indexOf(node); + } + function getLiteralPropertyNameText(name) { + var type = getLiteralTypeFromPropertyName(name); + return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined; + } /** Return the inferred type for a binding element */ function getTypeForBindingElement(declaration) { var pattern = declaration.parent; @@ -35116,9 +35286,9 @@ var ts; else { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) var name = declaration.propertyName || declaration.name; - var exprType = getLiteralTypeFromPropertyName(name); - var declaredType = checkIndexedAccessIndexType(getIndexedAccessType(parentType, exprType, name), name); - type = getFlowTypeOfReference(declaration, getConstraintForLocation(declaredType, declaration.name)); + var indexType = getLiteralTypeFromPropertyName(name); + var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); } } else { @@ -35135,21 +35305,13 @@ var ts; mapType(parentType, function (t) { return sliceTupleType(t, index_1); }) : createArrayType(elementType); } + else if (isArrayLikeType(parentType)) { + var indexType = getLiteralType(index_1); + var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, declaration.name), declaration.name); + type = getFlowTypeOfDestructuring(declaration, declaredType); + } else { - // Use specific property type when parent is a tuple or numeric index type when parent is an array - var index_2 = pattern.elements.indexOf(declaration); - type = everyType(parentType, isTupleLikeType) ? - getTupleElementType(parentType, index_2) || declaration.initializer && checkDeclarationInitializer(declaration) : - elementType; - if (!type) { - if (isTupleType(parentType)) { - error(declaration, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(parentType), getTypeReferenceArity(parentType), pattern.elements.length); - } - else { - error(declaration, ts.Diagnostics.Type_0_has_no_property_1, typeToString(parentType), "" + index_2); - } - return errorType; - } + type = elementType; } } // In strict null checking mode, if a default value of a non-undefined type is specified, remove @@ -35600,12 +35762,11 @@ var ts; return anyType; } // Handle export default expressions - if (ts.isSourceFile(declaration)) { - var jsonSourceFile = ts.cast(declaration, ts.isJsonSourceFile); - if (!jsonSourceFile.statements.length) { + if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) { + if (!declaration.statements.length) { return emptyObjectType; } - var type_1 = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression)); + var type_1 = getWidenedLiteralType(checkExpression(declaration.statements[0].expression)); if (type_1.flags & 524288 /* Object */) { return getRegularTypeOfObjectLiteral(type_1); } @@ -35616,6 +35777,10 @@ var ts; } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & 512 /* ValueModule */) { + return getTypeOfFuncClassEnumModule(symbol); + } return errorType; } var type; @@ -35629,7 +35794,8 @@ var ts; || ts.isClassDeclaration(declaration) || ts.isFunctionDeclaration(declaration) || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration)) - || ts.isMethodSignature(declaration)) { + || ts.isMethodSignature(declaration) + || ts.isSourceFile(declaration)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) { return getTypeOfFuncClassEnumModule(symbol); @@ -35669,6 +35835,10 @@ var ts; return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.showSyntaxKind(declaration) + " for " + ts.Debug.showSymbol(symbol)); } if (!popTypeResolution()) { + // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` + if (symbol.flags & 512 /* ValueModule */) { + return getTypeOfFuncClassEnumModule(symbol); + } type = reportCircularityError(symbol); } return type; @@ -35862,7 +36032,7 @@ var ts; if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } - if (ts.getCheckFlags(symbol) & 2048 /* ReverseMapped */) { + if (ts.getCheckFlags(symbol) & 4096 /* ReverseMapped */) { return getTypeOfReverseMappedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -36241,9 +36411,8 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(262144 /* TypeParameter */); + type.thisType = createTypeParameter(symbol); type.thisType.isThisType = true; - type.thisType.symbol = symbol; type.thisType.constraint = type; } } @@ -36379,19 +36548,11 @@ var ts; } function getDeclaredTypeOfTypeParameter(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - var type = createType(262144 /* TypeParameter */); - type.symbol = symbol; - links.declaredType = type; - } - return links.declaredType; + return links.declaredType || (links.declaredType = createTypeParameter(symbol)); } function getDeclaredTypeOfAlias(symbol) { var links = getSymbolLinks(symbol); - if (!links.declaredType) { - links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); - } - return links.declaredType; + return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol))); } function getDeclaredTypeOfSymbol(symbol) { return tryGetDeclaredTypeOfSymbol(symbol) || errorType; @@ -36588,7 +36749,7 @@ var ts; * members. */ function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) { - ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 1024 /* Late */), "Expected a late-bound symbol."); + ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 2048 /* Late */), "Expected a late-bound symbol."); symbol.flags |= symbolFlags; getSymbolLinks(member.symbol).lateSymbol = symbol; if (!symbol.declarations) { @@ -36645,7 +36806,7 @@ var ts; // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations. var lateSymbol = lateSymbols.get(memberName); if (!lateSymbol) - lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */)); + lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 2048 /* Late */)); // Report an error if a late-bound member has the same name as an early-bound member, // or if we have another early-bound symbol declaration with the same name and // conflicting flags. @@ -36654,10 +36815,10 @@ var ts; // If we have an existing early-bound member, combine its declarations so that we can // report an error at each declaration. var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations; - var name_2 = ts.declarationNameToString(decl.name); - ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_2); }); - error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_2); - lateSymbol = createSymbol(0 /* None */, memberName, 1024 /* Late */); + var name_3 = ts.declarationNameToString(decl.name); + ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_declaration_0, name_3); }); + error(decl.name || decl, ts.Diagnostics.Duplicate_declaration_0, name_3); + lateSymbol = createSymbol(0 /* None */, memberName, 2048 /* Late */); } lateSymbol.nameType = type; addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags); @@ -36833,8 +36994,8 @@ var ts; var tupleRestIndex_1 = restType.target.hasRestElement ? elementTypes.length - 1 : -1; var restParams = ts.map(elementTypes, function (t, i) { var name = getParameterNameAtPosition(sig, restIndex_1 + i); - var checkFlags = i === tupleRestIndex_1 ? 8192 /* RestParameter */ : - i >= minLength_1 ? 4096 /* OptionalParameter */ : 0; + var checkFlags = i === tupleRestIndex_1 ? 16384 /* RestParameter */ : + i >= minLength_1 ? 8192 /* OptionalParameter */ : 0; var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags); symbol.type = i === tupleRestIndex_1 ? createArrayType(t) : t; return symbol; @@ -36907,7 +37068,13 @@ var ts; // type is the union of the constituent return types. function getUnionSignatures(signatureLists) { var result; + var indexWithLengthOverOne; for (var i = 0; i < signatureLists.length; i++) { + if (signatureLists[i].length === 0) + return ts.emptyArray; + if (signatureLists[i].length > 1) { + indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets + } for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) { var signature = _a[_i]; // Only process signatures with parameter lists that aren't already in the result list @@ -36932,8 +37099,82 @@ var ts; } } } + if (!ts.length(result) && indexWithLengthOverOne !== -1) { + // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single + // signature that handles all over them. We only do this when there are overloads in only one constituent. + // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of + // signatures from the type, whose ordering would be non-obvious) + var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0]; + var results = masterList.slice(); + var _loop_5 = function (signatures) { + if (signatures !== masterList) { + var signature_1 = signatures[0]; + ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass"); + results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); }); + if (!results) { + return "break"; + } + } + }; + for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) { + var signatures = signatureLists_1[_b]; + var state_2 = _loop_5(signatures); + if (state_2 === "break") + break; + } + result = results; + } return result || ts.emptyArray; } + function combineUnionThisParam(left, right) { + if (!left || !right) { + return left || right; + } + // A signature `this` type might be a read or a write position... It's very possible that it should be invariant + // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be + // permissive when calling, for now, we'll union the `this` types just like the overlapping-union-signature check does + var thisType = getUnionType([getTypeOfSymbol(left), getTypeOfSymbol(right)], 2 /* Subtype */); + return createSymbolWithType(left, thisType); + } + function combineUnionParameters(left, right) { + var longest = getParameterCount(left) >= getParameterCount(right) ? left : right; + var shorter = longest === left ? right : left; + var longestCount = getParameterCount(longest); + var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right)); + var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest); + var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0)); + for (var i = 0; i < longestCount; i++) { + var longestParamType = tryGetTypeAtPosition(longest, i); + var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType; + var unionParamType = getIntersectionType([longestParamType, shorterParamType]); + var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1); + var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter); + var leftName = getParameterNameAtPosition(left, i); + var rightName = getParameterNameAtPosition(right, i); + var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), leftName === rightName ? leftName : "arg" + i); + paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType; + params[i] = paramSymbol; + } + if (needsExtraRestElement) { + var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args"); + restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount)); + params[longestCount] = restParamSymbol; + } + return params; + } + function combineSignaturesOfUnionMembers(left, right) { + var declaration = left.declaration; + var params = combineUnionParameters(left, right); + var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); + var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); + var hasRestParam = left.hasRestParameter || right.hasRestParameter; + var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; + var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, + /*resolvedReturnType*/ undefined, + /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); + return result; + } function getUnionIndexInfo(types, kind) { var indexTypes = []; var isAnyReadonly = false; @@ -36951,7 +37192,7 @@ var ts; function resolveUnionTypeMembers(type) { // The members and properties collections are empty for union types. To get all properties of a union // type use getPropertiesOfType (only the language service uses this). - var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 0 /* Call */); })); + var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); })); var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); })); var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */); var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */); @@ -36987,7 +37228,7 @@ var ts; var numberIndexInfo; var types = type.types; var mixinCount = ts.countWhere(types, isMixinConstructorType); - var _loop_5 = function (i) { + var _loop_6 = function (i) { var t = type.types[i]; // When an intersection type contains mixin constructor types, the construct signatures from // those types are discarded and their return types are mixed into the return types of all @@ -37010,7 +37251,7 @@ var ts; numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */)); }; for (var i = 0; i < types.length; i++) { - _loop_5(i); + _loop_6(i); } setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo); } @@ -37086,7 +37327,7 @@ var ts; var members = ts.createSymbolTable(); for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) { var prop = _a[_i]; - var checkFlags = 2048 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); + var checkFlags = 4096 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0); var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags); inferredProp.declarations = prop.declarations; inferredProp.nameType = prop.nameType; @@ -37097,6 +37338,37 @@ var ts; } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined); } + // Return the lower bound of the key type in a mapped type. Intuitively, the lower + // bound includes those keys that are known to always be present, for example because + // because of constraints on type parameters (e.g. 'keyof T' for a constrained T). + function getLowerBoundOfKeyType(type) { + if (type.flags & (1 /* Any */ | 131068 /* Primitive */)) { + return type; + } + if (type.flags & 4194304 /* Index */) { + return getIndexType(getApparentType(type.type)); + } + if (type.flags & 16777216 /* Conditional */) { + return getLowerBoundOfConditionalType(type); + } + if (type.flags & 1048576 /* Union */) { + return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); + } + if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType)); + } + return neverType; + } + function getLowerBoundOfConditionalType(type) { + if (type.root.isDistributive) { + var constraint = getLowerBoundOfKeyType(type.checkType); + if (constraint !== type.checkType) { + var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); + return getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); + } + } + return type; + } /** Resolve the members of a mapped type { [P in K]: T } */ function resolveMappedTypeMembers(type) { var members = ts.createSymbolTable(); @@ -37126,10 +37398,7 @@ var ts; } } else { - // If the key type is a 'keyof X', obtain 'keyof C' where C is the base constraint of X. - // Then iterate over the constituents of the key type. - var iterationType = constraintType.flags & 4194304 /* Index */ ? getIndexType(getApparentType(constraintType.type)) : constraintType; - forEachType(iterationType, addMemberForKeyType); + forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType); } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo); function addMemberForKeyType(t) { @@ -37313,7 +37582,7 @@ var ts; return list.some(function (property) { var name = property.name && ts.getTextOfPropertyName(property.name); var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - return !!expected && typeIsLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); }); } function getAllPossiblePropertiesOfTypes(types) { @@ -37377,7 +37646,7 @@ var ts; if (type.root.isDistributive) { var simplified = getSimplifiedType(type.checkType); var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified; - if (constraint) { + if (constraint && constraint !== type.checkType) { var mapper = makeUnaryTypeMapper(type.root.checkType, constraint); var instantiated = getConditionalTypeInstantiation(type, combineTypeMappers(mapper, type.mapper)); if (!(instantiated.flags & 131072 /* Never */)) { @@ -37622,10 +37891,10 @@ var ts; commonFlags &= prop.flags; props = ts.appendIfUnique(props, prop); checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | - (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 64 /* ContainsPublic */ : 0) | - (modifiers & 16 /* Protected */ ? 128 /* ContainsProtected */ : 0) | - (modifiers & 8 /* Private */ ? 256 /* ContainsPrivate */ : 0) | - (modifiers & 32 /* Static */ ? 512 /* ContainsStatic */ : 0); + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 512 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 1024 /* ContainsStatic */ : 0); if (!isPrototypeProperty(prop)) { syntheticFlag = 2 /* SyntheticProperty */; } @@ -37649,39 +37918,38 @@ var ts; return props[0]; } var declarations; - var commonType; + var firstType; var nameType; var propTypes = []; - var first = true; - var commonValueDeclaration; + var firstValueDeclaration; var hasNonUniformValueDeclaration = false; for (var _b = 0, props_1 = props; _b < props_1.length; _b++) { var prop = props_1[_b]; - if (!commonValueDeclaration) { - commonValueDeclaration = prop.valueDeclaration; + if (!firstValueDeclaration) { + firstValueDeclaration = prop.valueDeclaration; } - else if (prop.valueDeclaration !== commonValueDeclaration) { + else if (prop.valueDeclaration !== firstValueDeclaration) { hasNonUniformValueDeclaration = true; } declarations = ts.addRange(declarations, prop.declarations); var type = getTypeOfSymbol(prop); - if (first) { - commonType = type; + if (!firstType) { + firstType = type; nameType = prop.nameType; - first = false; } - else { - if (type !== commonType) { - checkFlags |= 32 /* HasNonUniformType */; - } + else if (type !== firstType) { + checkFlags |= 32 /* HasNonUniformType */; + } + if (isLiteralType(type)) { + checkFlags |= 64 /* HasLiteralType */; } propTypes.push(type); } ts.addRange(propTypes, indexTypes); var result = createSymbol(4 /* Property */ | commonFlags, name, syntheticFlag | checkFlags); result.containingType = containingType; - if (!hasNonUniformValueDeclaration && commonValueDeclaration) { - result.valueDeclaration = commonValueDeclaration; + if (!hasNonUniformValueDeclaration && firstValueDeclaration) { + result.valueDeclaration = firstValueDeclaration; } result.declarations = declarations; result.nameType = nameType; @@ -37881,21 +38149,17 @@ var ts; var numTypeArguments = ts.length(typeArguments); if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) { var result = typeArguments ? typeArguments.slice() : []; - // Map an unsatisfied type parameter with a default type. - // If a type parameter does not have a default type, or if the default type - // is a forward reference, the empty object type is used. - var baseDefaultType_1 = getDefaultTypeArgumentType(isJavaScriptImplicitAny); - var circularityMapper = createTypeMapper(typeParameters, ts.map(typeParameters, function () { return baseDefaultType_1; })); + // Map invalid forward references in default types to the error type for (var i = numTypeArguments; i < numTypeParameters; i++) { - result[i] = instantiateType(getConstraintFromTypeParameter(typeParameters[i]) || baseDefaultType_1, circularityMapper); + result[i] = errorType; } + var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny); for (var i = numTypeArguments; i < numTypeParameters; i++) { - var mapper = createTypeMapper(typeParameters, result); var defaultType = getDefaultFromTypeParameter(typeParameters[i]); if (isJavaScriptImplicitAny && defaultType && isTypeIdenticalTo(defaultType, emptyObjectType)) { defaultType = anyType; } - result[i] = defaultType ? instantiateType(defaultType, mapper) : baseDefaultType_1; + result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType; } result.length = typeParameters.length; return result; @@ -37984,7 +38248,7 @@ var ts; var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); - var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 8192 /* RestParameter */); + var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 16384 /* RestParameter */); syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType; if (lastParamVariadicType) { // Replace the last parameter with a rest parameter. @@ -38855,7 +39119,7 @@ var ts; if (arity) { typeParameters = new Array(arity); for (var i = 0; i < arity; i++) { - var typeParameter = typeParameters[i] = createType(262144 /* TypeParameter */); + var typeParameter = typeParameters[i] = createTypeParameter(); if (i < maxLength) { var property = createSymbol(4 /* Property */ | (i >= minLength ? 16777216 /* Optional */ : 0), "" + i); property.type = typeParameter; @@ -38877,7 +39141,7 @@ var ts; type.instantiations.set(getTypeListId(type.typeParameters), type); type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(262144 /* TypeParameter */); + type.thisType = createTypeParameter(); type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; @@ -39378,8 +39642,13 @@ var ts; if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) { var type = getLateBoundSymbol(prop).nameType; if (!type && !ts.isKnownSymbol(prop)) { - var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); - type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + if (prop.escapedName === "default" /* Default */) { + type = getLiteralType("default"); + } + else { + var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration); + type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop)); + } } if (type && type.flags & include) { return type; @@ -39469,14 +39738,14 @@ var ts; } function getPropertyTypeForIndexType(objectType, indexType, accessNode, cacheSymbol, missingType) { var accessExpression = accessNode && accessNode.kind === 190 /* ElementAccessExpression */ ? accessNode : undefined; - var propName = isTypeUsableAsLateBoundName(indexType) - ? getLateBoundNameFromType(indexType) - : accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) - ? ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) - : accessNode && ts.isPropertyName(accessNode) + var propName = isTypeUsableAsLateBoundName(indexType) ? + getLateBoundNameFromType(indexType) : + accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ? + ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) : + accessNode && ts.isPropertyName(accessNode) ? // late bound names are handled in the first branch, so here we only need to handle normal names - ? ts.getPropertyNameForPropertyNameNode(accessNode) - : undefined; + ts.getPropertyNameForPropertyNameNode(accessNode) : + undefined; if (propName !== undefined) { var prop = getPropertyOfType(objectType, propName); if (prop) { @@ -39498,7 +39767,12 @@ var ts; if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) { if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; })) { var indexNode = getIndexNodeForAccessExpression(accessNode); - error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + if (isTupleType(objectType)) { + error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName)); + } + else { + error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } } return mapType(objectType, function (t) { return getRestTypeOfTupleType(t) || undefinedType; }); } @@ -39623,24 +39897,14 @@ var ts; // ((A & B) | C)[K1 | K2] -> ((A & B) | C)[K1] | ((A & B) | C)[K2] -> (A & B)[K1] | C[K1] | (A & B)[K2] | C[K2] -> (A[K1] & B[K1]) | C[K1] | (A[K2] & B[K2]) | C[K2] // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we - // construct the type Box. We do not further simplify the result because mapped types can be recursive - // and we might never terminate. + // construct the type Box. if (isGenericMappedType(objectType)) { - return type.simplified = substituteIndexedMappedType(objectType, type); - } - if (objectType.flags & 262144 /* TypeParameter */) { - var constraint = getConstraintOfTypeParameter(objectType); - if (constraint && isGenericMappedType(constraint)) { - return type.simplified = substituteIndexedMappedType(constraint, type); - } + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var templateMapper = combineTypeMappers(objectType.mapper, mapper); + return type.simplified = mapType(instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper), getSimplifiedType); } return type.simplified = type; } - function substituteIndexedMappedType(objectType, type) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var templateMapper = combineTypeMappers(objectType.mapper, mapper); - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); - } function getIndexedAccessType(objectType, indexType, accessNode, missingType) { if (missingType === void 0) { missingType = accessNode ? errorType : unknownType; } if (objectType === wildcardType || indexType === wildcardType) { @@ -39728,14 +39992,11 @@ var ts; if (checkType === wildcardType || extendsType === wildcardType) { return wildcardType; } - // If this is a distributive conditional type and the check type is generic we need to defer - // resolution of the conditional type such that a later instantiation will properly distribute - // over union types. - var isDeferred = root.isDistributive && maybeTypeOfKind(checkType, 63176704 /* Instantiable */); + var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */); var combinedMapper; if (root.inferTypeParameters) { var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */); - if (!isDeferred) { + if (!checkTypeInstantiable) { // We don't want inferences from constraints as they may cause us to eagerly resolve the // conditional type instead of deferring resolution. Also, we always want strict function // types rules (i.e. proper contravariance) for inferences. @@ -39743,28 +40004,30 @@ var ts; } combinedMapper = combineTypeMappers(mapper, context); } - if (!isDeferred) { - if (extendsType.flags & 3 /* AnyOrUnknown */) { + // Instantiate the extends type including inferences for 'infer T' type parameters + var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; + // We attempt to resolve the conditional type only when the check and extends types are non-generic + if (!checkTypeInstantiable && !maybeTypeOfKind(inferredExtendsType, 63176704 /* Instantiable */ | 134217728 /* GenericMappedType */)) { + if (inferredExtendsType.flags & 3 /* AnyOrUnknown */) { return instantiateType(root.trueType, mapper); } // Return union of trueType and falseType for 'any' since it matches anything if (checkType.flags & 1 /* Any */) { return getUnionType([instantiateType(root.trueType, combinedMapper || mapper), instantiateType(root.falseType, mapper)]); } - // Instantiate the extends type including inferences for 'infer T' type parameters - var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType; // Return falseType for a definitely false extends check. We check an instantations of the two // types with type parameters mapped to the wildcard type, the most permissive instantiations // possible (the wildcard type is assignable to and from all types). If those are not related, // then no instatiations will be and we can just return the false branch type. - if (!isTypeAssignableTo(getWildcardInstantiation(checkType), getWildcardInstantiation(inferredExtendsType))) { + if (!isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType))) { return instantiateType(root.falseType, mapper); } - // Return trueType for a definitely true extends check. The definitely assignable relation excludes - // type variable constraints from consideration. Without the definitely assignable relation, the type + // Return trueType for a definitely true extends check. We check instantiations of the two + // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter + // that has no constraint. This ensures that, for example, the type // type Foo = T extends { x: string } ? string : number - // would immediately resolve to 'string' instead of being deferred. - if (checkTypeRelatedTo(checkType, inferredExtendsType, definitelyAssignableRelation, /*errorNode*/ undefined)) { + // doesn't immediately resolve to 'string' instead of being deferred. + if (isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) { return instantiateType(root.trueType, combinedMapper || mapper); } } @@ -40313,12 +40576,17 @@ var ts; function createReplacementMapper(source, target, baseMapper) { return function (t) { return t === source ? target : baseMapper(t); }; } - function wildcardMapper(type) { + function permissiveMapper(type) { return type.flags & 262144 /* TypeParameter */ ? wildcardType : type; } + function getRestrictiveTypeParameter(tp) { + return !tp.constraint ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol)); + } + function restrictiveMapper(type) { + return type.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(type) : type; + } function cloneTypeParameter(typeParameter) { - var result = createType(262144 /* TypeParameter */); - result.symbol = typeParameter.symbol; + var result = createTypeParameter(typeParameter.symbol); result.target = typeParameter; return result; } @@ -40377,7 +40645,7 @@ var ts; } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (1024 /* Late */ | 4096 /* OptionalParameter */ | 8192 /* RestParameter */)); + var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (2048 /* Late */ | 8192 /* OptionalParameter */ | 16384 /* RestParameter */)); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -40649,9 +40917,13 @@ var ts; } return type; } - function getWildcardInstantiation(type) { + function getPermissiveInstantiation(type) { return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : - type.wildcardInstantiation || (type.wildcardInstantiation = instantiateType(type, wildcardMapper)); + type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper)); + } + function getRestrictiveInstantiation(type) { + return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type : + type.restrictiveInstantiation || (type.restrictiveInstantiation = instantiateType(type, restrictiveMapper)); } function instantiateIndexInfo(info, mapper) { return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration); @@ -40715,8 +40987,7 @@ var ts; } function hasContextSensitiveReturnExpression(node) { // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value. - var body = node.body; - return body.kind === 218 /* Block */ ? false : isContextSensitive(body); + return !!node.body && node.body.kind !== 218 /* Block */ && isContextSensitive(node.body); } function isContextSensitiveFunctionOrObjectLiteralMethod(func) { return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) && @@ -40833,7 +41104,7 @@ var ts; case 187 /* ArrayLiteralExpression */: return elaborateArrayLiteral(node, source, target, relation); case 268 /* JsxAttributes */: - return elaborateJsxAttributes(node, source, target, relation); + return elaborateJsxComponents(node, source, target, relation); case 197 /* ArrowFunction */: return elaborateArrowFunction(node, source, target, relation); } @@ -40974,8 +41245,117 @@ var ts; } }); } - function elaborateJsxAttributes(node, source, target, relation) { - return elaborateElementwise(generateJsxAttributes(node), source, target, relation); + function generateJsxChildren(node, getInvalidTextDiagnostic) { + var memberOffset, i, child, nameType, elem; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!ts.length(node.children)) + return [2 /*return*/]; + memberOffset = 0; + i = 0; + _a.label = 1; + case 1: + if (!(i < node.children.length)) return [3 /*break*/, 5]; + child = node.children[i]; + nameType = getLiteralType(i - memberOffset); + elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic); + if (!elem) return [3 /*break*/, 3]; + return [4 /*yield*/, elem]; + case 2: + _a.sent(); + return [3 /*break*/, 4]; + case 3: + memberOffset++; + _a.label = 4; + case 4: + i++; + return [3 /*break*/, 1]; + case 5: return [2 /*return*/]; + } + }); + } + function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) { + switch (child.kind) { + case 270 /* JsxExpression */: + // child is of the type of the expression + return { errorNode: child, innerExpression: child.expression, nameType: nameType }; + case 11 /* JsxText */: + if (child.containsOnlyWhiteSpaces) { + break; // Whitespace only jsx text isn't real jsx text + } + // child is a string + return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() }; + case 260 /* JsxElement */: + case 261 /* JsxSelfClosingElement */: + case 264 /* JsxFragment */: + // child is of type JSX.Element + return { errorNode: child, innerExpression: child, nameType: nameType }; + default: + return ts.Debug.assertNever(child, "Found invalid jsx child"); + } + } + function elaborateJsxComponents(node, source, target, relation) { + var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation); + var invalidTextDiagnostic; + if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) { + var containingElement = node.parent.parent; + var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName); + var childrenNameType = getLiteralType(childrenPropName); + var childrenTargetType = getIndexedAccessType(target, childrenNameType); + var validChildren = ts.filter(containingElement.children, function (i) { return !ts.isJsxText(i) || !i.containsOnlyWhiteSpaces; }); + if (!ts.length(validChildren)) { + return result; + } + var moreThanOneRealChildren = ts.length(validChildren) > 1; + var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType); + var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); }); + if (moreThanOneRealChildren) { + if (arrayLikeTargetParts !== neverType) { + var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */)); + result = elaborateElementwise(generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic), realSource, arrayLikeTargetParts, relation) || result; + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + // arity mismatch + result = true; + error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_a_single_child_of_type_1_but_multiple_children_were_provided, childrenPropName, typeToString(childrenTargetType)); + } + } + else { + if (nonArrayLikeTargetParts !== neverType) { + var child = validChildren[0]; + var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic); + if (elem_1) { + result = elaborateElementwise((function () { return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, elem_1]; + case 1: + _a.sent(); + return [2 /*return*/]; + } + }); })(), source, target, relation) || result; + } + } + else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) { + // arity mismatch + result = true; + error(containingElement.openingElement.tagName, ts.Diagnostics.This_JSX_tag_s_0_prop_expects_type_1_which_requires_multiple_children_but_only_a_single_child_was_provided, childrenPropName, typeToString(childrenTargetType)); + } + } + } + return result; + function getInvalidTextualChildDiagnostic() { + if (!invalidTextDiagnostic) { + var tagNameText = ts.getTextOfNode(node.parent.tagName); + var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); + var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName); + var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName)); + var diagnostic = ts.Diagnostics._0_components_don_t_accept_text_as_child_elements_Text_in_JSX_has_the_type_string_but_the_expected_type_of_1_is_2; + invalidTextDiagnostic = __assign({}, diagnostic, { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) }); + } + return invalidTextDiagnostic; + } } function generateLimitedTupleElements(node, target) { var len, i, elem, nameType; @@ -41228,7 +41608,7 @@ var ts; !t.numberIndexInfo; } function isEmptyObjectType(type) { - return type.flags & 524288 /* Object */ ? isEmptyResolvedType(resolveStructuredTypeMembers(type)) : + return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) : type.flags & 67108864 /* NonPrimitive */ ? true : type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) : type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) : @@ -41311,9 +41691,7 @@ var ts; return true; if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */) return true; - if (s & 8192 /* UniqueESSymbol */ || t & 8192 /* UniqueESSymbol */) - return false; - if (relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) { + if (relation === assignableRelation || relation === comparableRelation) { if (s & 1 /* Any */) return true; // Type number or any numeric literal type is assignable to any numeric enum type or any @@ -41483,7 +41861,7 @@ var ts; target = target.regularType; } if (source.flags & 33554432 /* Substitution */) { - source = relation === definitelyAssignableRelation ? source.typeVariable : source.substitute; + source = source.substitute; } if (target.flags & 33554432 /* Substitution */) { target = target.typeVariable; @@ -41658,9 +42036,9 @@ var ts; if (!noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) { return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny } - if (maybeTypeOfKind(target, 524288 /* Object */) && !(ts.getObjectFlags(target) & 512 /* ObjectLiteralPatternWithComputedProperties */)) { + if (isExcessPropertyCheckTarget(target)) { var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */); - if ((relation === assignableRelation || relation === definitelyAssignableRelation || relation === comparableRelation) && + if ((relation === assignableRelation || relation === comparableRelation) && (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) { return false; } @@ -41668,9 +42046,12 @@ var ts; // check excess properties against discriminant type only, not the entire union return hasExcessProperties(source, discriminant, /*discriminant*/ undefined, reportErrors); } - var _loop_6 = function (prop) { + var _loop_7 = function (prop) { if (shouldCheckAsExcessProperty(prop, source.symbol) && !isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) { if (reportErrors) { + // Report error in terms of object types in the target as those are the only ones + // we check in isKnownProperty. + var errorTarget = filterType(target, isExcessPropertyCheckTarget); // We know *exactly* where things went wrong when comparing the types. // Use this property as the error node as this will be more helpful in // reasoning about what went wrong. @@ -41680,7 +42061,7 @@ var ts; // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal. // However, using an object-literal error message will be very confusing to the users so we give different a message. // TODO: Spelling suggestions for excess jsx attributes (needs new diagnostic messages) - reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(target)); + reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(prop), typeToString(errorTarget)); } else { // use the property's value declaration if the property is assigned inside the literal itself @@ -41692,14 +42073,14 @@ var ts; errorNode = propDeclaration; var name = propDeclaration.name; if (ts.isIdentifier(name)) { - suggestion = getSuggestionForNonexistentProperty(name, target); + suggestion = getSuggestionForNonexistentProperty(name, errorTarget); } } if (suggestion !== undefined) { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(target), suggestion); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_but_0_does_not_exist_in_type_1_Did_you_mean_to_write_2, symbolToString(prop), typeToString(errorTarget), suggestion); } else { - reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(target)); + reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget)); } } } @@ -41708,9 +42089,9 @@ var ts; }; for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; - var state_2 = _loop_6(prop); - if (typeof state_2 === "object") - return state_2.value; + var state_3 = _loop_7(prop); + if (typeof state_3 === "object") + return state_3.value; } } return false; @@ -41747,7 +42128,8 @@ var ts; var bestMatchingType = findMatchingDiscriminantType(source, target) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || - findBestTypeForInvokable(source, target); + findBestTypeForInvokable(source, target) || + findMostOverlappyType(source, target); isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); } return 0 /* False */; @@ -41782,6 +42164,34 @@ var ts; return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; }); } } + function findMostOverlappyType(source, unionTarget) { + var bestMatch; + var matchingCount = 0; + for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) { + var target_1 = _a[_i]; + var overlap = getIntersectionType([getIndexType(source), getIndexType(target_1)]); + if (overlap.flags & 4194304 /* Index */) { + // perfect overlap of keys + bestMatch = target_1; + matchingCount = Infinity; + } + else if (overlap.flags & 1048576 /* Union */) { + // We only want to account for literal types otherwise. + // If we have a union of index types, it seems likely that we + // needed to elaborate between two generic mapped types anyway. + var len = ts.length(ts.filter(overlap.types, isUnitType)); + if (len >= matchingCount) { + bestMatch = target_1; + matchingCount = len; + } + } + else if (isUnitType(overlap) && 1 >= matchingCount) { + bestMatch = target_1; + matchingCount = 1; + } + } + return bestMatch; + } // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly function findMatchingDiscriminantType(source, target) { if (target.flags & 1048576 /* Union */) { @@ -41955,30 +42365,27 @@ var ts; } return result; } - function getConstraintForRelation(type) { - return relation === definitelyAssignableRelation ? undefined : getConstraintOfType(type); - } function structuredTypeRelatedTo(source, target, reportErrors, isIntersectionConstituent) { var flags = source.flags & target.flags; if (relation === identityRelation && !(flags & 524288 /* Object */)) { if (flags & 4194304 /* Index */) { return isRelatedTo(source.type, target.type, /*reportErrors*/ false); } - var result_2 = 0 /* False */; + var result_3 = 0 /* False */; if (flags & 8388608 /* IndexedAccess */) { - if (result_2 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { - return result_2; + if (result_3 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) { + return result_3; } } } if (flags & 16777216 /* Conditional */) { if (source.root.isDistributive === target.root.isDistributive) { - if (result_2 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_2 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { - return result_2; + if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + return result_3; } } } @@ -42027,24 +42434,23 @@ var ts; } // A type S is assignable to keyof T if S is assignable to keyof C, where C is the // simplified form of T or, if T doesn't simplify, the constraint of T. - if (relation !== definitelyAssignableRelation) { - var simplified = getSimplifiedType(target.type); - var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); - if (constraint) { - // We require Ternary.True here such that circular constraints don't cause - // false positives. For example, given 'T extends { [K in keyof T]: string }', - // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when - // related to other types. - if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { - return -1 /* True */; - } + var simplified = getSimplifiedType(target.type); + var constraint = simplified !== target.type ? simplified : getConstraintOfType(target.type); + if (constraint) { + // We require Ternary.True here such that circular constraints don't cause + // false positives. For example, given 'T extends { [K in keyof T]: string }', + // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when + // related to other types. + if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) { + return -1 /* True */; } } } else if (target.flags & 8388608 /* IndexedAccess */) { // A type S is related to a type T[K], where T and K aren't both type variables, if S is related to C, // where C is the base constraint of T[K] - if (relation !== identityRelation && !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { + if (relation !== identityRelation && + !(isGenericObjectType(target.objectType) && isGenericIndexType(target.indexType))) { var constraint = getBaseConstraintOfType(target); if (constraint && constraint !== target) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -42085,8 +42491,8 @@ var ts; return result; } } - var constraint = getConstraintForRelation(source); - if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 3 /* AnyOrUnknown */)) { + var constraint = getConstraintOfType(source); + if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) { // A type variable with no constraint is not related to the non-primitive object type. if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) { errorInfo = saveErrorInfo; @@ -42126,7 +42532,7 @@ var ts; } } } - else if (relation !== definitelyAssignableRelation) { + else { var distributiveConstraint = getConstraintOfDistributiveConditionalType(source); if (distributiveConstraint) { if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) { @@ -42145,7 +42551,7 @@ var ts; } else { // An empty object type is related to any mapped type that includes a '?' modifier. - if (isPartialMappedType(target) && !isGenericMappedType(source) && isEmptyObjectType(source)) { + if (isPartialMappedType(target) && isEmptyObjectType(source)) { return -1 /* True */; } if (isGenericMappedType(target)) { @@ -42157,9 +42563,6 @@ var ts; } return 0 /* False */; } - if (relation === definitelyAssignableRelation && isGenericMappedType(source)) { - return 0 /* False */; - } var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */); if (relation !== identityRelation) { source = getApparentType(source); @@ -42239,10 +42642,10 @@ var ts; var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) : getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target)); if (modifiersRelated) { - var result_3; - if (result_3 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { + var result_4; + if (result_4 = isRelatedTo(getConstraintTypeFromMappedType(target), getConstraintTypeFromMappedType(source), reportErrors)) { var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]); - return result_3 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); + return result_4 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors); } } return 0 /* False */; @@ -42252,10 +42655,10 @@ var ts; return propertiesIdenticalTo(source, target); } var requireOptionalProperties = relation === subtypeRelation && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source); - var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties); + var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false); if (unmatchedProperty) { if (reportErrors) { - var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties)); + var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false)); if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code && headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) { suppressNextError = true; // Retain top-level error for interface implementing issues, otherwise omit it @@ -42331,7 +42734,7 @@ var ts; var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { var hasDifferingDeclarations = sourceProp.valueDeclaration !== targetProp.valueDeclaration; - if (ts.getCheckFlags(sourceProp) & 256 /* ContainsPrivate */ && hasDifferingDeclarations) { + if (ts.getCheckFlags(sourceProp) & 512 /* ContainsPrivate */ && hasDifferingDeclarations) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); } @@ -43007,6 +43410,9 @@ var ts; function isTupleLikeType(type) { return isTupleType(type) || !!getPropertyOfType(type, "0"); } + function isArrayOrTupleLikeType(type) { + return isArrayLikeType(type) || isTupleLikeType(type); + } function getTupleElementType(type, index) { var propType = getTypeOfPropertyOfType(type, "" + index); if (propType) { @@ -43296,6 +43702,9 @@ var ts; // union includes empty object types (e.g. reducing {} | string to just {}). return getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */); } + if (type.flags & 2097152 /* Intersection */) { + return getIntersectionType(ts.sameMap(type.types, getWidenedType)); + } if (isArrayType(type) || isTupleType(type)) { return createTypeReference(type.target, ts.sameMap(type.typeArguments, getWidenedType)); } @@ -43382,6 +43791,10 @@ var ts; break; case 186 /* BindingElement */: diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type; + if (!noImplicitAny) { + // Don't issue a suggestion for binding elements since the codefix doesn't yet support them. + return; + } break; case 289 /* JSDocFunctionType */: error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString); @@ -43579,8 +43992,8 @@ var ts; inferTypes([inference], sourceType, templateType); return getTypeFromInference(inference); } - function getUnmatchedProperties(source, target, requireOptionalProperties) { - var properties, _i, properties_4, targetProp, sourceProp; + function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) { + var properties, _i, properties_4, targetProp, sourceProp, targetType, sourceType; return __generator(this, function (_a) { switch (_a.label) { case 0: @@ -43588,24 +44001,34 @@ var ts; _i = 0, properties_4 = properties; _a.label = 1; case 1: - if (!(_i < properties_4.length)) return [3 /*break*/, 4]; + if (!(_i < properties_4.length)) return [3 /*break*/, 6]; targetProp = properties_4[_i]; - if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 3]; + if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */))) return [3 /*break*/, 5]; sourceProp = getPropertyOfType(source, targetProp.escapedName); if (!!sourceProp) return [3 /*break*/, 3]; return [4 /*yield*/, targetProp]; case 2: _a.sent(); - _a.label = 3; + return [3 /*break*/, 5]; case 3: + if (!matchDiscriminantProperties) return [3 /*break*/, 5]; + targetType = getTypeOfSymbol(targetProp); + if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5]; + sourceType = getTypeOfSymbol(sourceProp); + if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5]; + return [4 /*yield*/, targetProp]; + case 4: + _a.sent(); + _a.label = 5; + case 5: _i++; return [3 /*break*/, 1]; - case 4: return [2 /*return*/]; + case 6: return [2 /*return*/]; } }); } - function getUnmatchedProperty(source, target, requireOptionalProperties) { - return getUnmatchedProperties(source, target, requireOptionalProperties).next().value; + function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) { + return getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next().value; } function tupleTypesDefinitelyUnrelated(source, target) { return target.target.minLength > source.target.minLength || @@ -43615,7 +44038,8 @@ var ts; // Two tuple types with incompatible arities are definitely unrelated. // Two object types that each have a property that is unmatched in the other are definitely unrelated. return isTupleType(source) && isTupleType(target) && tupleTypesDefinitelyUnrelated(source, target) || - !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false) && !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false); + !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) && + !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true); } function getTypeFromInference(inference) { return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : @@ -44220,48 +44644,31 @@ var ts; // occurring in an apparent type position with '@' because the control flow type // of such nodes may be based on the apparent type instead of the declared type. function getFlowCacheKey(node) { - if (node.kind === 72 /* Identifier */) { - var symbol = getResolvedSymbol(node); - return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; - } - if (node.kind === 100 /* ThisKeyword */) { - return "0"; - } - if (node.kind === 189 /* PropertyAccessExpression */) { - var key = getFlowCacheKey(node.expression); - return key && key + "." + ts.idText(node.name); - } - if (node.kind === 186 /* BindingElement */) { - var container = node.parent.parent; - var key = container.kind === 186 /* BindingElement */ ? getFlowCacheKey(container) : (container.initializer && getFlowCacheKey(container.initializer)); - var text = getBindingElementNameText(node); - var result = key && text && (key + "." + text); - return result; + switch (node.kind) { + case 72 /* Identifier */: + var symbol = getResolvedSymbol(node); + return symbol !== unknownSymbol ? (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined; + case 100 /* ThisKeyword */: + return "0"; + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + return getFlowCacheKey(node.expression); + case 189 /* PropertyAccessExpression */: + case 190 /* ElementAccessExpression */: + var propName = getAccessedPropertyName(node); + if (propName !== undefined) { + var key = getFlowCacheKey(node.expression); + return key && key + "." + propName; + } } return undefined; } - function getBindingElementNameText(element) { - var parent = element.parent; - if (parent.kind === 184 /* ObjectBindingPattern */) { - var name = element.propertyName || element.name; - switch (name.kind) { - case 72 /* Identifier */: - return ts.idText(name); - case 149 /* ComputedPropertyName */: - return ts.isStringOrNumericLiteralLike(name.expression) ? name.expression.text : undefined; - case 10 /* StringLiteral */: - case 8 /* NumericLiteral */: - return name.text; - default: - // Per types, array and object binding patterns remain, however they should never be present if propertyName is not defined - ts.Debug.fail("Unexpected name kind for binding element name"); - } - } - else { - return "" + parent.elements.indexOf(element); - } - } function isMatchingReference(source, target) { + switch (target.kind) { + case 195 /* ParenthesizedExpression */: + case 213 /* NonNullExpression */: + return isMatchingReference(source, target.expression); + } switch (source.kind) { case 72 /* Identifier */: return target.kind === 72 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || @@ -44271,34 +44678,24 @@ var ts; return target.kind === 100 /* ThisKeyword */; case 98 /* SuperKeyword */: return target.kind === 98 /* SuperKeyword */; + case 213 /* NonNullExpression */: + case 195 /* ParenthesizedExpression */: + return isMatchingReference(source.expression, target); case 189 /* PropertyAccessExpression */: case 190 /* ElementAccessExpression */: - return (ts.isPropertyAccessExpression(target) || ts.isElementAccessExpression(target)) && + return ts.isAccessExpression(target) && getAccessedPropertyName(source) === getAccessedPropertyName(target) && isMatchingReference(source.expression, target.expression); - case 186 /* BindingElement */: - if (target.kind !== 189 /* PropertyAccessExpression */) - return false; - var t = target; - if (t.name.escapedText !== getBindingElementNameText(source)) - return false; - if (source.parent.parent.kind === 186 /* BindingElement */ && isMatchingReference(source.parent.parent, t.expression)) { - return true; - } - if (source.parent.parent.kind === 237 /* VariableDeclaration */) { - var maybeId = source.parent.parent.initializer; - return !!maybeId && isMatchingReference(maybeId, t.expression); - } } return false; } function getAccessedPropertyName(access) { - return ts.isPropertyAccessExpression(access) ? access.name.escapedText : + return access.kind === 189 /* PropertyAccessExpression */ ? access.name.escapedText : ts.isStringLiteral(access.argumentExpression) || ts.isNumericLiteral(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) : undefined; } function containsMatchingReference(source, target) { - while (source.kind === 189 /* PropertyAccessExpression */) { + while (ts.isAccessExpression(source)) { source = source.expression; if (isMatchingReference(source, target)) { return true; @@ -44311,42 +44708,37 @@ var ts; // a possible discriminant if its type differs in the constituents of containing union type, and if every // choice is a unit type or a union of unit types. function containsMatchingReferenceDiscriminant(source, target) { - return target.kind === 189 /* PropertyAccessExpression */ && + var name; + return ts.isAccessExpression(target) && containsMatchingReference(source, target.expression) && - isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), target.name.escapedText); + (name = getAccessedPropertyName(target)) !== undefined && + isDiscriminantProperty(getDeclaredTypeOfReference(target.expression), name); } function getDeclaredTypeOfReference(expr) { if (expr.kind === 72 /* Identifier */) { return getTypeOfSymbol(getResolvedSymbol(expr)); } - if (expr.kind === 189 /* PropertyAccessExpression */) { + if (ts.isAccessExpression(expr)) { var type = getDeclaredTypeOfReference(expr.expression); - return type && getTypeOfPropertyOfType(type, expr.name.escapedText); + if (type) { + var propName = getAccessedPropertyName(expr); + return propName !== undefined ? getTypeOfPropertyOfType(type, propName) : undefined; + } } return undefined; } function isDiscriminantType(type) { - if (type.flags & 1048576 /* Union */) { - if (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */)) { - return true; - } - var combined = 0; - for (var _i = 0, _a = type.types; _i < _a.length; _i++) { - var t = _a[_i]; - combined |= t.flags; - } - if (combined & 109440 /* Unit */ && !(combined & 63176704 /* Instantiable */)) { - return true; - } - } - return false; + return !!(type.flags & 1048576 /* Union */ && + (type.flags & (16 /* Boolean */ | 1024 /* EnumLiteral */) || !isGenericIndexType(type))); } function isDiscriminantProperty(type, name) { if (type && type.flags & 1048576 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !!(prop.checkFlags & 32 /* HasNonUniformType */) && isDiscriminantType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = + (prop.checkFlags & 96 /* Discriminant */) === 96 /* Discriminant */ && + isDiscriminantType(getTypeOfSymbol(prop)); } return !!prop.isDiscriminantProperty; } @@ -45205,25 +45597,23 @@ var ts; return result; } function isMatchingReferenceDiscriminant(expr, computedType) { - if (!(computedType.flags & 1048576 /* Union */) || - expr.kind !== 189 /* PropertyAccessExpression */ && expr.kind !== 190 /* ElementAccessExpression */) { + if (!(computedType.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) { return false; } - var access = expr; - var name = getAccessedPropertyName(access); - if (!name) { + var name = getAccessedPropertyName(expr); + if (name === undefined) { return false; } - return isMatchingReference(reference, access.expression) && isDiscriminantProperty(computedType, name); + return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(computedType, name); } function narrowTypeByDiscriminant(type, access, narrowType) { var propName = getAccessedPropertyName(access); - if (!propName) { + if (propName === undefined) { return type; } var propType = getTypeOfPropertyOfType(type, propName); var narrowedPropType = propType && narrowType(propType); - return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOfType(t, propName), narrowedPropType); }); + return propType === narrowedPropType ? type : filterType(type, function (t) { return isTypeComparableTo(getTypeOfPropertyOrIndexSignature(t, propName), narrowedPropType); }); } function narrowTypeByTruthiness(type, expr, assumeTrue) { if (isMatchingReference(reference, expr)) { @@ -45568,9 +45958,8 @@ var ts; } else { var invokedExpression = ts.skipParentheses(callExpression.expression); - if (invokedExpression.kind === 190 /* ElementAccessExpression */ || invokedExpression.kind === 189 /* PropertyAccessExpression */) { - var accessExpression = invokedExpression; - var possibleReference = ts.skipParentheses(accessExpression.expression); + if (ts.isAccessExpression(invokedExpression)) { + var possibleReference = ts.skipParentheses(invokedExpression.expression); if (isMatchingReference(reference, possibleReference)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } @@ -45987,7 +46376,7 @@ var ts; } function checkThisBeforeSuper(node, container, diagnosticMessage) { var containingClassDecl = container.parent; - var baseTypeNode = ts.getEffectiveBaseTypeNode(containingClassDecl); + var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl); // If a containing class does not have extends clause or the class extends null // skip checking whether super statement is called before "this" accessing. if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) { @@ -46308,7 +46697,7 @@ var ts; } // at this point the only legal case for parent is ClassLikeDeclaration var classLikeDeclaration = container.parent; - if (!ts.getEffectiveBaseTypeNode(classLikeDeclaration)) { + if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) { error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); return errorType; } @@ -46465,6 +46854,30 @@ var ts; tryGetTypeAtPosition(contextualSignature, index); } } + function getContextualTypeForVariableLikeDeclaration(declaration) { + var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); + if (typeNode) { + return getTypeFromTypeNode(typeNode); + } + switch (declaration.kind) { + case 151 /* Parameter */: + return getContextuallyTypedParameterType(declaration); + case 186 /* BindingElement */: + return getContextualTypeForBindingElement(declaration); + // By default, do nothing and return undefined - only parameters and binding elements have context implied by a parent + } + } + function getContextualTypeForBindingElement(declaration) { + var parentDeclaration = declaration.parent.parent; + var name = declaration.propertyName || declaration.name; + var parentType = getContextualTypeForVariableLikeDeclaration(parentDeclaration); + if (parentType && !ts.isBindingPattern(name)) { + var text = ts.getTextOfPropertyName(name); + if (text !== undefined) { + return getTypeOfPropertyOfType(parentType, text); + } + } + } // In a variable, parameter or property declaration with a type annotation, // the contextual type of an initializer expression is the type of the variable, parameter or property. // Otherwise, in a parameter declaration of a contextually typed function expression, @@ -46476,32 +46889,13 @@ var ts; function getContextualTypeForInitializerExpression(node) { var declaration = node.parent; if (ts.hasInitializer(declaration) && node === declaration.initializer) { - var typeNode = ts.getEffectiveTypeAnnotationNode(declaration); - if (typeNode) { - return getTypeFromTypeNode(typeNode); + var result = getContextualTypeForVariableLikeDeclaration(declaration); + if (result) { + return result; } - if (declaration.kind === 151 /* Parameter */) { - var type = getContextuallyTypedParameterType(declaration); - if (type) { - return type; - } - } - if (ts.isBindingPattern(declaration.name)) { + if (ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false); } - if (ts.isBindingPattern(declaration.parent)) { - var parentDeclaration = declaration.parent.parent; - var name = declaration.propertyName || declaration.name; - if (parentDeclaration.kind !== 186 /* BindingElement */) { - var parentTypeNode = ts.getEffectiveTypeAnnotationNode(parentDeclaration); - if (parentTypeNode && !ts.isBindingPattern(name)) { - var text = ts.getTextOfPropertyName(name); - if (text) { - return getTypeOfPropertyOfType(getTypeFromTypeNode(parentTypeNode), text); - } - } - } - } } return undefined; } @@ -46754,18 +47148,30 @@ var ts; var conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } - function getContextualTypeForChildJsxExpression(node) { + function getContextualTypeForChildJsxExpression(node, child) { var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName); // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty) var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node)); - return attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "" ? getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName) : undefined; + if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) { + return undefined; + } + var childIndex = node.children.indexOf(child); + var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName); + return childFieldType && mapType(childFieldType, function (t) { + if (isArrayLikeType(t)) { + return getIndexedAccessType(t, getLiteralType(childIndex)); + } + else { + return t; + } + }, /*noReductions*/ true); } function getContextualTypeForJsxExpression(node) { var exprParent = node.parent; return ts.isJsxAttributeLike(exprParent) ? getContextualType(node) : ts.isJsxElement(exprParent) - ? getContextualTypeForChildJsxExpression(exprParent) + ? getContextualTypeForChildJsxExpression(exprParent, node) : undefined; } function getContextualTypeForJsxAttribute(attribute) { @@ -46932,6 +47338,27 @@ var ts; return propsType; } function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) { + if (sig.unionSignatures) { + // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input + // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature, + // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur + // for a union signature). It's an unfortunate quirk of looking in the output of the signature for the type we want to use for the input. + // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane. + var results = []; + for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) { + var signature = _a[_i]; + var instance = getReturnTypeOfSignature(signature); + if (isTypeAny(instance)) { + return instance; + } + var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation); + if (!propType) { + return; + } + results.push(propType); + } + return getIntersectionType(results); + } var instanceType = getReturnTypeOfSignature(sig); return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation); } @@ -47323,7 +47750,7 @@ var ts; var nameType = computedNameType && computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */ ? computedNameType : undefined; var prop = nameType ? - createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 1024 /* Late */) : + createSymbol(4 /* Property */ | member.flags, getLateBoundNameFromType(nameType), 2048 /* Late */) : createSymbol(4 /* Property */ | member.flags, member.escapedName); if (nameType) { prop.nameType = nameType; @@ -47923,7 +48350,7 @@ var ts; return true; } } - else if (targetType.flags & 3145728 /* UnionOrIntersection */) { + else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) { for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) { var t = _a[_i]; if (isKnownProperty(t, name, isComparingJsxAttributes)) { @@ -47931,12 +48358,14 @@ var ts; } } } - else if (targetType.flags & 16777216 /* Conditional */) { - return isKnownProperty(targetType.root.trueType, name, isComparingJsxAttributes) || - isKnownProperty(targetType.root.falseType, name, isComparingJsxAttributes); - } return false; } + function isExcessPropertyCheckTarget(type) { + return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) || + type.flags & 67108864 /* NonPrimitive */ || + type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) || + type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget)); + } function checkJsxExpression(node, checkMode) { if (node.expression) { var type = checkExpression(node.expression, checkMode); @@ -47977,7 +48406,7 @@ var ts; function checkPropertyAccessibility(node, isSuper, type, prop) { var flags = ts.getDeclarationModifierFlagsFromSymbol(prop); var errorNode = node.kind === 148 /* QualifiedName */ ? node.right : node.kind === 183 /* ImportType */ ? node : node.name; - if (ts.getCheckFlags(prop) & 256 /* ContainsPrivate */) { + if (ts.getCheckFlags(prop) & 512 /* ContainsPrivate */) { // Synthetic property with private constituent property error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); return false; @@ -48341,7 +48770,7 @@ var ts; } } function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) { - if (nodeForCheckWriteOnly && isInTypeQuery(nodeForCheckWriteOnly) || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { + if (!prop || !(prop.flags & 106500 /* ClassMember */) || !prop.valueDeclaration || !ts.hasModifier(prop.valueDeclaration, 8 /* Private */)) { return; } if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */))) { @@ -48367,7 +48796,7 @@ var ts; } } function isValidPropertyAccessForCompletions(node, type, property) { - return isValidPropertyAccessWithType(node, node.kind !== 183 /* ImportType */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) + return isValidPropertyAccessWithType(node, node.kind === 189 /* PropertyAccessExpression */ && node.expression.kind === 98 /* SuperKeyword */, property.escapedName, type) && (!(property.flags & 8192 /* Method */) || isValidMethodAccess(property, type)); } function isValidMethodAccess(method, actualThisType) { @@ -49052,15 +49481,32 @@ var ts; return related ? addRelatedInfo(diagnostic, related) : diagnostic; } function getTypeArgumentArityError(node, signatures, typeArguments) { - var min = Infinity; - var max = -Infinity; + var argCount = typeArguments.length; + // No overloads exist + if (signatures.length === 1) { + var sig = signatures[0]; + var min_1 = getMinTypeArgumentCount(sig.typeParameters); + var max = ts.length(sig.typeParameters); + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, min_1 < max ? min_1 + "-" + max : min_1, argCount); + } + // Overloads exist + var belowArgCount = -Infinity; + var aboveArgCount = Infinity; for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { var sig = signatures_5[_i]; - min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); - max = Math.max(max, ts.length(sig.typeParameters)); + var min_2 = getMinTypeArgumentCount(sig.typeParameters); + var max = ts.length(sig.typeParameters); + if (min_2 > argCount) { + aboveArgCount = Math.min(aboveArgCount, min_2); + } + else if (max < argCount) { + belowArgCount = Math.max(belowArgCount, max); + } } - var paramCount = min === max ? min : min + "-" + max; - return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, paramCount, typeArguments.length); + if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) { + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount); + } + return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount); } function resolveCall(node, signatures, candidatesOutArray, isForSignatureHelp, fallbackError) { var isTaggedTemplate = node.kind === 193 /* TaggedTemplateExpression */; @@ -49289,7 +49735,7 @@ var ts; } var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; - var _loop_7 = function (i) { + var _loop_8 = function (i) { var symbols = ts.mapDefined(candidates, function (_a) { var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; return hasRestParameter ? @@ -49300,7 +49746,7 @@ var ts; parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { - _loop_7(i); + _loop_8(i); } var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); var hasRestParameter = restParameterSymbols.length !== 0; @@ -49457,7 +49903,7 @@ var ts; */ function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) { // We exclude union types because we may have a union of function types that happen to have no common signatures. - return isTypeAny(funcType) || isTypeAny(apparentFuncType) && funcType.flags & 262144 /* TypeParameter */ || + return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType); } function resolveNewExpression(node, candidatesOutArray, isForSignatureHelp) { @@ -49965,6 +50411,7 @@ var ts; if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); + newSymbol.nameType = getLiteralType("default"); newSymbol.target = resolveSymbol(symbol); memberTable.set("default" /* Default */, newSymbol); var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); @@ -50958,20 +51405,18 @@ var ts; if (rightIsThis === void 0) { rightIsThis = false; } if (property.kind === 275 /* PropertyAssignment */ || property.kind === 276 /* ShorthandPropertyAssignment */) { var name = property.name; - if (name.kind === 149 /* ComputedPropertyName */) { - checkComputedPropertyName(name); - } - if (isComputedNonLiteralName(name)) { - return undefined; - } - var type = getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis); - if (type) { - // non-shorthand property assignments should always have initializers - return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); - } - else { - error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name)); + var text = ts.getTextOfPropertyName(name); + if (text) { + var prop = getPropertyOfType(objectLiteralType, text); + if (prop) { + markPropertyAsReferenced(prop, property, rightIsThis); + checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); + } } + var exprType = getLiteralTypeFromPropertyName(name); + var elementType = getIndexedAccessType(objectLiteralType, exprType, name); + var type = getFlowTypeOfDestructuring(property, elementType); + return checkDestructuringAssignment(property.kind === 276 /* ShorthandPropertyAssignment */ ? property : property.initializer, type); } else if (property.kind === 277 /* SpreadAssignment */) { if (languageVersion < 6 /* ESNext */) { @@ -50991,23 +51436,6 @@ var ts; error(property, ts.Diagnostics.Property_assignment_expected); } } - function getTypeOfObjectLiteralDestructuringProperty(objectLiteralType, name, property, rightIsThis) { - if (isTypeAny(objectLiteralType)) { - return objectLiteralType; - } - var type; - var text = ts.getTextOfPropertyName(name); - if (text) { // TODO: GH#26379 - var prop = getPropertyOfType(objectLiteralType, text); - if (prop) { - markPropertyAsReferenced(prop, property, rightIsThis); - checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop); - type = getTypeOfSymbol(prop); - } - type = type || (isNumericLiteralName(text) ? getIndexTypeOfType(objectLiteralType, 1 /* Number */) : undefined); - } - return type || getIndexTypeOfType(objectLiteralType, 0 /* String */); - } function checkArrayLiteralAssignment(node, sourceType, checkMode) { var elements = node.elements; if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) { @@ -51027,39 +51455,30 @@ var ts; var element = elements[elementIndex]; if (element.kind !== 210 /* OmittedExpression */) { if (element.kind !== 208 /* SpreadElement */) { - var propName = "" + elementIndex; - var type = isTypeAny(sourceType) ? sourceType : - everyType(sourceType, isTupleLikeType) ? getTupleElementType(sourceType, elementIndex) : - elementType; - if (type) { + var indexType = getLiteralType(elementIndex); + if (isArrayLikeType(sourceType)) { + // We create a synthetic expression so that getIndexedAccessType doesn't get confused + // when the element is a SyntaxKind.ElementAccessExpression. + var elementType_2 = getIndexedAccessType(sourceType, indexType, createSyntheticExpression(element, indexType)); + var type = getFlowTypeOfDestructuring(element, elementType_2); return checkDestructuringAssignment(element, type, checkMode); } - // We still need to check element expression here because we may need to set appropriate flag on the expression - // such as NodeCheckFlags.LexicalThis on "this"expression. - checkExpression(element); - if (isTupleType(sourceType)) { - error(element, ts.Diagnostics.Tuple_type_0_with_length_1_cannot_be_assigned_to_tuple_with_length_2, typeToString(sourceType), getTypeReferenceArity(sourceType), elements.length); - } - else { - error(element, ts.Diagnostics.Type_0_has_no_property_1, typeToString(sourceType), propName); - } + return checkDestructuringAssignment(element, elementType, checkMode); + } + if (elementIndex < elements.length - 1) { + error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } else { - if (elementIndex < elements.length - 1) { - error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); + var restExpression = element.expression; + if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { + error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } else { - var restExpression = element.expression; - if (restExpression.kind === 204 /* BinaryExpression */ && restExpression.operatorToken.kind === 59 /* EqualsToken */) { - error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); - } - else { - checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); - var type = everyType(sourceType, isTupleType) ? - mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : - createArrayType(elementType); - return checkDestructuringAssignment(restExpression, type, checkMode); - } + checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); + var type = everyType(sourceType, isTupleType) ? + mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) : + createArrayType(elementType); + return checkDestructuringAssignment(restExpression, type, checkMode); } } } @@ -51580,7 +51999,8 @@ var ts; var type = getTypeOfExpression(initializer, /*cache*/ true); var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) || - isTypeAssertion(initializer) ? type : getWidenedLiteralType(type); + isTypeAssertion(initializer) || + isLiteralOfContextualType(type, getContextualType(initializer)) ? type : getWidenedLiteralType(type); if (ts.isInJSFile(declaration)) { if (widened.flags & 98304 /* Nullable */) { reportImplicitAny(declaration, anyType); @@ -52263,7 +52683,7 @@ var ts; // Constructors of classes with no extends clause may not contain super calls, whereas // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; - if (ts.getEffectiveBaseTypeNode(containingClassDecl)) { + if (ts.getClassExtendsHeritageElement(containingClassDecl)) { captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); @@ -52457,7 +52877,6 @@ var ts; break; } } - checkGrammarForDisallowedTrailingComma(node.elementTypes); ts.forEach(node.elementTypes, checkSourceElement); } function checkUnionOrIntersectionType(node) { @@ -52826,10 +53245,10 @@ var ts; case 248 /* ImportEqualsDeclaration */: case 251 /* NamespaceImport */: case 250 /* ImportClause */: - var result_4 = 0 /* None */; + var result_5 = 0 /* None */; var target = resolveAlias(getSymbolOfNode(d)); - ts.forEach(target.declarations, function (d) { result_4 |= getDeclarationSpaces(d); }); - return result_4; + ts.forEach(target.declarations, function (d) { result_5 |= getDeclarationSpaces(d); }); + return result_5; case 237 /* VariableDeclaration */: case 186 /* BindingElement */: case 239 /* FunctionDeclaration */: @@ -53317,7 +53736,12 @@ var ts; return; } if (!containsArgumentsReference(decl)) { - error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name.kind === 148 /* QualifiedName */ ? node.name.right : node.name)); + if (ts.isQualifiedName(node.name)) { + error(node.name, ts.Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, ts.entityNameToString(node.name), ts.entityNameToString(node.name.left)); + } + else { + error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name)); + } } else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node && node.typeExpression && node.typeExpression.type && @@ -54855,6 +55279,7 @@ var ts; if (produceDiagnostics) { if (node.default) { seenDefault = true; + checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i); } else if (seenDefault) { error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters); @@ -54868,6 +55293,23 @@ var ts; } } } + /** Check that type parameter defaults only reference previously declared type parameters */ + function checkTypeParametersNotReferenced(root, typeParameters, index) { + visit(root); + function visit(node) { + if (node.kind === 164 /* TypeReference */) { + var type = getTypeFromTypeReference(node); + if (type.flags & 262144 /* TypeParameter */) { + for (var i = index; i < typeParameters.length; i++) { + if (type.symbol === getSymbolOfNode(typeParameters[i])) { + error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters); + } + } + } + } + ts.forEachChild(node, visit); + } + } /** Check that type parameter lists are identical across multiple declarations */ function checkTypeParameterListsIdentical(symbol) { if (symbol.declarations.length === 1) { @@ -55058,7 +55500,7 @@ var ts; function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible var issuedMemberError = false; - var _loop_8 = function (member) { + var _loop_9 = function (member) { if (ts.hasStaticModifier(member)) { return "continue"; } @@ -55077,7 +55519,7 @@ var ts; }; for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; - _loop_8(member); + _loop_9(member); } if (!issuedMemberError) { // check again with diagnostics to generate a less-specific error @@ -55351,7 +55793,7 @@ var ts; return 0; } else if (isConstEnum) { - error(initializer, ts.Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values); } else if (member.parent.flags & 4194304 /* Ambient */) { error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression); @@ -57433,7 +57875,7 @@ var ts; isLateBound: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration); var symbol = node && getSymbolOfNode(node); - return !!(symbol && ts.getCheckFlags(symbol) & 1024 /* Late */); + return !!(symbol && ts.getCheckFlags(symbol) & 2048 /* Late */); }, getJsxFactoryEntity: function (location) { return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity; }, getAllAccessorDeclarations: function (accessor) { @@ -58025,9 +58467,6 @@ var ts; if (!(parameter.flags & 4194304 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070 checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma); } - if (ts.isBindingPattern(parameter.name)) { - return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); - } if (parameter.questionToken) { return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional); } @@ -59013,9 +59452,6 @@ var ts; JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes"; // tslint:enable variable-name })(JsxNames || (JsxNames = {})); - function typeIsLiteralType(type) { - return !!(type.flags & 2944 /* Literal */); - } })(ts || (ts = {})); var ts; (function (ts) { @@ -64579,15 +65015,19 @@ var ts; // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M]) var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/; var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/; + function getLineInfo(text, lineStarts) { + return { + getLineCount: function () { return lineStarts.length; }, + getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); } + }; + } + ts.getLineInfo = getLineInfo; /** * Tries to find the sourceMappingURL comment at the end of a file. - * @param text The source text of the file. - * @param lineStarts The line starts of the file. */ - function tryGetSourceMappingURL(text, lineStarts) { - if (lineStarts === void 0) { lineStarts = ts.computeLineStarts(text); } - for (var index = lineStarts.length - 1; index >= 0; index--) { - var line = text.substring(lineStarts[index], lineStarts[index + 1]); + function tryGetSourceMappingURL(lineInfo) { + for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) { + var line = lineInfo.getLineText(index); var comment = sourceMapCommentRegExp.exec(line); if (comment) { return comment[1]; @@ -64831,7 +65271,10 @@ var ts; && left.sourcePosition === right.sourcePosition; } function compareSourcePositions(left, right) { - return ts.compareValues(left.sourceIndex, right.sourceIndex); + // Compares sourcePosition without comparing sourceIndex + // since the mappings are grouped by sourceIndex + ts.Debug.assert(left.sourceIndex === right.sourceIndex); + return ts.compareValues(left.sourcePosition, right.sourcePosition); } function compareGeneratedPositions(left, right) { return ts.compareValues(left.generatedPosition, right.generatedPosition); @@ -64846,11 +65289,9 @@ var ts; var mapDirectory = ts.getDirectoryPath(mapPath); var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory; var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory); - var generatedCanonicalFilePath = host.getCanonicalFileName(generatedAbsoluteFilePath); - var generatedFile = host.getSourceFileLike(generatedCanonicalFilePath); + var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath); var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); }); - var sourceFileCanonicalPaths = sourceFileAbsolutePaths.map(function (source) { return host.getCanonicalFileName(source); }); - var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileCanonicalPaths.map(function (source, i) { return [source, i]; })); + var sourceToSourceIndexMap = ts.createMapFromEntries(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; })); var decodedMappings; var generatedMappings; var sourceMappings; @@ -64860,16 +65301,15 @@ var ts; }; function processMapping(mapping) { var generatedPosition = generatedFile !== undefined - ? ts.getPositionOfLineAndCharacterWithEdits(generatedFile, mapping.generatedLine, mapping.generatedCharacter) + ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true) : -1; var source; var sourcePosition; if (isSourceMapping(mapping)) { - var sourceFilePath = sourceFileCanonicalPaths[mapping.sourceIndex]; - var sourceFile = host.getSourceFileLike(sourceFilePath); + var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]); source = map.sources[mapping.sourceIndex]; sourcePosition = sourceFile !== undefined - ? ts.getPositionOfLineAndCharacterWithEdits(sourceFile, mapping.sourceLine, mapping.sourceCharacter) + ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true) : -1; } return { @@ -67287,6 +67727,7 @@ var ts; switch (node.literal.kind) { case 10 /* StringLiteral */: return ts.createIdentifier("String"); + case 202 /* PrefixUnaryExpression */: case 8 /* NumericLiteral */: return ts.createIdentifier("Number"); case 9 /* BigIntLiteral */: @@ -71057,7 +71498,7 @@ var ts; if (node.name) { enableSubstitutionsForBlockScopedBindings(); } - var extendsClauseElement = ts.getEffectiveBaseTypeNode(node); + var extendsClauseElement = ts.getClassExtendsHeritageElement(node); var classFunction = ts.createFunctionExpression( /*modifiers*/ undefined, /*asteriskToken*/ undefined, @@ -71466,7 +71907,7 @@ var ts; * synthesized call to `super` */ function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { - return node && node.dotDotDotToken && node.name.kind === 72 /* Identifier */ && !inConstructorWithSynthesizedSuper; + return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper); } /** * Adds statements to the body of a function-like node if it contains a rest parameter. @@ -71483,10 +71924,10 @@ var ts; return; } // `declarationName` is the name of the local declaration for the parameter. - var declarationName = ts.getMutableClone(parameter.name); + var declarationName = parameter.name.kind === 72 /* Identifier */ ? ts.getMutableClone(parameter.name) : ts.createTempVariable(/*recordTempVariable*/ undefined); ts.setEmitFlags(declarationName, 48 /* NoSourceMap */); // `expressionName` is the name of the parameter used in expressions. - var expressionName = ts.getSynthesizedClone(parameter.name); + var expressionName = parameter.name.kind === 72 /* Identifier */ ? ts.getSynthesizedClone(parameter.name) : declarationName; var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; @@ -71510,6 +71951,11 @@ var ts; ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */); ts.startOnNewLine(forStatement); statements.push(forStatement); + if (parameter.name.kind !== 72 /* Identifier */) { + // do the actual destructuring of the rest parameter if necessary + statements.push(ts.setEmitFlags(ts.setTextRange(ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */)); + } } /** * Adds a statement to capture the `this` of a function declaration if it is needed. @@ -79745,6 +80191,7 @@ var ts; case 241 /* InterfaceDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; break; + case 166 /* ConstructorType */: case 161 /* ConstructSignature */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; break; @@ -79763,6 +80210,7 @@ var ts; diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; } break; + case 165 /* FunctionType */: case 239 /* FunctionDeclaration */: diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; break; @@ -80340,7 +80788,10 @@ var ts; if (!ts.isLateVisibilityPaintedStatement(i)) { return ts.Debug.fail("Late replaced statement was found which is not handled by the declaration transformer!: " + (ts.SyntaxKind ? ts.SyntaxKind[i.kind] : i.kind)); } + var priorNeedsDeclare = needsDeclare; + needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit); var result = transformTopLevelDeclaration(i, /*privateDeclaration*/ true); + needsDeclare = priorNeedsDeclare; lateStatementReplacementMap.set("" + ts.getOriginalNodeId(i), result); } // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list @@ -80703,7 +81154,8 @@ var ts; var extendsClause_1 = ts.getEffectiveBaseTypeNode(input); if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 96 /* NullKeyword */) { // We must add a temporary declaration for the extends clause expression - var newId_1 = ts.createOptimisticUniqueName(ts.unescapeLeadingUnderscores(input.name.escapedText) + "_base"); // TODO: GH#18217 + var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default"; + var newId_1 = ts.createOptimisticUniqueName(oldId + "_base"); getSymbolAccessibilityDiagnostic = function () { return ({ diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, errorNode: extendsClause_1, @@ -80857,7 +81309,7 @@ var ts; var prop = ts.createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? 64 /* Readonly */ : 0 /* None */), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); var leadingsSyntheticCommentRanges = accessors.secondAccessor && ts.getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); if (leadingsSyntheticCommentRanges) { - var _loop_9 = function (range) { + var _loop_10 = function (range) { if (range.kind === 3 /* MultiLineCommentTrivia */) { var text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); var lines = text.split(/\r\n?|\n/g); @@ -80871,7 +81323,7 @@ var ts; }; for (var _i = 0, leadingsSyntheticCommentRanges_1 = leadingsSyntheticCommentRanges; _i < leadingsSyntheticCommentRanges_1.length; _i++) { var range = leadingsSyntheticCommentRanges_1[_i]; - _loop_9(range); + _loop_10(range); } } return prop; @@ -82761,18 +83213,22 @@ var ts; function emitPropertyAccessExpression(node) { var indentBeforeDot = false; var indentAfterDot = false; + var dotRangeFirstCommentStart = ts.skipTrivia(currentSourceFile.text, node.expression.end, + /*stopAfterLineBreak*/ false, + /*stopAtComments*/ true); + var dotRangeStart = ts.skipTrivia(currentSourceFile.text, dotRangeFirstCommentStart); + var dotRangeEnd = dotRangeStart + 1; if (!(ts.getEmitFlags(node) & 131072 /* NoIndentation */)) { - var dotRangeStart = node.expression.end; - var dotRangeEnd = ts.skipTrivia(currentSourceFile.text, node.expression.end) + 1; var dotToken = ts.createToken(24 /* DotToken */); - dotToken.pos = dotRangeStart; + dotToken.pos = node.expression.end; dotToken.end = dotRangeEnd; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } emitExpression(node.expression); increaseIndentIf(indentBeforeDot, /*writeSpaceIfNotIndenting*/ false); - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); + var dotHasCommentTrivia = dotRangeFirstCommentStart !== dotRangeStart; + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression, dotHasCommentTrivia); if (shouldEmitDotDot) { writePunctuation("."); } @@ -82783,13 +83239,15 @@ var ts; } // 1..toString is a valid property access, emit a dot after the literal // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal - function needsDotDotForPropertyAccess(expression) { + function needsDotDotForPropertyAccess(expression, dotHasTrivia) { expression = ts.skipPartiallyEmittedExpressions(expression); if (ts.isNumericLiteral(expression)) { // check if numeric literal is a decimal literal that was originally written with a dot var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true); - return !expression.numericLiteralFlags - && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)); + // If he number will be printed verbatim and it doesn't already contain a dot, add one + // if the expression doesn't have any comments that will be emitted. + return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */)) && + (!dotHasTrivia || printerOptions.removeComments); } else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer @@ -83540,6 +83998,7 @@ var ts; function emitJsxSelfClosingElement(node) { writePunctuation("<"); emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); writeSpace(); emit(node.attributes); writePunctuation("/>"); @@ -83553,6 +84012,7 @@ var ts; writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); + emitTypeArguments(node, node.typeArguments); if (node.attributes.properties && node.attributes.properties.length > 0) { writeSpace(); } @@ -85158,7 +85618,7 @@ var ts; if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) { return; } - var _a = ts.getLineAndCharacterOfPosition(currentSourceFile, pos), sourceLine = _a.line, sourceCharacter = _a.character; + var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character; sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, /*nameIndex*/ undefined); } @@ -85567,7 +86027,7 @@ var ts; }, flags); } function getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo) { - return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo1); + return "WatchInfo: " + file + " " + flags + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2); } function closeFileWatcherOf(objWithWatcher) { objWithWatcher.watcher.close(); @@ -85648,7 +86108,7 @@ var ts; var text; try { ts.performance.mark("beforeIORead"); - text = system.readFile(fileName, options.charset); + text = compilerHost.readFile(fileName); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -85674,7 +86134,12 @@ var ts; if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) { var parentDirectory = ts.getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); - system.createDirectory(directoryPath); + if (compilerHost.createDirectory) { + compilerHost.createDirectory(directoryPath); + } + else { + system.createDirectory(directoryPath); + } } } var outputFingerprints; @@ -85726,7 +86191,7 @@ var ts; } var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; }); var realpath = system.realpath && (function (path) { return system.realpath(path); }); - return { + var compilerHost = { getSourceFile: getSourceFile, getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, @@ -85742,10 +86207,112 @@ var ts; getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return system.getDirectories(path); }, realpath: realpath, - readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); } + readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); }, + createDirectory: function (d) { return system.createDirectory(d); } }; + return compilerHost; } ts.createCompilerHostWorker = createCompilerHostWorker; + /*@internal*/ + function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) { + var originalReadFile = host.readFile; + var originalFileExists = host.fileExists; + var originalDirectoryExists = host.directoryExists; + var originalCreateDirectory = host.createDirectory; + var originalWriteFile = host.writeFile; + var readFileCache = ts.createMap(); + var fileExistsCache = ts.createMap(); + var directoryExistsCache = ts.createMap(); + var sourceFileCache = ts.createMap(); + var readFileWithCache = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value || undefined; + return setReadFileCache(key, fileName); + }; + var setReadFileCache = function (key, fileName) { + var newValue = originalReadFile.call(host, fileName); + readFileCache.set(key, newValue || false); + return newValue; + }; + host.readFile = function (fileName) { + var key = toPath(fileName); + var value = readFileCache.get(key); + if (value !== undefined) + return value; // could be .d.ts from output + if (!ts.fileExtensionIs(fileName, ".json" /* Json */)) { + return originalReadFile.call(host, fileName); + } + return setReadFileCache(key, fileName); + }; + var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { + var key = toPath(fileName); + var value = sourceFileCache.get(key); + if (value) + return value; + var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile); + if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) { + sourceFileCache.set(key, sourceFile); + } + return sourceFile; + } : undefined; + // fileExists for any kind of extension + host.fileExists = function (fileName) { + var key = toPath(fileName); + var value = fileExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalFileExists.call(host, fileName); + fileExistsCache.set(key, !!newValue); + return newValue; + }; + if (originalWriteFile) { + host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) { + var key = toPath(fileName); + fileExistsCache.delete(key); + var value = readFileCache.get(key); + if (value && value !== data) { + readFileCache.delete(key); + sourceFileCache.delete(key); + } + else if (getSourceFileWithCache) { + var sourceFile = sourceFileCache.get(key); + if (sourceFile && sourceFile.text !== data) { + sourceFileCache.delete(key); + } + } + originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles); + }; + } + // directoryExists + if (originalDirectoryExists && originalCreateDirectory) { + host.directoryExists = function (directory) { + var key = toPath(directory); + var value = directoryExistsCache.get(key); + if (value !== undefined) + return value; + var newValue = originalDirectoryExists.call(host, directory); + directoryExistsCache.set(key, !!newValue); + return newValue; + }; + host.createDirectory = function (directory) { + var key = toPath(directory); + directoryExistsCache.delete(key); + originalCreateDirectory.call(host, directory); + }; + } + return { + originalReadFile: originalReadFile, + originalFileExists: originalFileExists, + originalDirectoryExists: originalDirectoryExists, + originalCreateDirectory: originalCreateDirectory, + originalWriteFile: originalWriteFile, + getSourceFileWithCache: getSourceFileWithCache, + readFileWithCache: readFileWithCache + }; + } + ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache; function getPreEmitDiagnostics(program, sourceFile, cancellationToken) { var diagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); if (ts.getEmitDeclarations(program.getCompilerOptions())) { @@ -86078,7 +86645,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = ts.createMap(); ts.performance.mark("beforeProgram"); var host = createProgramOptions.host || createCompilerHost(options); - var configParsingHost = parseConfigHostFromCompilerHost(host); + var configParsingHost = parseConfigHostFromCompilerHostLike(host); var skipDefaultLib = options.noLib; var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); }); var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName()); @@ -86124,6 +86691,12 @@ var ts; var sourceFileToPackageName = ts.createMap(); // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it. var redirectTargetsMap = ts.createMultiMap(); + /** + * map with + * - SourceFile if present + * - false if sourceFile missing for source of project reference redirect + * - undefined otherwise + */ var filesByName = ts.createMap(); var missingFilePaths; // stores 'filename -> file association' ignoring case @@ -86184,7 +86757,10 @@ var ts; }); } } - missingFilePaths = ts.arrayFrom(filesByName.keys(), function (p) { return p; }).filter(function (p) { return !filesByName.get(p); }); + missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) { + var path = _a[0], file = _a[1]; + return file === undefined ? path : undefined; + })); files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles); processingDefaultLibFiles = undefined; processingOtherFiles = undefined; @@ -86330,13 +86906,13 @@ var ts; // which per above occurred during the current program creation. // Since we assume the filesystem does not change during program creation, // it is safe to reuse resolutions from the earlier call. - var result_5 = []; + var result_6 = []; for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { var moduleName = moduleNames_1[_i]; var resolvedModule = file.resolvedModules.get(moduleName); - result_5.push(resolvedModule); + result_6.push(resolvedModule); } - return result_5; + return result_6; } // At this point, we know at least one of the following hold: // - file has local declarations for ambient modules @@ -86792,7 +87368,7 @@ var ts; return getSourceFileByPath(toPath(fileName)); } function getSourceFileByPath(path) { - return filesByName.get(path); + return filesByName.get(path) || undefined; } function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { if (sourceFile) { @@ -87270,7 +87846,7 @@ var ts; } /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */ function getSourceFileFromReference(referencingFile, ref) { - return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)); }); + return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; }); } function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) { if (ts.hasExtension(fileName)) { @@ -87376,7 +87952,9 @@ var ts; processReferencedFiles(file_1, isDefaultLib); processTypeReferenceDirectives(file_1); } - processLibReferenceDirectives(file_1); + if (!options.noLib) { + processLibReferenceDirectives(file_1); + } modulesWithElidedImports.set(file_1.path, false); processImportedModules(file_1); } @@ -87387,7 +87965,7 @@ var ts; processImportedModules(file_1); } } - return file_1; + return file_1 || undefined; } var redirectedPath; if (refFile) { @@ -87453,7 +88031,9 @@ var ts; processReferencedFiles(file, isDefaultLib); processTypeReferenceDirectives(file); } - processLibReferenceDirectives(file); + if (!options.noLib) { + processLibReferenceDirectives(file); + } // always process imported modules to record module name resolutions processImportedModules(file); if (isDefaultLib) { @@ -87466,9 +88046,12 @@ var ts; return file; } function addFileToFilesByName(file, path, redirectedPath) { - filesByName.set(path, file); if (redirectedPath) { filesByName.set(redirectedPath, file); + filesByName.set(path, file || false); + } + else { + filesByName.set(path, file); } } function getProjectReferenceRedirect(fileName) { @@ -88131,21 +88714,22 @@ var ts; } ts.createProgram = createProgram; /* @internal */ - function parseConfigHostFromCompilerHost(host) { + function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) { + if (directoryStructureHost === void 0) { directoryStructureHost = host; } return { - fileExists: function (f) { return host.fileExists(f); }, + fileExists: function (f) { return directoryStructureHost.fileExists(f); }, readDirectory: function (root, extensions, excludes, includes, depth) { - ts.Debug.assertDefined(host.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); - return host.readDirectory(root, extensions, excludes, includes, depth); + ts.Debug.assertDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'"); + return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth); }, - readFile: function (f) { return host.readFile(f); }, + readFile: function (f) { return directoryStructureHost.readFile(f); }, useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(), getCurrentDirectory: function () { return host.getCurrentDirectory(); }, - onUnRecoverableConfigFileDiagnostic: function () { return undefined; }, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || (function () { return undefined; }), trace: host.trace ? function (s) { return host.trace(s); } : undefined }; } - ts.parseConfigHostFromCompilerHost = parseConfigHostFromCompilerHost; + ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike; function resolveProjectReferencePath(hostOrRef, ref) { var passedInRef = ref ? ref : hostOrRef; return ts.resolveConfigFileProjectName(passedInRef.path); @@ -88212,6 +88796,10 @@ var ts; } } ts.getFileEmitOutput = getFileEmitOutput; + function cloneMapOrUndefined(map) { + return map ? ts.cloneMap(map) : undefined; + } + ts.cloneMapOrUndefined = cloneMapOrUndefined; })(ts || (ts = {})); /*@internal*/ (function (ts) { @@ -88359,12 +88947,35 @@ var ts; fileInfos: fileInfos, referencedMap: referencedMap, exportedModulesMap: exportedModulesMap, - hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, - allFilesExcludingDefaultLibraryFile: undefined, - allFileNames: undefined + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature }; } BuilderState.create = create; + /** + * Releases needed properties + */ + function releaseCache(state) { + state.allFilesExcludingDefaultLibraryFile = undefined; + state.allFileNames = undefined; + } + BuilderState.releaseCache = releaseCache; + /** + * Creates a clone of the state + */ + function clone(state) { + var fileInfos = ts.createMap(); + state.fileInfos.forEach(function (value, key) { + fileInfos.set(key, __assign({}, value)); + }); + // Dont need to backup allFiles info since its cache anyway + return { + fileInfos: fileInfos, + referencedMap: ts.cloneMapOrUndefined(state.referencedMap), + exportedModulesMap: ts.cloneMapOrUndefined(state.exportedModulesMap), + hasCalledUpdateShapeSignature: ts.cloneMap(state.hasCalledUpdateShapeSignature), + }; + } + BuilderState.clone = clone; /** * Gets the files affected by the path from the program */ @@ -88613,7 +89224,7 @@ var ts; var seenFileNamesMap = ts.createMap(); // Start with the paths this file was referenced by seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); - var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath); while (queue.length > 0) { var currentPath = queue.pop(); if (!seenFileNamesMap.has(currentPath)) { @@ -88621,7 +89232,7 @@ var ts; seenFileNamesMap.set(currentPath, currentSourceFile); if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) { // TODO: GH#18217 queue.push.apply(// TODO: GH#18217 - queue, getReferencedByPaths(state, currentPath)); + queue, getReferencedByPaths(state, currentSourceFile.resolvedPath)); } } } @@ -88645,24 +89256,32 @@ var ts; var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); state.program = newProgram; var compilerOptions = newProgram.getCompilerOptions(); - if (!compilerOptions.outFile && !compilerOptions.out) { + state.compilerOptions = compilerOptions; + // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them + // With --isolatedModules, emitting changed file doesnt emit dependent files so we cant know of dependent files to retrieve errors so dont cache the errors + if (!compilerOptions.outFile && !compilerOptions.out && !compilerOptions.isolatedModules) { state.semanticDiagnosticsPerFile = ts.createMap(); } state.changedFilesSet = ts.createMap(); var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); - var oldCompilerOptions = useOldState ? oldState.program.getCompilerOptions() : undefined; + var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined; var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile && !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions); if (useOldState) { // Verify the sanity of old state if (!oldState.currentChangedFilePath) { - ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + var affectedSignatures = oldState.currentAffectedFilesSignatures; + ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); } if (canCopySemanticDiagnostics) { ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); } // Copy old state's changed files set ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + if (!compilerOptions.outFile && !compilerOptions.out && oldState.affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit; + state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex; + } } // Update changed files and copy semantic diagnostics if we can var referencedMap = state.referencedMap; @@ -88686,7 +89305,7 @@ var ts; state.changedFilesSet.set(sourceFilePath, true); } else if (canCopySemanticDiagnostics) { - var sourceFile = state.program.getSourceFileByPath(sourceFilePath); + var sourceFile = newProgram.getSourceFileByPath(sourceFilePath); if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) { return; } @@ -88706,6 +89325,36 @@ var ts; }); return state; } + /** + * Releases program and other related not needed properties + */ + function releaseCache(state) { + ts.BuilderState.releaseCache(state); + state.program = undefined; + } + /** + * Creates a clone of the state + */ + function cloneBuilderProgramState(state) { + var newState = ts.BuilderState.clone(state); + newState.semanticDiagnosticsPerFile = ts.cloneMapOrUndefined(state.semanticDiagnosticsPerFile); + newState.changedFilesSet = ts.cloneMap(state.changedFilesSet); + newState.affectedFiles = state.affectedFiles; + newState.affectedFilesIndex = state.affectedFilesIndex; + newState.currentChangedFilePath = state.currentChangedFilePath; + newState.currentAffectedFilesSignatures = ts.cloneMapOrUndefined(state.currentAffectedFilesSignatures); + newState.currentAffectedFilesExportedModulesMap = ts.cloneMapOrUndefined(state.currentAffectedFilesExportedModulesMap); + newState.seenAffectedFiles = ts.cloneMapOrUndefined(state.seenAffectedFiles); + newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles; + newState.semanticDiagnosticsFromOldState = ts.cloneMapOrUndefined(state.semanticDiagnosticsFromOldState); + newState.program = state.program; + newState.compilerOptions = state.compilerOptions; + newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit; + newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex; + newState.seenEmittedFiles = ts.cloneMapOrUndefined(state.seenEmittedFiles); + newState.programEmitComplete = state.programEmitComplete; + return newState; + } /** * Verifies that source file is ok to be used in calls that arent handled by next */ @@ -88752,22 +89401,43 @@ var ts; } // With --out or --outFile all outputs go into single file // so operations are performed directly on program, return program - var compilerOptions = state.program.getCompilerOptions(); + var program = ts.Debug.assertDefined(state.program); + var compilerOptions = program.getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); - return state.program; + return program; } // Get next batch of affected files state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); if (state.exportedModulesMap) { state.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap || ts.createMap(); } - state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap); state.currentChangedFilePath = nextKey.value; state.affectedFilesIndex = 0; state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); } } + /** + * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet + */ + function getNextAffectedFilePendingEmit(state) { + var affectedFilesPendingEmit = state.affectedFilesPendingEmit; + if (affectedFilesPendingEmit) { + var seenEmittedFiles = state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap()); + for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) { + var affectedFile = ts.Debug.assertDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]); + if (affectedFile && !seenEmittedFiles.has(affectedFile.path)) { + // emit this file + state.affectedFilesPendingEmitIndex = i; + return affectedFile; + } + } + state.affectedFilesPendingEmit = undefined; + state.affectedFilesPendingEmitIndex = undefined; + } + return undefined; + } /** * Remove the semantic diagnostics cached from old state for affected File and the files that are referencing modules that export entities from affected file */ @@ -88779,9 +89449,10 @@ var ts; // Clean lib file diagnostics if its all files excluding default files to emit if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles && !state.cleanedDiagnosticsOfLibFiles) { state.cleanedDiagnosticsOfLibFiles = true; - var options_2 = state.program.getCompilerOptions(); - if (ts.forEach(state.program.getSourceFiles(), function (f) { - return state.program.isSourceFileDefaultLibrary(f) && + var program_1 = ts.Debug.assertDefined(state.program); + var options_2 = program_1.getCompilerOptions(); + if (ts.forEach(program_1.getSourceFiles(), function (f) { + return program_1.isSourceFileDefaultLibrary(f) && !ts.skipTypeChecking(f, options_2) && removeSemanticDiagnosticsOf(state, f.path); })) { @@ -88842,11 +89513,20 @@ var ts; return true; } // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected - return !!ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { + if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) { return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it exportedModules.has(filePath) && removeSemanticDiagnosticsOfFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile); - }); + })) { + return true; + } + // Remove diagnostics of files that import this file (without going to exports of referencing files) + return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) { + return referencesInFile.has(filePath) && + !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file + removeSemanticDiagnosticsOf(state, referencingFilePath); + } // Dont add to seen since this is not yet done with the export removal + ); } /** * Removes semantic diagnostics for path and @@ -88864,20 +89544,26 @@ var ts; * This is called after completing operation on the next affected file. * The operations here are postponed to ensure that cancellation during the iteration is handled correctly */ - function doneWithAffectedFile(state, affected) { + function doneWithAffectedFile(state, affected, isPendingEmit) { if (affected === state.program) { state.changedFilesSet.clear(); + state.programEmitComplete = true; } else { state.seenAffectedFiles.set(affected.path, true); - state.affectedFilesIndex++; + if (isPendingEmit) { + state.affectedFilesPendingEmitIndex++; + } + else { + state.affectedFilesIndex++; + } } } /** * Returns the result with affected file */ - function toAffectedFileResult(state, result, affected) { - doneWithAffectedFile(state, affected); + function toAffectedFileResult(state, result, affected, isPendingEmit) { + doneWithAffectedFile(state, affected, isPendingEmit); return { result: result, affected: affected }; } /** @@ -88886,14 +89572,18 @@ var ts; */ function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { var path = sourceFile.path; - var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - return cachedDiagnostics; + if (state.semanticDiagnosticsPerFile) { + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } } // Diagnostics werent cached, get them from program, and cache the result - var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); - state.semanticDiagnosticsPerFile.set(path, diagnostics); + var diagnostics = ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); + if (state.semanticDiagnosticsPerFile) { + state.semanticDiagnosticsPerFile.set(path, diagnostics); + } return diagnostics; } var BuilderProgramKind; @@ -88918,7 +89608,7 @@ var ts; rootNames: newProgramOrRootNames, options: hostOrOptions, host: oldProgramOrHost, - oldProgram: oldProgram && oldProgram.getProgram(), + oldProgram: oldProgram && oldProgram.getProgramOrUndefined(), configFileParsingDiagnostics: configFileParsingDiagnostics, projectReferences: projectReferences }); @@ -88949,26 +89639,29 @@ var ts; /** * Computing hash to for signature verification */ - var computeHash = host.createHash || ts.identity; + var computeHash = host.createHash || ts.generateDjb2Hash; var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + var backupState; // To ensure that we arent storing any references to old program or new program without state newProgram = undefined; // TODO: GH#18217 oldProgram = undefined; oldState = undefined; - var result = { - getState: function () { return state; }, - getProgram: function () { return state.program; }, - getCompilerOptions: function () { return state.program.getCompilerOptions(); }, - getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, - getSourceFiles: function () { return state.program.getSourceFiles(); }, - getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, - getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, - getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics || state.program.getConfigFileParsingDiagnostics(); }, - getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, - getSemanticDiagnostics: getSemanticDiagnostics, - emit: emit, - getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, - getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + var result = createRedirectedBuilderProgram(state, configFileParsingDiagnostics); + result.getState = function () { return state; }; + result.backupState = function () { + ts.Debug.assert(backupState === undefined); + backupState = cloneBuilderProgramState(state); + }; + result.restoreState = function () { + state = ts.Debug.assertDefined(backupState); + backupState = undefined; + }; + result.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.assertDefined(state.program), sourceFile); }; + result.getSemanticDiagnostics = getSemanticDiagnostics; + result.emit = emit; + result.releaseProgram = function () { + releaseCache(state); + backupState = undefined; }; if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; @@ -88987,14 +89680,33 @@ var ts; */ function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { var affected = getNextAffectedFile(state, cancellationToken, computeHash); + var isPendingEmitFile = false; if (!affected) { - // Done - return undefined; + if (!state.compilerOptions.out && !state.compilerOptions.outFile) { + affected = getNextAffectedFilePendingEmit(state); + if (!affected) { + return undefined; + } + isPendingEmitFile = true; + } + else { + var program = ts.Debug.assertDefined(state.program); + // Check if program uses any prepend project references, if thats the case we cant track of the js files of those, so emit even though there are no changes + if (state.programEmitComplete || !ts.some(program.getProjectReferences(), function (ref) { return !!ref.prepend; })) { + state.programEmitComplete = true; + return undefined; + } + affected = program; + } + } + // Mark seen emitted files if there are pending files to be emitted + if (state.affectedFilesPendingEmit && state.program !== affected) { + (state.seenEmittedFiles || (state.seenEmittedFiles = ts.createMap())).set(affected.path, true); } return toAffectedFileResult(state, // When whole program is affected, do emit only once (eg when --out or --outFile is specified) // Otherwise just affected file - state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + ts.Debug.assertDefined(state.program).emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected, isPendingEmitFile); } /** * Emits the JavaScript and declaration files. @@ -89031,7 +89743,7 @@ var ts; }; } } - return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return ts.Debug.assertDefined(state.program).emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); } /** * Return the semantic diagnostics for the next affected file or undefined if iteration is complete @@ -89067,25 +89779,38 @@ var ts; */ function getSemanticDiagnostics(sourceFile, cancellationToken) { assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); - var compilerOptions = state.program.getCompilerOptions(); + var compilerOptions = ts.Debug.assertDefined(state.program).getCompilerOptions(); if (compilerOptions.outFile || compilerOptions.out) { ts.Debug.assert(!state.semanticDiagnosticsPerFile); // We dont need to cache the diagnostics just return them from program - return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + return ts.Debug.assertDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken); } if (sourceFile) { return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); } - if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { - // When semantic builder asks for diagnostics of the whole program, - // ensure that all the affected files are handled - var affected = void 0; - while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { - doneWithAffectedFile(state, affected); + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected; + var affectedFilesPendingEmit; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + if (affected !== state.program && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + (affectedFilesPendingEmit || (affectedFilesPendingEmit = [])).push(affected.path); + } + doneWithAffectedFile(state, affected); + } + // In case of emit builder, cache the files to be emitted + if (affectedFilesPendingEmit) { + state.affectedFilesPendingEmit = ts.concatenate(state.affectedFilesPendingEmit, affectedFilesPendingEmit); + // affectedFilesPendingEmitIndex === undefined + // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files + // so start from 0 as array would be affectedFilesPendingEmit + // else, continue to iterate from existing index, the current set is appended to existing files + if (state.affectedFilesPendingEmitIndex === undefined) { + state.affectedFilesPendingEmitIndex = 0; } } var diagnostics; - for (var _i = 0, _a = state.program.getSourceFiles(); _i < _a.length; _i++) { + for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { var sourceFile_2 = _a[_i]; diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); } @@ -89093,6 +89818,32 @@ var ts; } } ts.createBuilderProgram = createBuilderProgram; + function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { + return { + getState: ts.notImplemented, + backupState: ts.noop, + restoreState: ts.noop, + getProgram: getProgram, + getProgramOrUndefined: function () { return state.program; }, + releaseProgram: function () { return state.program = undefined; }, + getCompilerOptions: function () { return state.compilerOptions; }, + getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); }, + getSourceFiles: function () { return getProgram().getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); }, + getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); }, + emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); }, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); } + }; + function getProgram() { + return ts.Debug.assertDefined(state.program); + } + } + ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram; })(ts || (ts = {})); (function (ts) { function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { @@ -89104,23 +89855,8 @@ var ts; } ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) { - var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences).newProgram; - return { - // Only return program, all other methods are not implemented - getProgram: function () { return program; }, - getState: ts.notImplemented, - getCompilerOptions: ts.notImplemented, - getSourceFile: ts.notImplemented, - getSourceFiles: ts.notImplemented, - getOptionsDiagnostics: ts.notImplemented, - getGlobalDiagnostics: ts.notImplemented, - getConfigFileParsingDiagnostics: ts.notImplemented, - getSyntacticDiagnostics: ts.notImplemented, - getSemanticDiagnostics: ts.notImplemented, - emit: ts.notImplemented, - getAllDependencies: ts.notImplemented, - getCurrentDirectory: ts.notImplemented - }; + var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics; + return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics); } ts.createAbstractBuilder = createAbstractBuilder; })(ts || (ts = {})); @@ -89924,7 +90660,7 @@ var ts; if (ts.startsWithDirectory(importingFileName, resolved, getCanonicalFileName)) { return; // Don't want to a package to globally import from itself } - var target = targets.find(function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); + var target = ts.find(targets, function (t) { return compareStrings(t.slice(0, resolved.length + 1), resolved + "/") === 0 /* EqualTo */; }); if (target === undefined) return; var relative = ts.getRelativePathFromDirectory(resolved, target, getCanonicalFileName); @@ -90299,37 +91035,103 @@ var ts; var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system); return { onWatchStatusChange: onWatchStatusChange, - watchFile: system.watchFile ? (function (path, callback, pollingInterval) { return system.watchFile(path, callback, pollingInterval); }) : function () { return noopFileWatcher; }, - watchDirectory: system.watchDirectory ? (function (path, callback, recursive) { return system.watchDirectory(path, callback, recursive); }) : function () { return noopFileWatcher; }, - setTimeout: system.setTimeout ? (function (callback, ms) { - var args = []; - for (var _i = 2; _i < arguments.length; _i++) { - args[_i - 2] = arguments[_i]; - } - var _a; - return (_a = system.setTimeout).call.apply(_a, [system, callback, ms].concat(args)); - }) : ts.noop, - clearTimeout: system.clearTimeout ? (function (timeoutId) { return system.clearTimeout(timeoutId); }) : ts.noop + watchFile: ts.maybeBind(system, system.watchFile) || (function () { return noopFileWatcher; }), + watchDirectory: ts.maybeBind(system, system.watchDirectory) || (function () { return noopFileWatcher; }), + setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop, + clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop }; } ts.createWatchHost = createWatchHost; + var WatchType; + (function (WatchType) { + WatchType["ConfigFile"] = "Config file"; + WatchType["SourceFile"] = "Source file"; + WatchType["MissingFile"] = "Missing file"; + WatchType["WildcardDirectory"] = "Wild card directory"; + WatchType["FailedLookupLocations"] = "Failed Lookup Locations"; + WatchType["TypeRoots"] = "Type roots"; + })(WatchType = ts.WatchType || (ts.WatchType = {})); + function createWatchFactory(host, options) { + var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; + var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop; + var result = ts.getWatchFactory(watchLogLevel, writeLog); + result.writeLog = writeLog; + return result; + } + ts.createWatchFactory = createWatchFactory; + function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) { + if (directoryStructureHost === void 0) { directoryStructureHost = host; } + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); }); + return { + getSourceFile: function (fileName, languageVersion, onError) { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, getCompilerOptions().charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + text = ""; + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + }, + getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }), + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames), + getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); }, + fileExists: function (f) { return host.fileExists(f); }, + readFile: function (f) { return host.readFile(f); }, + trace: ts.maybeBind(host, host.trace), + directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists), + getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories), + realpath: ts.maybeBind(host, host.realpath), + getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }), + createHash: ts.maybeBind(host, host.createHash), + readDirectory: ts.maybeBind(host, host.readDirectory), + }; + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + if (host.createDirectory) + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost; /** * Creates the watch compiler host that can be extended with config file or root file names and options host */ - function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { - if (system === void 0) { system = ts.sys; } - if (!createProgram) { - createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; - } + function createProgramHost(system, createProgram) { + var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); }); var host = system; host; // tslint:disable-line no-unused-expression (TODO: `host` is unused!) - var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; - var writeFileName = function (s) { return system.write(s + system.newLine); }; - var _a = createWatchHost(system, reportWatchStatus), onWatchStatusChange = _a.onWatchStatusChange, watchFile = _a.watchFile, watchDirectory = _a.watchDirectory, setTimeout = _a.setTimeout, clearTimeout = _a.clearTimeout; return { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, + useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, getNewLine: function () { return system.newLine; }, - getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }), getDefaultLibLocation: getDefaultLibLocation, getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, fileExists: function (path) { return system.fileExists(path); }, @@ -90337,29 +91139,31 @@ var ts; directoryExists: function (path) { return system.directoryExists(path); }, getDirectories: function (path) { return system.getDirectories(path); }, readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, - realpath: system.realpath && (function (path) { return system.realpath(path); }), - getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), - watchFile: watchFile, - watchDirectory: watchDirectory, - setTimeout: setTimeout, - clearTimeout: clearTimeout, - trace: function (s) { return system.write(s); }, - onWatchStatusChange: onWatchStatusChange, + realpath: ts.maybeBind(system, system.realpath), + getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable), + trace: function (s) { return system.write(s + system.newLine); }, createDirectory: function (path) { return system.createDirectory(path); }, writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, - createHash: system.createHash && (function (s) { return system.createHash(s); }), - createProgram: createProgram, - afterProgramCreate: emitFilesAndReportErrorUsingBuilder + createHash: ts.maybeBind(system, system.createHash), + createProgram: createProgram }; - function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); - } - function emitFilesAndReportErrorUsingBuilder(builderProgram) { + } + ts.createProgramHost = createProgramHost; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var writeFileName = function (s) { return system.write(s + system.newLine); }; + var result = createProgramHost(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram); + ts.copyProperties(result, createWatchHost(system, reportWatchStatus)); + result.afterProgramCreate = function (builderProgram) { var compilerOptions = builderProgram.getCompilerOptions(); var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; }); - emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); - } + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions); }); + }; + return result; } /** * Report error and exit @@ -90415,8 +91219,6 @@ var ts; var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); var currentDirectory = host.getCurrentDirectory(); - var getCurrentDirectory = function () { return currentDirectory; }; - var readFile = function (path, encoding) { return host.readFile(path, encoding); }; var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; var rootFileNames = host.rootFiles, compilerOptions = host.options, projectReferences = host.projectReferences; var configFileSpecs; @@ -90428,15 +91230,7 @@ var ts; host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); } var directoryStructureHost = cachedDirectoryStructureHost || host; - var parseConfigFileHost = { - useCaseSensitiveFileNames: useCaseSensitiveFileNames, - readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, - fileExists: function (path) { return host.fileExists(path); }, - readFile: readFile, - getCurrentDirectory: getCurrentDirectory, - onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic, - trace: host.trace ? function (s) { return host.trace(s); } : undefined - }; + var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost); // From tsc we want to get already parsed result and hence check for rootFileNames var newLine = updateNewLine(); if (configFileName && host.configFileParsingResult) { @@ -90450,52 +91244,40 @@ var ts; parseConfigFile(); newLine = updateNewLine(); } - var trace = host.trace && (function (s) { host.trace(s + newLine); }); - var watchLogLevel = trace ? compilerOptions.extendedDiagnostics ? ts.WatchLogLevel.Verbose : - compilerOptions.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None; - var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? trace : ts.noop; // TODO: GH#18217 - var _b = ts.getWatchFactory(watchLogLevel, writeLog), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory; + var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog; var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames); if (configFileName) { - watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file"); + watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, "Config file" /* ConfigFile */); } - var compilerHost = { - // Members for CompilerHost - getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, - getSourceFileByPath: getVersionedSourceFileByPath, - getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), - getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, - writeFile: writeFile, - getCurrentDirectory: getCurrentDirectory, - useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, - getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return newLine; }, - fileExists: fileExists, - readFile: readFile, - trace: trace, - directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), - getDirectories: (directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); })), - realpath: host.realpath && (function (s) { return host.realpath(s); }), - getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), - onReleaseOldSourceFile: onReleaseOldSourceFile, - createHash: host.createHash && (function (data) { return host.createHash(data); }), - // Members for ResolutionCacheHost - toPath: toPath, - getCompilationSettings: function () { return compilerOptions; }, - watchDirectoryOfFailedLookupLocation: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations"); }, - watchTypeRootsDirectory: function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots"); }, - getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, - onInvalidatedResolution: scheduleProgramUpdate, - onChangedAutomaticTypeDirectiveNames: function () { - hasChangedAutomaticTypeDirectiveNames = true; - scheduleProgramUpdate(); - }, - maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, - getCurrentProgram: getCurrentProgram, - writeLog: writeLog, - readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost); + // Members for CompilerHost + var getNewSourceFile = compilerHost.getSourceFile; + compilerHost.getSourceFile = function (fileName) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + return getVersionedSourceFileByPath.apply(void 0, [fileName, toPath(fileName)].concat(args)); }; + compilerHost.getSourceFileByPath = getVersionedSourceFileByPath; + compilerHost.getNewLine = function () { return newLine; }; + compilerHost.fileExists = fileExists; + compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile; + // Members for ResolutionCacheHost + compilerHost.toPath = toPath; + compilerHost.getCompilationSettings = function () { return compilerOptions; }; + compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Failed Lookup Locations" /* FailedLookupLocations */); }; + compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, "Type roots" /* TypeRoots */); }; + compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; }; + compilerHost.onInvalidatedResolution = scheduleProgramUpdate; + compilerHost.onChangedAutomaticTypeDirectiveNames = function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }; + compilerHost.maxNumberOfFilesToIterateForInvalidation = host.maxNumberOfFilesToIterateForInvalidation; + compilerHost.getCurrentProgram = getCurrentProgram; + compilerHost.writeLog = writeLog; // Cache for the module resolution var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : @@ -90548,11 +91330,9 @@ var ts; } function createNewProgram(program, hasInvalidatedResolution) { // Compile the program - if (watchLogLevel !== ts.WatchLogLevel.None) { - writeLog("CreatingProgramWith::"); - writeLog(" roots: " + JSON.stringify(rootFileNames)); - writeLog(" options: " + JSON.stringify(compilerOptions)); - } + writeLog("CreatingProgramWith::"); + writeLog(" roots: " + JSON.stringify(rootFileNames)); + writeLog(" options: " + JSON.stringify(compilerOptions)); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; hasChangedCompilerOptions = false; hasChangedConfigFileParsingErrors = false; @@ -90615,7 +91395,7 @@ var ts; } // Create new source file if requested or the versions dont match if (!hostSourceFile || shouldCreateNewSourceFile || !isFilePresentOnHost(hostSourceFile) || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { - var sourceFile = getNewSourceFile(); + var sourceFile = getNewSourceFile(fileName, languageVersion, onError); if (hostSourceFile) { if (shouldCreateNewSourceFile) { hostSourceFile.version++; @@ -90625,7 +91405,7 @@ var ts; hostSourceFile.sourceFile = sourceFile; sourceFile.version = hostSourceFile.version.toString(); if (!hostSourceFile.fileWatcher) { - hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); } } else { @@ -90639,7 +91419,7 @@ var ts; else { if (sourceFile) { sourceFile.version = initialVersion.toString(); - var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file"); + var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, path, "Source file" /* SourceFile */); sourceFilesCache.set(path, { sourceFile: sourceFile, version: initialVersion, fileWatcher: fileWatcher }); } else { @@ -90649,21 +91429,6 @@ var ts; return sourceFile; } return hostSourceFile.sourceFile; - function getNewSourceFile() { - var text; - try { - ts.performance.mark("beforeIORead"); - text = host.readFile(fileName, compilerOptions.charset); - ts.performance.mark("afterIORead"); - ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } - return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; - } } function nextSourceFileVersion(path) { var hostSourceFile = sourceFilesCache.get(path); @@ -90790,7 +91555,7 @@ var ts; } } function watchMissingFilePath(missingFilePath) { - return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file"); + return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, missingFilePath, "Missing file" /* MissingFile */); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -90834,28 +91599,7 @@ var ts; // Schedule Update the program scheduleProgramUpdate(); } - }, flags, "Wild card directories"); - } - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - host.createDirectory(directoryPath); - } - } - function writeFile(fileName, text, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - } - catch (e) { - if (onError) { - onError(e.message); - } - } + }, flags, "Wild card directory" /* WildcardDirectory */); } } ts.createWatchProgram = createWatchProgram; @@ -91024,9 +91768,8 @@ var ts; }; } ts.createBuilderStatusReporter = createBuilderStatusReporter; - function createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus) { - if (system === void 0) { system = ts.sys; } - var host = ts.createCompilerHostWorker({}, /*setParentNodes*/ undefined, system); + function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) { + var host = ts.createProgramHost(system, createProgram); host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : function () { return undefined; }; host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop; host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop; @@ -91034,21 +91777,18 @@ var ts; host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system); return host; } - function createSolutionBuilderHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { + function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) { if (system === void 0) { system = ts.sys; } - var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + var host = createSolutionBuilderHostBase(system, createProgram || ts.createAbstractBuilder, reportDiagnostic, reportSolutionBuilderStatus); host.reportErrorSummary = reportErrorSummary; return host; } ts.createSolutionBuilderHost = createSolutionBuilderHost; - function createSolutionBuilderWithWatchHost(system, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { - var host = createSolutionBuilderHostBase(system, reportDiagnostic, reportSolutionBuilderStatus); + function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + var host = createSolutionBuilderHostBase(system, createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram, reportDiagnostic, reportSolutionBuilderStatus); var watchHost = ts.createWatchHost(system, reportWatchStatus); - host.onWatchStatusChange = watchHost.onWatchStatusChange; - host.watchFile = watchHost.watchFile; - host.watchDirectory = watchHost.watchDirectory; - host.setTimeout = watchHost.setTimeout; - host.clearTimeout = watchHost.clearTimeout; + ts.copyProperties(host, watchHost); return host; } ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost; @@ -91063,7 +91803,7 @@ var ts; var hostWithWatch = host; var currentDirectory = host.getCurrentDirectory(); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - var parseConfigFileHost = ts.parseConfigHostFromCompilerHost(host); + var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host); // State of the solution var options = defaultOptions; var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options); @@ -91075,7 +91815,14 @@ var ts; var missingRoots = ts.createMap(); var globalDependencyGraph; var writeFileName = function (s) { return host.trace && host.trace(s); }; + var readFileWithCache = function (f) { return host.readFile(f); }; + var projectCompilerOptions = baseCompilerOptions; + var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return projectCompilerOptions; }); + var originalGetSourceFile = compilerHost.getSourceFile; + var computeHash = host.createHash || ts.generateDjb2Hash; + updateGetSourceFile(); // Watch state + var builderPrograms = createFileMap(toPath); var diagnostics = createFileMap(toPath); var projectPendingBuild = createFileMap(toPath); var projectErrorsReported = createFileMap(toPath); @@ -91083,6 +91830,7 @@ var ts; var nextProjectToBuild = 0; var timerToBuildInvalidatedProject; var reportFileChangeDetected = false; + var _a = ts.createWatchFactory(host, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog; // Watches for the solution var allWatchedWildcardDirectories = createFileMap(toPath); var allWatchedInputFiles = createFileMap(toPath); @@ -91123,6 +91871,30 @@ var ts; ts.clearMap(allWatchedWildcardDirectories, function (wildCardWatches) { return ts.clearMap(wildCardWatches, ts.closeFileWatcherOf); }); ts.clearMap(allWatchedInputFiles, function (inputFileWatches) { return ts.clearMap(inputFileWatches, ts.closeFileWatcher); }); ts.clearMap(allWatchedConfigFiles, ts.closeFileWatcher); + builderPrograms.clear(); + updateGetSourceFile(); + } + function updateGetSourceFile() { + if (options.watch) { + if (compilerHost.getSourceFile === originalGetSourceFile) { + compilerHost.getSourceFile = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var result = originalGetSourceFile.call.apply(originalGetSourceFile, [compilerHost].concat(args)); + if (result && options.watch) { + result.version = computeHash.call(host, result.text); + } + return result; + }; + } + } + else { + if (compilerHost.getSourceFile !== originalGetSourceFile) { + compilerHost.getSourceFile = originalGetSourceFile; + } + } } function isParsedCommandLine(entry) { return !!entry.options; @@ -91172,36 +91944,34 @@ var ts; } function watchConfigFile(resolved) { if (options.watch && !allWatchedConfigFiles.hasKey(resolved)) { - allWatchedConfigFiles.setValue(resolved, hostWithWatch.watchFile(resolved, function () { + allWatchedConfigFiles.setValue(resolved, watchFile(hostWithWatch, resolved, function () { invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Full); - })); + }, ts.PollingInterval.High, "Config file" /* ConfigFile */, resolved)); } } function watchWildCardDirectories(resolved, parsed) { if (!options.watch) return; ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(allWatchedWildcardDirectories, resolved), ts.createMapFromTemplate(parsed.configFileSpecs.wildcardDirectories), function (dir, flags) { - return hostWithWatch.watchDirectory(dir, function (fileOrDirectory) { + return watchDirectory(hostWithWatch, dir, function (fileOrDirectory) { var fileOrDirectoryPath = toPath(fileOrDirectory); if (fileOrDirectoryPath !== toPath(dir) && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, parsed.options)) { - // writeLog(`Project: ${configFileName} Detected file add/remove of non supported extension: ${fileOrDirectory}`); + writeLog("Project: " + resolved + " Detected file add/remove of non supported extension: " + fileOrDirectory); return; } if (isOutputFile(fileOrDirectory, parsed)) { - // writeLog(`${fileOrDirectory} is output file`); + writeLog(fileOrDirectory + " is output file"); return; } invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.Partial); - }, !!(flags & 1 /* Recursive */)); + }, flags, "Wild card directory" /* WildcardDirectory */, resolved); }); } function watchInputFiles(resolved, parsed) { if (!options.watch) return; ts.mutateMap(getOrCreateValueMapFromConfigFileMap(allWatchedInputFiles, resolved), ts.arrayToMap(parsed.fileNames, toPath), { - createNewValue: function (_key, input) { return hostWithWatch.watchFile(input, function () { - invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); - }); }, + createNewValue: function (path, input) { return watchFilePath(hostWithWatch, input, function () { return invalidateProjectAndScheduleBuilds(resolved, ts.ConfigFileProgramReloadLevel.None); }, ts.PollingInterval.Low, path, "Source file" /* SourceFile */, resolved); }, onDeleteValue: ts.closeFileWatcher, }); } @@ -91521,18 +92291,39 @@ var ts; reportStatus(ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, resolved, status.upstreamProjectName); return; } + if (status.type === UpToDateStatusType.UpToDateWithUpstreamTypes) { + // Fake that files have been built by updating output file stamps + updateOutputTimestamps(proj); + return; + } var buildResult = buildSingleProject(resolved); - var dependencyGraph = getGlobalDependencyGraph(); - var referencingProjects = dependencyGraph.referencingProjectsMap.getValue(resolved); + if (buildResult & BuildResultFlags.AnyErrors) + return; + var _a = getGlobalDependencyGraph(), referencingProjectsMap = _a.referencingProjectsMap, buildQueue = _a.buildQueue; + var referencingProjects = referencingProjectsMap.getValue(resolved); if (!referencingProjects) return; // Always use build order to queue projects - for (var _i = 0, _a = dependencyGraph.buildQueue; _i < _a.length; _i++) { - var project = _a[_i]; + for (var index = buildQueue.indexOf(resolved) + 1; index < buildQueue.length; index++) { + var project = buildQueue[index]; var prepend = referencingProjects.getValue(project); - // If the project is referenced with prepend, always build downstream projectm, - // otherwise queue it only if declaration output changed - if (prepend || (prepend !== undefined && !(buildResult & BuildResultFlags.DeclarationOutputUnchanged))) { + if (prepend !== undefined) { + // If the project is referenced with prepend, always build downstream projects, + // If declaration output is changed, build the project + // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps + var status_1 = projectStatus.getValue(project); + if (prepend || !(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) { + if (status_1 && (status_1.type === UpToDateStatusType.UpToDate || status_1.type === UpToDateStatusType.UpToDateWithUpstreamTypes)) { + projectStatus.setValue(project, { + type: UpToDateStatusType.OutOfDateWithUpstream, + outOfDateOutputFileName: status_1.oldestOutputFileName, + newerProjectName: resolved + }); + } + } + else if (status_1 && status_1.type === UpToDateStatusType.UpToDate) { + status_1.type = UpToDateStatusType.UpToDateWithUpstreamTypes; + } addProjToQueue(project); } } @@ -91603,98 +92394,118 @@ var ts; // Nothing to build - must be a solution file, basically return BuildResultFlags.None; } - var programOptions = { - projectReferences: configFile.projectReferences, - host: host, - rootNames: configFile.fileNames, - options: configFile.options, - configFileParsingDiagnostics: configFile.errors - }; - if (host.beforeCreateProgram) { - host.beforeCreateProgram(options); - } - var program = ts.createProgram(programOptions); + // TODO: handle resolve module name to cache result in project reference redirect + projectCompilerOptions = configFile.options; + var program = host.createProgram(configFile.fileNames, configFile.options, compilerHost, builderPrograms.getValue(proj), configFile.errors, configFile.projectReferences); + projectCompilerOptions = baseCompilerOptions; // Don't emit anything in the presence of syntactic errors or options diagnostics - var syntaxDiagnostics = program.getOptionsDiagnostics().concat(program.getConfigFileParsingDiagnostics(), program.getSyntacticDiagnostics()); + var syntaxDiagnostics = program.getConfigFileParsingDiagnostics().concat(program.getOptionsDiagnostics(), program.getGlobalDiagnostics(), program.getSyntacticDiagnostics()); if (syntaxDiagnostics.length) { return buildErrors(syntaxDiagnostics, BuildResultFlags.SyntaxErrors, "Syntactic"); } - // Don't emit .d.ts if there are decl file errors - if (ts.getEmitDeclarations(program.getCompilerOptions())) { - var declDiagnostics = program.getDeclarationDiagnostics(); - if (declDiagnostics.length) { - return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); - } - } // Same as above but now for semantic diagnostics var semanticDiagnostics = program.getSemanticDiagnostics(); if (semanticDiagnostics.length) { return buildErrors(semanticDiagnostics, BuildResultFlags.TypeErrors, "Semantic"); } + // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly + program.backupState(); var newestDeclarationFileContentChangedTime = minimumDate; var anyDtsChanged = false; - var emitDiagnostics; - var reportEmitDiagnostic = function (d) { return (emitDiagnostics || (emitDiagnostics = [])).push(d); }; - ts.emitFilesAndReportErrors(program, reportEmitDiagnostic, writeFileName, /*reportSummary*/ undefined, function (fileName, content, writeBom, onError) { + var declDiagnostics; + var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); }; + var outputFiles = []; + ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, writeFileName, /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }); + // Don't emit .d.ts if there are decl file errors + if (declDiagnostics) { + program.restoreState(); + return buildErrors(declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"); + } + // Actual Emit + var emitterDiagnostics = ts.createDiagnosticCollection(); + var emittedOutputs = createFileMap(toPath); + outputFiles.forEach(function (_a) { + var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark; var priorChangeTime; - if (!anyDtsChanged && isDeclarationFile(fileName)) { + if (!anyDtsChanged && isDeclarationFile(name)) { // Check for unchanged .d.ts files - if (host.fileExists(fileName) && host.readFile(fileName) === content) { - priorChangeTime = host.getModifiedTime(fileName); + if (host.fileExists(name) && readFileWithCache(name) === text) { + priorChangeTime = host.getModifiedTime(name); } else { resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged; anyDtsChanged = true; } } - host.writeFile(fileName, content, writeBom, onError, ts.emptyArray); + emittedOutputs.setValue(name, true); + ts.writeFile(compilerHost, emitterDiagnostics, name, text, writeByteOrderMark); if (priorChangeTime !== undefined) { newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime); - unchangedOutputs.setValue(fileName, priorChangeTime); + unchangedOutputs.setValue(name, priorChangeTime); } }); - if (emitDiagnostics) { + var emitDiagnostics = emitterDiagnostics.getDiagnostics(); + if (emitDiagnostics.length) { return buildErrors(emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"); } + // Update time stamps for rest of the outputs + newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(configFile, newestDeclarationFileContentChangedTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs); var status = { type: UpToDateStatusType.UpToDate, - newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime + newestDeclarationFileContentChangedTime: anyDtsChanged ? maximumDate : newestDeclarationFileContentChangedTime, + oldestOutputFileName: outputFiles.length ? outputFiles[0].name : getFirstProjectOutput(configFile) }; diagnostics.removeKey(proj); projectStatus.setValue(proj, status); - if (host.afterProgramEmitAndDiagnostics) { - host.afterProgramEmitAndDiagnostics(program); - } + afterProgramCreate(proj, program); return resultFlags; function buildErrors(diagnostics, errorFlags, errorType) { resultFlags |= errorFlags; reportAndStoreErrors(proj, diagnostics); projectStatus.setValue(proj, { type: UpToDateStatusType.Unbuildable, reason: errorType + " errors" }); - if (host.afterProgramEmitAndDiagnostics) { - host.afterProgramEmitAndDiagnostics(program); - } + afterProgramCreate(proj, program); return resultFlags; } } + function afterProgramCreate(proj, program) { + if (host.afterProgramEmitAndDiagnostics) { + host.afterProgramEmitAndDiagnostics(program); + } + if (options.watch) { + program.releaseProgram(); + builderPrograms.setValue(proj, program); + } + } function updateOutputTimestamps(proj) { if (options.dry) { return reportStatus(ts.Diagnostics.A_non_dry_build_would_build_project_0, proj.options.configFilePath); } - if (options.verbose) { - reportStatus(ts.Diagnostics.Updating_output_timestamps_of_project_0, proj.options.configFilePath); - } - var now = new Date(); - var outputs = getAllProjectOutputs(proj); - var priorNewestUpdateTime = minimumDate; - for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { - var file = outputs_2[_i]; - if (isDeclarationFile(file)) { - priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); - } - host.setModifiedTime(file, now); - } + var priorNewestUpdateTime = updateOutputTimestampsWorker(proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0); projectStatus.setValue(proj.options.configFilePath, { type: UpToDateStatusType.UpToDate, newestDeclarationFileContentChangedTime: priorNewestUpdateTime }); } + function updateOutputTimestampsWorker(proj, priorNewestUpdateTime, verboseMessage, skipOutputs) { + var outputs = getAllProjectOutputs(proj); + if (!skipOutputs || outputs.length !== skipOutputs.getSize()) { + if (options.verbose) { + reportStatus(verboseMessage, proj.options.configFilePath); + } + var now = host.now ? host.now() : new Date(); + for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) { + var file = outputs_2[_i]; + if (skipOutputs && skipOutputs.hasKey(file)) { + continue; + } + if (isDeclarationFile(file)) { + priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime); + } + host.setModifiedTime(file, now); + if (proj.options.listEmittedFiles) { + writeFileName("TSFILE: " + file); + } + } + } + return priorNewestUpdateTime; + } function getFilesToClean() { // Get the same graph for cleaning we'd use for building var graph = getGlobalDependencyGraph(); @@ -91739,11 +92550,24 @@ var ts; if (options.watch) { reportWatchStatus(ts.Diagnostics.Starting_compilation_in_watch_mode); } + // TODO:: In watch mode as well to use caches for incremental build once we can invalidate caches correctly and have right api + // Override readFile for json files and output .d.ts to cache the text + var savedReadFileWithCache = readFileWithCache; + var savedGetSourceFile = compilerHost.getSourceFile; + var _a = ts.changeCompilerHostLikeToUseCache(host, toPath, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return savedGetSourceFile.call.apply(savedGetSourceFile, [compilerHost].concat(args)); + }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, newReadFileWithCache = _a.readFileWithCache; + readFileWithCache = newReadFileWithCache; + compilerHost.getSourceFile = getSourceFileWithCache; var graph = getGlobalDependencyGraph(); reportBuildQueue(graph); var anyFailed = false; - for (var _i = 0, _a = graph.buildQueue; _i < _a.length; _i++) { - var next = _a[_i]; + for (var _i = 0, _b = graph.buildQueue; _i < _b.length; _i++) { + var next = _b[_i]; var proj = parseConfigFile(next); if (proj === undefined) { reportParseConfigFileDiagnostic(next); @@ -91785,6 +92609,13 @@ var ts; anyFailed = anyFailed || !!(buildResult & BuildResultFlags.AnyErrors); } reportErrorSummary(); + host.readFile = originalReadFile; + host.fileExists = originalFileExists; + host.directoryExists = originalDirectoryExists; + host.createDirectory = originalCreateDirectory; + host.writeFile = originalWriteFile; + compilerHost.getSourceFile = savedGetSourceFile; + readFileWithCache = savedReadFileWithCache; return anyFailed ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } function reportParseConfigFileDiagnostic(proj) { @@ -91807,7 +92638,7 @@ var ts; } } function relName(path) { - return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return host.getCanonicalFileName(f); }); + return ts.convertToRelativePath(path, host.getCurrentDirectory(), function (f) { return compilerHost.getCanonicalFileName(f); }); } /** * Report the up-to-date status of a project if we're in verbose mode @@ -91840,6 +92671,19 @@ var ts; } } ts.getAllProjectOutputs = getAllProjectOutputs; + function getFirstProjectOutput(project) { + if (project.options.outFile || project.options.out) { + return ts.first(getOutFileOutputs(project)); + } + for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) { + var inputFile = _a[_i]; + var outputs = getOutputFileNames(inputFile, project); + if (outputs.length) { + return ts.first(outputs); + } + } + return ts.Debug.fail("project " + project.options.configFilePath + " expected to have at least one output"); + } function formatUpToDateStatus(configFileName, status, relName, formatMessage) { switch (status.type) { case UpToDateStatusType.OutOfDateWithSelf: @@ -91892,17 +92736,17 @@ var ts; } ts.inspectValue = inspectValue; function getRecurser() { - var seen = new Set(); + var seen = []; var nameStack = []; return function (obj, name, cbOk, cbFail) { - if (seen.has(obj) || nameStack.length > 4) { - return cbFail(seen.has(obj), nameStack); + if (seen.indexOf(obj) !== -1 || nameStack.length > 4) { + return cbFail(seen.indexOf(obj) !== -1, nameStack); } - seen.add(obj); + seen.push(obj); nameStack.push(name); var res = cbOk(); nameStack.pop(); - seen.delete(obj); + seen.pop(); return res; }; } @@ -91960,8 +92804,8 @@ var ts; return key === "constructor" ? undefined : getValueInfo(key, value, recurser); }); } - var ignoredProperties = new Set(["arguments", "caller", "constructor", "eval", "super_"]); - var reservedFunctionProperties = new Set(Object.getOwnPropertyNames(ts.noop)); + var ignoredProperties = ["arguments", "caller", "constructor", "eval", "super_"]; + var reservedFunctionProperties = Object.getOwnPropertyNames(ts.noop); function getEntriesOfObject(obj) { var seen = ts.createMap(); var entries = []; @@ -91970,8 +92814,8 @@ var ts; for (var _i = 0, _a = Object.getOwnPropertyNames(chain); _i < _a.length; _i++) { var key = _a[_i]; if (!isJsPrivate(key) && - !ignoredProperties.has(key) && - (typeof obj !== "function" || !reservedFunctionProperties.has(key)) && + ignoredProperties.indexOf(key) === -1 && + (typeof obj !== "function" || reservedFunctionProperties.indexOf(key) === -1) && // Don't add property from a higher prototype if it already exists in a lower one ts.addToSeen(seen, key)) { var value = safeGetPropertyOfObject(chain, key); @@ -91999,7 +92843,7 @@ var ts; return { kind: 0 /* Const */, name: name, typeName: "any", comment: comment }; } function isJsPrivate(name) { - return name.startsWith("_"); + return ts.startsWith(name, "_"); } ts.isJsPrivate = isJsPrivate; function tryRequire(fileNameToRequire) { diff --git a/lib/zh-tw/diagnosticMessages.generated.json b/lib/zh-tw/diagnosticMessages.generated.json index bc7bc2fccf4..bd1443da4fe 100644 --- a/lib/zh-tw/diagnosticMessages.generated.json +++ b/lib/zh-tw/diagnosticMessages.generated.json @@ -224,7 +224,7 @@ "Cannot_find_name_0_Did_you_mean_the_static_member_1_0_2662": "找不到名稱 '{0}'。您要找的是此靜態成員 '{1}.{0}' 嗎?", "Cannot_find_namespace_0_2503": "找不到命名空間 '{0}'。", "Cannot_find_parameter_0_1225": "找不到參數 '{0}'。", - "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "找不到輸入檔案的一般子目錄路徑。", + "Cannot_find_the_common_subdirectory_path_for_the_input_files_5009": "找不到輸入檔的一般子目錄路徑。", "Cannot_find_type_definition_file_for_0_2688": "找不到 '{0}' 的類型定義檔案。", "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "無法匯入型別宣告檔案。請考慮匯入 '{0}' 而不是 '{1}'。", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "無法初始化區塊範圍宣告 '{1}' 之同一範圍中的外部範圍變數 '{0}'。", @@ -817,7 +817,7 @@ "Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix_6060": "指定發出檔案時要用的行尾順序: 'CRLF' (DOS) 或 'LF' (UNIX)。", "Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations_6004": "指定偵錯工具尋找 TypeScript 檔案的位置,而非原始檔位置。", "Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations_6003": "指定偵錯工具尋找對應檔的位置,而非產生的位置。", - "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "指定輸入檔案的根目錄。用以控制具有 --outDir 的輸出目錄結構。", + "Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir_6058": "指定輸入檔的根目錄。用以控制具有 --outDir 的輸出目錄結構。", "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472": "只有當目標為 ECMAScript 5 及更高版本時,才可使用 'new' 運算式中的擴張運算子。", "Spread_types_may_only_be_created_from_object_types_2698": "Spread 類型只能從物件類型建立。", "Starting_compilation_in_watch_mode_6031": "在監看模式中開始編譯...", @@ -992,7 +992,7 @@ "Variable_declaration_expected_1134": "必須是變數宣告。", "Variable_declaration_list_cannot_be_empty_1123": "變數宣告清單不得為空白。", "Version_0_6029": "版本 {0}", - "Watch_input_files_6005": "監看輸入檔案。", + "Watch_input_files_6005": "監看輸入檔。", "Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen_6191": "是否要將已過期的主控台輸出,維持在監看模式下,而非清除螢幕。", "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001": "您無法重新命名標準 TypeScript 程式庫中所定義的項目。", "You_cannot_rename_this_element_8000": "您無法重新命名這個項目。",