diff --git a/.npmignore b/.npmignore index 3af34bded4a..d295e9bbd77 100644 --- a/.npmignore +++ b/.npmignore @@ -1,5 +1,6 @@ built doc +lib/README.md scripts src tests diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2e2c28590c2..68d88854849 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,6 +32,19 @@ Your pull request should: * Follow the code conventions descriped in [Coding guidelines](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines) * To avoid line ending issues, set `autocrlf = input` and `whitespace = cr-at-eol` in your git configuration +## Contributing `lib.d.ts` fixes + +The library sources are in: [src/lib](https://github.com/Microsoft/TypeScript/tree/master/src/lib) + +To build the library files, run +```Shell +jake lib +``` + +#### `src/lib/dom.generated.d.ts` and `src/lib/webworker.generated.d.ts` + +These two files represent the DOM typings and are auto-generated. To make any modifications to them, please submit a PR to https://github.com/Microsoft/TSJS-lib-generator + ## Running the Tests To run all tests, invoke the `runtests` target using jake: diff --git a/Jakefile.js b/Jakefile.js index 6a1ac19f456..14bf047cf21 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -147,7 +147,8 @@ var harnessSources = harnessCoreSources.concat([ "transpile.ts", "reuseProgramStructure.ts", "cachingInServerLSHost.ts", - "moduleResolution.ts" + "moduleResolution.ts", + "tsconfigParsing.ts" ].map(function (f) { return path.join(unittestsDirectory, f); })).concat([ @@ -227,7 +228,7 @@ var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename); function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOutFile, generateDeclarations, outDir, preserveConstEnums, keepComments, noResolve, stripInternal, callback) { file(outFile, prereqs, function() { var compilerPath = useBuiltCompiler ? builtLocalCompiler : LKGCompiler; - var options = "--module commonjs --noImplicitAny --noEmitOnError"; + var options = "--module commonjs --noImplicitAny --noEmitOnError --pretty"; // Keep comments when specifically requested // or when in debug mode. @@ -858,6 +859,7 @@ var tslintRuleDir = "scripts/tslint"; var tslintRules = ([ "nextLineRule", "noNullRule", + "preferConstRule", "booleanTriviaRule", "typeOperatorSpacingRule" ]); diff --git a/lib/README.md b/lib/README.md new file mode 100644 index 00000000000..b2837989505 --- /dev/null +++ b/lib/README.md @@ -0,0 +1,4 @@ +# Read this! + +These files are not meant to be edited by hand. +If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory. \ No newline at end of file diff --git a/lib/tsc.js b/lib/tsc.js index 511fc67c0aa..bbbcedf0f47 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -49,40 +49,49 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function createFileMap(getCanonicalFileName) { + function createFileMap(keyMapper) { var files = {}; return { get: get, set: set, contains: contains, remove: remove, - clear: clear, - forEachValue: forEachValueInMap + forEachValue: forEachValueInMap, + clear: clear }; - function set(fileName, value) { - files[normalizeKey(fileName)] = value; - } - function get(fileName) { - return files[normalizeKey(fileName)]; - } - function contains(fileName) { - return hasProperty(files, normalizeKey(fileName)); - } - function remove(fileName) { - var key = normalizeKey(fileName); - delete files[key]; - } function forEachValueInMap(f) { - forEachValue(files, f); + for (var key in files) { + f(key, files[key]); + } } - function normalizeKey(key) { - return getCanonicalFileName(normalizeSlashes(key)); + function get(path) { + return files[toKey(path)]; + } + function set(path, value) { + files[toKey(path)] = value; + } + function contains(path) { + return hasProperty(files, toKey(path)); + } + function remove(path) { + var key = toKey(path); + delete files[key]; } function clear() { files = {}; } + function toKey(path) { + return keyMapper ? keyMapper(path) : path; + } } ts.createFileMap = createFileMap; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; function forEach(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { @@ -97,8 +106,8 @@ var ts; ts.forEach = forEach; function contains(array, value) { if (array) { - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var v = array_1[_i]; if (v === value) { return true; } @@ -121,8 +130,8 @@ var ts; function countWhere(array, predicate) { var count = 0; if (array) { - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (predicate(v)) { count++; } @@ -135,8 +144,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var item = array[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; if (f(item)) { result.push(item); } @@ -149,8 +158,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; result.push(f(v)); } } @@ -169,8 +178,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var item = array[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; if (!contains(result, item)) { result.push(item); } @@ -181,8 +190,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -190,8 +199,8 @@ var ts; ts.sum = sum; function addRange(to, from) { if (to && from) { - for (var _i = 0; _i < from.length; _i++) { - var v = from[_i]; + for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { + var v = from_1[_i]; to.push(v); } } @@ -512,8 +521,8 @@ var ts; function getNormalizedParts(normalizedSlashedPath, rootLength) { var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); var normalized = []; - for (var _i = 0; _i < parts.length; _i++) { - var part = parts[_i]; + for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { + var part = parts_1[_i]; if (part !== ".") { if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { normalized.pop(); @@ -661,8 +670,8 @@ var ts; if (!fileName) { return false; } - for (var _i = 0; _i < ts.supportedExtensions.length; _i++) { - var extension = ts.supportedExtensions[_i]; + for (var _i = 0, supportedExtensions_1 = ts.supportedExtensions; _i < supportedExtensions_1.length; _i++) { + var extension = supportedExtensions_1[_i]; if (fileExtensionIs(fileName, extension)) { return true; } @@ -672,8 +681,8 @@ var ts; ts.isSupportedSourceFileName = isSupportedSourceFileName; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { - for (var _i = 0; _i < extensionsToRemove.length; _i++) { - var ext = extensionsToRemove[_i]; + for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { + var ext = extensionsToRemove_1[_i]; if (fileExtensionIs(path, ext)) { return path.substr(0, path.length - ext.length); } @@ -747,8 +756,8 @@ var ts; })(Debug = ts.Debug || (ts.Debug = {})); function copyListRemovingItem(item, list) { var copiedList = []; - for (var _i = 0; _i < list.length; _i++) { - var e = list[_i]; + for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { + var e = list_1[_i]; if (e !== item) { copiedList.push(e); } @@ -834,16 +843,16 @@ var ts; function visitDirectory(path) { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0; _i < files.length; _i++) { - var current = files[_i]; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; var name_1 = ts.combinePaths(path, current); if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { result.push(name_1); } } var subfolders = getNames(folder.subfolders); - for (var _a = 0; _a < subfolders.length; _a++) { - var current = subfolders[_a]; + for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { + var current = subfolders_1[_a]; var name_2 = ts.combinePaths(path, current); if (!ts.contains(exclude, getCanonicalPath(name_2))) { visitDirectory(name_2); @@ -894,6 +903,7 @@ var ts; var _fs = require("fs"); var _path = require("path"); var _os = require("os"); + var _tty = require("tty"); function createWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } if (chunkSize === void 0) { chunkSize = 30; } @@ -1006,8 +1016,8 @@ var ts; function visitDirectory(path) { var files = _fs.readdirSync(path || ".").sort(); var directories = []; - for (var _i = 0; _i < files.length; _i++) { - var current = files[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var current = files_2[_i]; var name_3 = ts.combinePaths(path, current); if (!ts.contains(exclude, getCanonicalPath(name_3))) { var stat = _fs.statSync(name_3); @@ -1021,8 +1031,8 @@ var ts; } } } - for (var _a = 0; _a < directories.length; _a++) { - var current = directories[_a]; + for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { + var current = directories_1[_a]; visitDirectory(current); } } @@ -1032,14 +1042,7 @@ var ts; newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, write: function (s) { - var buffer = new Buffer(s, "utf8"); - var offset = 0; - var toWrite = buffer.length; - var written = 0; - while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) { - offset += written; - toWrite -= written; - } + process.stdout.write(s); }, readFile: readFile, writeFile: writeFile, @@ -1306,6 +1309,7 @@ var ts; await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher_1311", message: "Async functions are only available when targeting ECMAScript 6 and higher." }, can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, + The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -1358,7 +1362,7 @@ var ts; Neither_type_0_nor_type_1_is_assignable_to_the_other: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Neither_type_0_nor_type_1_is_assignable_to_the_other_2352", message: "Neither type '{0}' nor type '{1}' is assignable to the other." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, No_best_common_type_exists_among_return_expressions: { code: 2354, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_return_expressions_2354", message: "No best common type exists among return expressions." }, - A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_th_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement." }, + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, @@ -1379,7 +1383,7 @@ var ts; Duplicate_number_index_signature: { code: 2375, category: ts.DiagnosticCategory.Error, key: "Duplicate_number_index_signature_2375", message: "Duplicate number index signature." }, A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: 2376, category: ts.DiagnosticCategory.Error, key: "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", message: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." }, Constructors_for_derived_classes_must_contain_a_super_call: { code: 2377, category: ts.DiagnosticCategory.Error, key: "Constructors_for_derived_classes_must_contain_a_super_call_2377", message: "Constructors for derived classes must contain a 'super' call." }, - A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement_2378", message: "A 'get' accessor must return a value or consist of a single 'throw' statement." }, + A_get_accessor_must_return_a_value: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_2378", message: "A 'get' accessor must return a value." }, Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2379, category: ts.DiagnosticCategory.Error, key: "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", message: "Getter and setter accessors do not agree in visibility." }, get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, @@ -1669,8 +1673,6 @@ var ts; NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "NEWLINE" }, Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: ts.DiagnosticCategory.Error, key: "Argument_for_newLine_option_must_be_CRLF_or_LF_6062", message: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, Argument_for_moduleResolution_option_must_be_node_or_classic: { code: 6063, category: ts.DiagnosticCategory.Error, key: "Argument_for_moduleResolution_option_must_be_node_or_classic_6063", message: "Argument for '--moduleResolution' option must be 'node' or 'classic'." }, - Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, - Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, @@ -1678,7 +1680,14 @@ var ts; Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: ts.DiagnosticCategory.Message, key: "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", message: "Initializes a TypeScript project and creates a tsconfig.json file." }, Successfully_created_a_tsconfig_json_file: { code: 6071, category: ts.DiagnosticCategory.Message, key: "Successfully_created_a_tsconfig_json_file_6071", message: "Successfully created a tsconfig.json file." }, Suppress_excess_property_checks_for_object_literals: { code: 6072, category: ts.DiagnosticCategory.Message, key: "Suppress_excess_property_checks_for_object_literals_6072", message: "Suppress excess property checks for object literals." }, - Disallow_inconsistently_cased_references_to_the_same_file: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6073", message: "Disallow inconsistently-cased references to the same file." }, + Stylize_errors_and_messages_using_color_and_context_experimental: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Stylize_errors_and_messages_using_color_and_context_experimental_6073", message: "Stylize errors and messages using color and context. (experimental)" }, + Do_not_report_errors_on_unused_labels: { code: 6074, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unused_labels_6074", message: "Do not report errors on unused labels." }, + Report_error_when_not_all_code_paths_in_function_return_a_value: { code: 6075, category: ts.DiagnosticCategory.Message, key: "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", message: "Report error when not all code paths in function return a value." }, + Report_errors_for_fallthrough_cases_in_switch_statement: { code: 6076, category: ts.DiagnosticCategory.Message, key: "Report_errors_for_fallthrough_cases_in_switch_statement_6076", message: "Report errors for fallthrough cases in switch statement." }, + Do_not_report_errors_on_unreachable_code: { code: 6077, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unreachable_code_6077", message: "Do not report errors on unreachable code." }, + Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, + Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, + Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -1696,6 +1705,10 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", message: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: ts.DiagnosticCategory.Error, key: "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", message: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." }, JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", message: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists" }, + Unreachable_code_detected: { code: 7027, category: ts.DiagnosticCategory.Error, key: "Unreachable_code_detected_7027", message: "Unreachable code detected." }, + Unused_label: { code: 7028, category: ts.DiagnosticCategory.Error, key: "Unused_label_7028", message: "Unused label." }, + Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, + Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -3082,6 +3095,13 @@ var ts; var ts; (function (ts) { ts.bindTime = 0; + function or(state1, state2) { + return (state1 | state2) & 2 + ? 2 + : (state1 & state2) & 8 + ? 8 + : 4; + } function getModuleInstanceState(node) { if (node.kind === 215 || node.kind === 216) { return 0; @@ -3089,7 +3109,7 @@ var ts; else if (ts.isConstEnumDeclaration(node)) { return 2; } - else if ((node.kind === 222 || node.kind === 221) && !(node.flags & 1)) { + else if ((node.kind === 222 || node.kind === 221) && !(node.flags & 2)) { return 0; } else if (node.kind === 219) { @@ -3116,28 +3136,52 @@ var ts; } } ts.getModuleInstanceState = getModuleInstanceState; - function bindSourceFile(file) { + var binder = createBinder(); + function bindSourceFile(file, options) { var start = new Date().getTime(); - bindSourceFileWorker(file); + binder(file, options); ts.bindTime += new Date().getTime() - start; } ts.bindSourceFile = bindSourceFile; - function bindSourceFileWorker(file) { + function createBinder() { + var file; + var options; var parent; var container; var blockScopeContainer; var lastContainer; var seenThisKeyword; - var inStrictMode = !!file.externalModuleIndicator; + var hasExplicitReturn; + var currentReachabilityState; + var labelStack; + var labelIndexMap; + var implicitLabels; + var inStrictMode; var symbolCount = 0; - var Symbol = ts.objectAllocator.getSymbolConstructor(); - var classifiableNames = {}; - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; + var Symbol; + var classifiableNames; + function bindSourceFile(f, opts) { + file = f; + options = opts; + inStrictMode = !!file.externalModuleIndicator; + classifiableNames = {}; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + hasExplicitReturn = false; + labelStack = undefined; + labelIndexMap = undefined; + implicitLabels = undefined; } - return; + return bindSourceFile; function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -3188,7 +3232,7 @@ var ts; return node.isExportEquals ? "export=" : "default"; case 213: case 214: - return node.flags & 1024 ? "default" : undefined; + return node.flags & 512 ? "default" : undefined; } } function getDisplayName(node) { @@ -3196,7 +3240,7 @@ var ts; } function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = node.flags & 1024; + var isDefaultExport = node.flags & 512; var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; if (name !== undefined) { @@ -3214,7 +3258,7 @@ var ts; ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 1024) { + if (declaration.flags & 512) { message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } }); @@ -3233,7 +3277,7 @@ var ts; return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedNodeFlags(node) & 1; + var hasExportModifier = ts.getCombinedNodeFlags(node) & 2; if (symbolFlags & 8388608) { if (node.kind === 230 || (node.kind === 221 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -3243,7 +3287,7 @@ var ts; } } else { - if (hasExportModifier || container.flags & 262144) { + if (hasExportModifier || container.flags & 131072) { var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | (symbolFlags & 793056 ? 2097152 : 0) | (symbolFlags & 1536 ? 4194304 : 0); @@ -3274,18 +3318,202 @@ var ts; blockScopeContainer = node; blockScopeContainer.locals = undefined; } - if (node.kind === 215) { + var savedReachabilityState; + var savedLabelStack; + var savedLabels; + var savedImplicitLabels; + var savedHasExplicitReturn; + var kind = node.kind; + var flags = node.flags; + flags &= ~1572864; + if (kind === 215) { seenThisKeyword = false; - ts.forEachChild(node, bind); - node.flags = seenThisKeyword ? node.flags | 524288 : node.flags & ~524288; } - else { - ts.forEachChild(node, bind); + var saveState = kind === 248 || kind === 219 || ts.isFunctionLikeKind(kind); + if (saveState) { + savedReachabilityState = currentReachabilityState; + savedLabelStack = labelStack; + savedLabels = labelIndexMap; + savedImplicitLabels = implicitLabels; + savedHasExplicitReturn = hasExplicitReturn; + currentReachabilityState = 2; + hasExplicitReturn = false; + labelStack = labelIndexMap = implicitLabels = undefined; + } + bindReachableStatement(node); + if (currentReachabilityState === 2 && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) { + flags |= 524288; + if (hasExplicitReturn) { + flags |= 1048576; + } + } + if (kind === 215) { + flags = seenThisKeyword ? flags | 262144 : flags & ~262144; + } + node.flags = flags; + if (saveState) { + hasExplicitReturn = savedHasExplicitReturn; + currentReachabilityState = savedReachabilityState; + labelStack = savedLabelStack; + labelIndexMap = savedLabels; + implicitLabels = savedImplicitLabels; } container = saveContainer; parent = saveParent; blockScopeContainer = savedBlockScopeContainer; } + function bindReachableStatement(node) { + if (checkUnreachable(node)) { + ts.forEachChild(node, bind); + return; + } + switch (node.kind) { + case 198: + bindWhileStatement(node); + break; + case 197: + bindDoStatement(node); + break; + case 199: + bindForStatement(node); + break; + case 200: + case 201: + bindForInOrForOfStatement(node); + break; + case 196: + bindIfStatement(node); + break; + case 204: + case 208: + bindReturnOrThrow(node); + break; + case 203: + case 202: + bindBreakOrContinueStatement(node); + break; + case 209: + bindTryStatement(node); + break; + case 206: + bindSwitchStatement(node); + break; + case 220: + bindCaseBlock(node); + break; + case 207: + bindLabeledStatement(node); + break; + default: + ts.forEachChild(node, bind); + break; + } + } + function bindWhileStatement(n) { + var preWhileState = n.expression.kind === 84 ? 4 : currentReachabilityState; + var postWhileState = n.expression.kind === 99 ? 4 : currentReachabilityState; + bind(n.expression); + currentReachabilityState = preWhileState; + var postWhileLabel = pushImplicitLabel(); + bind(n.statement); + popImplicitLabel(postWhileLabel, postWhileState); + } + function bindDoStatement(n) { + var preDoState = currentReachabilityState; + var postDoLabel = pushImplicitLabel(); + bind(n.statement); + var postDoState = n.expression.kind === 99 ? 4 : preDoState; + popImplicitLabel(postDoLabel, postDoState); + bind(n.expression); + } + function bindForStatement(n) { + var preForState = currentReachabilityState; + var postForLabel = pushImplicitLabel(); + bind(n.initializer); + bind(n.condition); + bind(n.incrementor); + bind(n.statement); + var isInfiniteLoop = (!n.condition || n.condition.kind === 99); + var postForState = isInfiniteLoop ? 4 : preForState; + popImplicitLabel(postForLabel, postForState); + } + function bindForInOrForOfStatement(n) { + var preStatementState = currentReachabilityState; + var postStatementLabel = pushImplicitLabel(); + bind(n.initializer); + bind(n.expression); + bind(n.statement); + popImplicitLabel(postStatementLabel, preStatementState); + } + function bindIfStatement(n) { + var ifTrueState = n.expression.kind === 84 ? 4 : currentReachabilityState; + var ifFalseState = n.expression.kind === 99 ? 4 : currentReachabilityState; + currentReachabilityState = ifTrueState; + bind(n.expression); + bind(n.thenStatement); + if (n.elseStatement) { + var preElseState = currentReachabilityState; + currentReachabilityState = ifFalseState; + bind(n.elseStatement); + currentReachabilityState = or(currentReachabilityState, preElseState); + } + else { + currentReachabilityState = or(currentReachabilityState, ifFalseState); + } + } + function bindReturnOrThrow(n) { + bind(n.expression); + if (n.kind === 204) { + hasExplicitReturn = true; + } + currentReachabilityState = 4; + } + function bindBreakOrContinueStatement(n) { + bind(n.label); + var isValidJump = jumpToLabel(n.label, n.kind === 203 ? currentReachabilityState : 4); + if (isValidJump) { + currentReachabilityState = 4; + } + } + function bindTryStatement(n) { + var preTryState = currentReachabilityState; + bind(n.tryBlock); + var postTryState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.catchClause); + var postCatchState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.finallyBlock); + currentReachabilityState = or(postTryState, postCatchState); + } + function bindSwitchStatement(n) { + var preSwitchState = currentReachabilityState; + var postSwitchLabel = pushImplicitLabel(); + bind(n.expression); + bind(n.caseBlock); + var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242; }); + var postSwitchState = hasDefault && currentReachabilityState !== 2 ? 4 : preSwitchState; + popImplicitLabel(postSwitchLabel, postSwitchState); + } + function bindCaseBlock(n) { + var startState = currentReachabilityState; + for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + currentReachabilityState = startState; + bind(clause); + if (clause.statements.length && currentReachabilityState === 2 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + } + function bindLabeledStatement(n) { + bind(n.label); + var ok = pushNamedLabel(n.label); + bind(n.statement); + if (ok) { + popNamedLabel(n.label, currentReachabilityState); + } + } function getContainerFlags(node) { switch (node.kind) { case 186: @@ -3365,7 +3593,7 @@ var ts; } } function declareClassMember(node, symbolFlags, symbolExcludes) { - return node.flags & 128 + return node.flags & 64 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } @@ -3374,15 +3602,6 @@ var ts; ? declareModuleMember(node, symbolFlags, symbolExcludes) : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } - function isAmbientContext(node) { - while (node) { - if (node.flags & 2) { - return true; - } - node = node.parent; - } - return false; - } function hasExportDeclarations(node) { var body = node.kind === 248 ? node : node.body; if (body.kind === 248 || body.kind === 219) { @@ -3396,11 +3615,11 @@ var ts; return false; } function setExportContextFlag(node) { - if (isAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 262144; + if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 131072; } else { - node.flags &= ~262144; + node.flags &= ~131072; } } function bindModuleDeclaration(node) { @@ -3551,7 +3770,7 @@ var ts; } } function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.flags & 65536) { + if (inStrictMode && node.flags & 32768) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } @@ -3569,10 +3788,10 @@ var ts; } function checkStrictModeWithStatement(node) { if (inStrictMode) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); } } - function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + function errorOnFirstToken(node, message, arg0, arg1, arg2) { var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } @@ -3580,6 +3799,9 @@ var ts; return "__" + ts.indexOf(node.parent.parameters, node); } function bind(node) { + if (!node) { + return; + } node.parent = parent; var savedInStrictMode = inStrictMode; if (!savedInStrictMode) { @@ -3607,8 +3829,8 @@ var ts; } } function updateStrictModeStatementList(statements) { - for (var _i = 0; _i < statements.length; _i++) { - var statement = statements[_i]; + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; if (!ts.isPrologueDirective(statement)) { return; } @@ -3795,7 +4017,7 @@ var ts; else { declareSymbolAndAddToSymbolTable(node, 1, 107455); } - if (node.flags & 112 && + if (node.flags & 56 && node.parent.kind === 144 && ts.isClassLike(node.parent.parent)) { var classDeclaration = node.parent.parent; @@ -3807,6 +4029,95 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } + function pushNamedLabel(name) { + initializeReachabilityStateIfNecessary(); + if (ts.hasProperty(labelIndexMap, name.text)) { + return false; + } + labelIndexMap[name.text] = labelStack.push(1) - 1; + return true; + } + function pushImplicitLabel() { + initializeReachabilityStateIfNecessary(); + var index = labelStack.push(1) - 1; + implicitLabels.push(index); + return index; + } + function popNamedLabel(label, outerState) { + var index = labelIndexMap[label.text]; + ts.Debug.assert(index !== undefined); + ts.Debug.assert(labelStack.length == index + 1); + labelIndexMap[label.text] = undefined; + setCurrentStateAtLabel(labelStack.pop(), outerState, label); + } + function popImplicitLabel(implicitLabelIndex, outerState) { + if (labelStack.length !== implicitLabelIndex + 1) { + ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex); + } + var i = implicitLabels.pop(); + if (implicitLabelIndex !== i) { + ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex); + } + setCurrentStateAtLabel(labelStack.pop(), outerState, undefined); + } + function setCurrentStateAtLabel(innerMergedState, outerState, label) { + if (innerMergedState === 1) { + if (label && !options.allowUnusedLabels) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label)); + } + currentReachabilityState = outerState; + } + else { + currentReachabilityState = or(innerMergedState, outerState); + } + } + function jumpToLabel(label, outerState) { + initializeReachabilityStateIfNecessary(); + var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels); + if (index === undefined) { + return false; + } + var stateAtLabel = labelStack[index]; + labelStack[index] = stateAtLabel === 1 ? outerState : or(stateAtLabel, outerState); + return true; + } + function checkUnreachable(node) { + switch (currentReachabilityState) { + case 4: + var reportError = ts.isStatement(node) || + node.kind === 214 || + (node.kind === 218 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 217 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + if (reportError) { + currentReachabilityState = 8; + var reportUnreachableCode = !options.allowUnreachableCode && + !ts.isInAmbientContext(node) && + (node.kind !== 193 || + ts.getCombinedNodeFlags(node.declarationList) & 24576 || + ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); + if (reportUnreachableCode) { + errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + } + } + case 8: + return true; + default: + return false; + } + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); + } + } + function initializeReachabilityStateIfNecessary() { + if (labelIndexMap) { + return; + } + currentReachabilityState = 2; + labelIndexMap = {}; + labelStack = []; + implicitLabels = []; + } } })(ts || (ts = {})); var ts; @@ -3814,8 +4125,8 @@ var ts; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; if (declaration.kind === kind) { return declaration; } @@ -3985,7 +4296,7 @@ var ts; } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 49152) !== 0 || + return (getCombinedNodeFlags(declaration) & 24576) !== 0 || isCatchClauseVariableDeclaration(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; @@ -4086,7 +4397,7 @@ var ts; } ts.isExternalModule = isExternalModule; function isDeclarationFile(file) { - return (file.flags & 8192) !== 0; + return (file.flags & 4096) !== 0; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { @@ -4116,11 +4427,11 @@ var ts; } ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(getCombinedNodeFlags(node) & 32768); + return !!(getCombinedNodeFlags(node) & 16384); } ts.isConst = isConst; function isLet(node) { - return !!(getCombinedNodeFlags(node) & 16384); + return !!(getCombinedNodeFlags(node) & 8192); } ts.isLet = isLet; function isPrologueDirective(node) { @@ -4299,27 +4610,28 @@ var ts; } ts.isClassLike = isClassLike; function isFunctionLike(node) { - if (node) { - switch (node.kind) { - case 144: - case 173: - case 213: - case 174: - case 143: - case 142: - case 145: - case 146: - case 147: - case 148: - case 149: - case 152: - case 153: - return true; - } - } - return false; + return node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; + function isFunctionLikeKind(kind) { + switch (kind) { + case 144: + case 173: + case 213: + case 174: + case 143: + case 142: + case 145: + case 146: + case 147: + case 148: + case 149: + case 152: + case 153: + return true; + } + } + ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 143: @@ -4783,9 +5095,18 @@ var ts; return !!node && (node.kind === 162 || node.kind === 161); } ts.isBindingPattern = isBindingPattern; + function isNodeDescendentOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + ts.isNodeDescendentOf = isNodeDescendentOf; function isInAmbientContext(node) { while (node) { - if (node.flags & (2 | 8192)) { + if (node.flags & (4 | 4096)) { return true; } node = node.parent; @@ -4843,7 +5164,7 @@ var ts; case 207: case 204: case 206: - case 98: + case 208: case 209: case 193: case 198: @@ -4942,8 +5263,8 @@ var ts; ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; function getHeritageClause(clauses, kind) { if (clauses) { - for (var _i = 0; _i < clauses.length; _i++) { - var clause = clauses[_i]; + for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { + var clause = clauses_1[_i]; if (clause.token === kind) { return clause; } @@ -4955,7 +5276,6 @@ var ts; function tryResolveScriptReference(host, sourceFile, reference) { if (!host.getCompilerOptions().noResolve) { var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); - referenceFileName = ts.getNormalizedAbsolutePath(referenceFileName, host.getCurrentDirectory()); return host.getSourceFile(referenceFileName); } } @@ -5013,7 +5333,7 @@ var ts; } ts.isTrivia = isTrivia; function isAsyncFunctionLike(node) { - return isFunctionLike(node) && (node.flags & 512) !== 0 && !isAccessor(node); + return isFunctionLike(node) && (node.flags & 256) !== 0 && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; function hasDynamicName(declaration) { @@ -5371,7 +5691,7 @@ var ts; else { ts.forEach(declarations, function (member) { if ((member.kind === 145 || member.kind === 146) - && (member.flags & 128) === (accessor.flags & 128)) { + && (member.flags & 64) === (accessor.flags & 64)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -5426,6 +5746,49 @@ var ts; }); } ts.emitComments = emitComments; + function emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, removeComments) { + var leadingComments; + var currentDetachedCommentInfo; + if (removeComments) { + if (node.pos === 0) { + leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment); + } + } + else { + leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment; + for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { + var comment = leadingComments_1[_i]; + if (lastComment) { + var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); + var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); + if (commentLine >= lastCommentLine + 2) { + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + var lastCommentLine = getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); + var nodeLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedComment(comment) { + return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 && + currentSourceFile.text.charCodeAt(comment.pos + 2) === 33; + } + } + ts.emitDetachedComments = emitDetachedComments; function writeCommentRange(currentSourceFile, writer, comment, newLine) { if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42) { var firstCommentLineAndCharacter = ts.getLineAndCharacterOfPosition(currentSourceFile, comment.pos); @@ -5490,16 +5853,16 @@ var ts; ts.writeCommentRange = writeCommentRange; function modifierToFlag(token) { switch (token) { - case 113: return 128; - case 112: return 16; - case 111: return 64; - case 110: return 32; - case 115: return 256; - case 82: return 1; - case 122: return 2; - case 74: return 32768; - case 77: return 1024; - case 118: return 512; + case 113: return 64; + case 112: return 8; + case 111: return 32; + case 110: return 16; + case 115: return 128; + case 82: return 2; + case 122: return 4; + case 74: return 16384; + case 77: return 512; + case 118: return 256; } return 0; } @@ -5578,7 +5941,7 @@ var ts; } ts.isEmptyObjectLiteralOrArrayLiteral = isEmptyObjectLiteralOrArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 1024) ? symbol.valueDeclaration.localSymbol : undefined; + return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function isJavaScript(fileName) { @@ -5642,6 +6005,12 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !ts.isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -5814,8 +6183,8 @@ var ts; } function visitEachNode(cbNode, nodes) { if (nodes) { - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; var result = cbNode(node); if (result) { return result; @@ -6276,8 +6645,8 @@ var ts; function addJSDocComment(node) { var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); if (comments) { - for (var _i = 0; _i < comments.length; _i++) { - var comment = comments[_i]; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); if (jsDocComment) { node.jsDocComment = jsDocComment; @@ -6308,7 +6677,7 @@ var ts; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); - sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 8192 : 0; + sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 : 0; sourceFile.languageVariant = ts.isTsx(sourceFile.fileName) ? 1 : 0; return sourceFile; } @@ -7144,7 +7513,7 @@ var ts; if (node.kind === 8 && sourceText.charCodeAt(tokenPos) === 48 && ts.isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { - node.flags |= 65536; + node.flags |= 32768; } return node; } @@ -7713,7 +8082,7 @@ var ts; if (!arrowFunction) { return undefined; } - var isAsync = !!(arrowFunction.flags & 512); + var isAsync = !!(arrowFunction.flags & 256); var lastToken = token; arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 || lastToken === 15) @@ -7805,7 +8174,7 @@ var ts; function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(174); setModifiers(node, parseModifiersForArrowFunction()); - var isAsync = !!(node.flags & 512); + var isAsync = !!(node.flags & 256); fillSignature(54, false, isAsync, !allowAmbiguity, node); if (!node.parameters) { return undefined; @@ -8419,7 +8788,7 @@ var ts; var node = createNode(164); parseExpected(19); if (scanner.hasPrecedingLineBreak()) - node.flags |= 2048; + node.flags |= 1024; node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); parseExpected(20); return finishNode(node); @@ -8474,7 +8843,7 @@ var ts; var node = createNode(165); parseExpected(15); if (scanner.hasPrecedingLineBreak()) { - node.flags |= 2048; + node.flags |= 1024; } node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); parseExpected(16); @@ -8490,7 +8859,7 @@ var ts; parseExpected(87); node.asteriskToken = parseOptionalToken(37); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 512); + var isAsync = !!(node.flags & 256); node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -9028,10 +9397,10 @@ var ts; case 102: break; case 108: - node.flags |= 16384; + node.flags |= 8192; break; case 74: - node.flags |= 32768; + node.flags |= 16384; break; default: ts.Debug.fail(); @@ -9065,9 +9434,9 @@ var ts; setModifiers(node, modifiers); parseExpected(87); node.asteriskToken = parseOptionalToken(37); - node.name = node.flags & 1024 ? parseOptionalIdentifier() : parseIdentifier(); + node.name = node.flags & 512 ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 512); + var isAsync = !!(node.flags & 256); fillSignature(54, isGenerator, isAsync, false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return finishNode(node); @@ -9089,7 +9458,7 @@ var ts; method.name = name; method.questionToken = questionToken; var isGenerator = !!asteriskToken; - var isAsync = !!(method.flags & 512); + var isAsync = !!(method.flags & 256); fillSignature(54, isGenerator, isAsync, false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return finishNode(method); @@ -9101,7 +9470,7 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - property.initializer = modifiers && modifiers.flags & 128 + property.initializer = modifiers && modifiers.flags & 64 ? allowInAnd(parseNonParameterInitializer) : doOutsideOfContext(2 | 1, parseNonParameterInitializer); parseSemicolon(); @@ -9391,13 +9760,13 @@ var ts; } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { var node = createNode(218, fullStart); - var namespaceFlag = flags & 131072; + var namespaceFlag = flags & 65536; node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(21) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 1 | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 2 | namespaceFlag) : parseModuleBlock(); return finishNode(node); } @@ -9412,7 +9781,7 @@ var ts; function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; if (parseOptional(126)) { - flags |= 131072; + flags |= 65536; } else { parseExpected(125); @@ -9626,7 +9995,7 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return node.flags & 1 + return node.flags & 2 || node.kind === 221 && node.moduleReference.kind === 232 || node.kind === 222 || node.kind === 227 @@ -10200,8 +10569,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0; _i < array.length; _i++) { - var node = array[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var node = array_7[_i]; visitNode(node); } } @@ -10273,8 +10642,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0; _i < array.length; _i++) { - var node = array[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } return; @@ -10547,6 +10916,7 @@ var ts; var getInstantiatedGlobalPromiseLikeType; var getGlobalPromiseConstructorLikeType; var getGlobalThenableType; + var jsxElementClassType; var tupleTypes = {}; var unionTypes = {}; var intersectionTypes = {}; @@ -10795,7 +11165,7 @@ var ts; } var initializerOfNonStaticProperty = current.parent && current.parent.kind === 141 && - (current.parent.flags & 128) === 0 && + (current.parent.flags & 64) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -10854,7 +11224,7 @@ var ts; break; case 141: case 140: - if (ts.isClassLike(location.parent) && !(location.flags & 128)) { + if (ts.isClassLike(location.parent) && !(location.flags & 64)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455)) { @@ -10867,7 +11237,7 @@ var ts; case 186: case 215: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { - if (lastLocation && lastLocation.flags & 128) { + if (lastLocation && lastLocation.flags & 64) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; } @@ -11301,8 +11671,8 @@ var ts; } function findConstructorDeclaration(node) { var members = node.members; - for (var _i = 0; _i < members.length; _i++) { - var member = members[_i]; + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var member = members_1[_i]; if (member.kind === 144 && ts.nodeIsPresent(member.body)) { return member; } @@ -11508,7 +11878,7 @@ var ts; if (!isDeclarationVisible(declaration)) { var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 1) && + !(anyImportSyntax.flags & 2) && isDeclarationVisible(anyImportSyntax.parent)) { getNodeLinks(declaration).isVisible = true; if (aliasesToMakeVisible) { @@ -11638,8 +12008,8 @@ var ts; walkSymbol(getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol), getQualifiedLeftMeaning(meaning)); } if (accessibleSymbolChain) { - for (var _i = 0; _i < accessibleSymbolChain.length; _i++) { - var accessibleSymbol = accessibleSymbolChain[_i]; + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } @@ -11805,7 +12175,7 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 128; })); + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 64; })); var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { @@ -11911,8 +12281,8 @@ var ts; var t = getTypeOfSymbol(p); if (p.flags & (16 | 8192) && !getPropertiesOfObjectType(t).length) { var signatures = getSignaturesOfType(t, 0); - for (var _f = 0; _f < signatures.length; _f++) { - var signature = signatures[_f]; + for (var _f = 0, signatures_1 = signatures; _f < signatures_1.length; _f++) { + var signature = signatures_1[_f]; buildSymbolDisplay(p, writer); if (p.flags & 536870912) { writePunctuation(writer, 53); @@ -12115,7 +12485,7 @@ var ts; case 217: case 221: var parent_4 = getDeclarationContainer(node); - if (!(ts.getCombinedNodeFlags(node) & 1) && + if (!(ts.getCombinedNodeFlags(node) & 2) && !(node.kind !== 221 && parent_4.kind !== 248 && ts.isInAmbientContext(parent_4))) { return isGlobalSourceFile(parent_4); } @@ -12126,7 +12496,7 @@ var ts; case 146: case 143: case 142: - if (node.flags & (32 | 64)) { + if (node.flags & (16 | 32)) { return false; } case 144: @@ -12555,8 +12925,8 @@ var ts; } } function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); if (!typeParameters) { typeParameters = [tp]; @@ -12737,13 +13107,13 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 215) { - if (declaration.flags & 524288) { + if (declaration.flags & 262144) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { - for (var _b = 0; _b < baseTypeNodes.length; _b++) { - var node = baseTypeNodes[_b]; + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; if (ts.isSupportedExpressionWithTypeArguments(node)) { var baseSymbol = resolveEntityName(node.expression, 793056, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { @@ -12911,23 +13281,23 @@ var ts; } function createSymbolTable(symbols) { var result = {}; - for (var _i = 0; _i < symbols.length; _i++) { - var symbol = symbols[_i]; + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; result[symbol.name] = symbol; } return result; } function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { var result = {}; - for (var _i = 0; _i < symbols.length; _i++) { - var symbol = symbols[_i]; + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); } return result; } function addInheritedMembers(symbols, baseSymbols) { - for (var _i = 0; _i < baseSymbols.length; _i++) { - var s = baseSymbols[_i]; + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; if (!ts.hasProperty(symbols, s.name)) { symbols[s.name] = s; } @@ -12935,8 +13305,8 @@ var ts; } function addInheritedSignatures(signatures, baseSignatures) { if (baseSignatures) { - for (var _i = 0; _i < baseSignatures.length; _i++) { - var signature = baseSignatures[_i]; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var signature = baseSignatures_1[_i]; signatures.push(signature); } } @@ -12979,8 +13349,8 @@ var ts; members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); - for (var _i = 0; _i < baseTypes.length; _i++) { - var baseType = baseTypes[_i]; + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0)); @@ -13026,8 +13396,8 @@ var ts; var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; - for (var _i = 0; _i < baseSignatures.length; _i++) { - var baseSig = baseSignatures[_i]; + for (var _i = 0, baseSignatures_2 = baseSignatures; _i < baseSignatures_2.length; _i++) { + var baseSig = baseSignatures_2[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); @@ -13055,8 +13425,8 @@ var ts; setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); } function findMatchingSignature(signatureList, signature, partialMatch, ignoreReturnTypes) { - for (var _i = 0; _i < signatureList.length; _i++) { - var s = signatureList[_i]; + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { return s; } @@ -13110,8 +13480,8 @@ var ts; } function getUnionIndexType(types, kind) { var indexTypes = []; - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexType = getIndexTypeOfType(type, kind); if (!indexType) { return undefined; @@ -13275,12 +13645,12 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (32 | 64))) { + if (prop && !(getDeclarationFlagsFromSymbol(prop) & (16 | 32))) { if (!props) { props = [prop]; } @@ -13301,8 +13671,8 @@ var ts; } var propTypes = []; var declarations = []; - for (var _a = 0; _a < props.length; _a++) { - var prop = props[_a]; + for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { + var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } @@ -13635,8 +14005,8 @@ var ts; } function getPropagatingFlagsOfTypes(types) { var result = 0; - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type = types_3[_i]; result |= type.flags; } return result & 14680064; @@ -13757,8 +14127,8 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; switch (declaration.kind) { case 214: case 215: @@ -13856,8 +14226,8 @@ var ts; } } function addTypesToSet(typeSet, types, typeSetKind) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; addTypeToSet(typeSet, type, typeSetKind); } } @@ -13879,8 +14249,8 @@ var ts; } } function containsTypeAny(types) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (isTypeAny(type)) { return true; } @@ -13983,7 +14353,8 @@ var ts; var container = ts.getThisContainer(node, false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 215)) { - if (!(container.flags & 128)) { + if (!(container.flags & 64) && + (container.kind !== 144 || ts.isNodeDescendentOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -14048,8 +14419,8 @@ var ts; function instantiateList(items, mapper, instantiator) { if (items && items.length) { var result = []; - for (var _i = 0; _i < items.length; _i++) { - var v = items[_i]; + for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { + var v = items_1[_i]; result.push(instantiator(v, mapper)); } return result; @@ -14088,8 +14459,8 @@ var ts; case 2: return createBinaryTypeEraser(sources[0], sources[1]); } return function (t) { - for (var _i = 0; _i < sources.length; _i++) { - var source = sources[_i]; + for (var _i = 0, sources_1 = sources; _i < sources_1.length; _i++) { + var source = sources_1[_i]; if (t === source) { return anyType; } @@ -14454,8 +14825,8 @@ var ts; function eachTypeRelatedToSomeType(source, target) { var result = -1; var sourceTypes = source.types; - for (var _i = 0; _i < sourceTypes.length; _i++) { - var sourceType = sourceTypes[_i]; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; var related = typeRelatedToSomeType(sourceType, target, false); if (!related) { return 0; @@ -14477,8 +14848,8 @@ var ts; function typeRelatedToEachType(source, target, reportErrors) { var result = -1; var targetTypes = target.types; - for (var _i = 0; _i < targetTypes.length; _i++) { - var targetType = targetTypes[_i]; + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var targetType = targetTypes_1[_i]; var related = isRelatedTo(source, targetType, reportErrors); if (!related) { return 0; @@ -14500,8 +14871,8 @@ var ts; function eachTypeRelatedToType(source, target, reportErrors) { var result = -1; var sourceTypes = source.types; - for (var _i = 0; _i < sourceTypes.length; _i++) { - var sourceType = sourceTypes[_i]; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; var related = isRelatedTo(sourceType, target, reportErrors); if (!related) { return 0; @@ -14614,8 +14985,8 @@ var ts; var result = -1; var properties = getPropertiesOfObjectType(target); var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288); - for (var _i = 0; _i < properties.length; _i++) { - var targetProp = properties[_i]; + for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { + var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -14629,20 +15000,20 @@ var ts; else if (!(targetProp.flags & 134217728)) { var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); - if (sourcePropFlags & 32 || targetPropFlags & 32) { + if (sourcePropFlags & 16 || targetPropFlags & 16) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { - if (sourcePropFlags & 32 && targetPropFlags & 32) { + if (sourcePropFlags & 16 && targetPropFlags & 16) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); } else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 32 ? source : target), typeToString(sourcePropFlags & 32 ? target : source)); + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 16 ? source : target), typeToString(sourcePropFlags & 16 ? target : source)); } } return 0; } } - else if (targetPropFlags & 64) { + else if (targetPropFlags & 32) { var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32; var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; var targetClass = getDeclaredTypeOfSymbol(targetProp.parent); @@ -14653,7 +15024,7 @@ var ts; return 0; } } - else if (sourcePropFlags & 64) { + else if (sourcePropFlags & 32) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -14688,8 +15059,8 @@ var ts; return 0; } var result = -1; - for (var _i = 0; _i < sourceProperties.length; _i++) { - var sourceProp = sourceProperties[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return 0; @@ -14721,13 +15092,13 @@ var ts; return result; } } - outer: for (var _i = 0; _i < targetSignatures.length; _i++) { - var t = targetSignatures[_i]; + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; if (!t.hasStringLiterals || target.flags & 262144) { var localErrors = reportErrors; var checkedAbstractAssignability = false; - for (var _a = 0; _a < sourceSignatures.length; _a++) { - var s = sourceSignatures[_a]; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; if (!s.hasStringLiterals || source.flags & 262144) { var related = signatureRelatedTo(s, t, localErrors); if (related) { @@ -14755,8 +15126,8 @@ var ts; var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 256; - var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 256; + var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 128; + var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 128; if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { if (reportErrors) { reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); @@ -14957,8 +15328,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (32 | 64); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (32 | 64); + var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (16 | 32); + var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (16 | 32); if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -15024,8 +15395,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; if (candidate !== type && !isTypeSubtypeOf(type, candidate)) return false; } @@ -15238,8 +15609,8 @@ var ts; } function createInferenceContext(typeParameters, inferUnionTypes) { var inferences = []; - for (var _i = 0; _i < typeParameters.length; _i++) { - var unused = typeParameters[_i]; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var unused = typeParameters_1[_i]; inferences.push({ primary: undefined, secondary: undefined, isFixed: false }); @@ -15305,8 +15676,8 @@ var ts; var targetTypes = target.types; var typeParameterCount = 0; var typeParameter; - for (var _i = 0; _i < targetTypes.length; _i++) { - var t = targetTypes[_i]; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var t = targetTypes_2[_i]; if (t.flags & 512 && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; @@ -15323,8 +15694,8 @@ var ts; } else if (source.flags & 49152) { var sourceTypes = source.types; - for (var _a = 0; _a < sourceTypes.length; _a++) { - var sourceType = sourceTypes[_a]; + for (var _a = 0, sourceTypes_3 = sourceTypes; _a < sourceTypes_3.length; _a++) { + var sourceType = sourceTypes_3[_a]; inferFromTypes(sourceType, target); } } @@ -15357,8 +15728,8 @@ var ts; } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0; _i < properties.length; _i++) { - var targetProp = properties[_i]; + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var targetProp = properties_2[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -15849,7 +16220,7 @@ var ts; break; case 141: case 140: - if (container.flags & 128) { + if (container.flags & 64) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; @@ -15862,7 +16233,7 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - return container.flags & 128 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return container.flags & 64 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; } return anyType; } @@ -15890,7 +16261,7 @@ var ts; var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; if (canUseSuperExpression) { - if ((container.flags & 128) || isCallExpression) { + if ((container.flags & 64) || isCallExpression) { nodeCheckFlag = 512; } else { @@ -15935,7 +16306,7 @@ var ts; } else { if (container && ts.isClassLike(container.parent)) { - if (container.flags & 128) { + if (container.flags & 64) { return container.kind === 143 || container.kind === 142 || container.kind === 145 || @@ -16074,8 +16445,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var current = types_7[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -16239,8 +16610,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -16291,8 +16662,8 @@ var ts; var hasSpreadElement = false; var elementTypes = []; var inDestructuringPattern = isAssignmentTarget(node); - for (var _i = 0; _i < elements.length; _i++) { - var e = elements[_i]; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var e = elements_1[_i]; if (inDestructuringPattern && e.kind === 185) { var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1) || @@ -16551,8 +16922,8 @@ var ts; function checkJsxSpreadAttribute(node, elementAttributesType, nameTable) { var type = checkExpression(node.expression); var props = getPropertiesOfType(type); - for (var _i = 0; _i < props.length; _i++) { - var prop = props[_i]; + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; if (!nameTable[prop.name]) { var targetPropSym = getPropertyOfType(elementAttributesType, prop.name); if (targetPropSym) { @@ -16721,7 +17092,6 @@ var ts; var prop = getPropertyOfType(attributesType, attrib.name.text); return prop || unknownSymbol; } - var jsxElementClassType = undefined; function getJsxGlobalElementClassType() { if (!jsxElementClassType) { jsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); @@ -16788,7 +17158,7 @@ var ts; return s.valueDeclaration ? s.valueDeclaration.kind : 141; } function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 ? 16 | 128 : 0; + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 ? 8 | 64 : 0; } function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationFlagsFromSymbol(prop); @@ -16801,17 +17171,17 @@ var ts; error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } - if (flags & 256) { + if (flags & 128) { error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass)); return false; } } - if (!(flags & (32 | 64))) { + if (!(flags & (16 | 32))) { return true; } var enclosingClassDeclaration = ts.getContainingClass(node); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; - if (flags & 32) { + if (flags & 16) { if (declaringClass !== enclosingClass) { error(node, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); return false; @@ -16825,7 +17195,7 @@ var ts; error(node, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass)); return false; } - if (flags & 128) { + if (flags & 64) { return true; } if (type.flags & 33554432) { @@ -17005,8 +17375,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0; _i < signatures.length; _i++) { - var signature = signatures[_i]; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent_5 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -17417,8 +17787,8 @@ var ts; reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); } if (!produceDiagnostics) { - for (var _i = 0; _i < candidates.length; _i++) { - var candidate = candidates[_i]; + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -17437,8 +17807,8 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); } function chooseOverload(candidates, relation) { - for (var _i = 0; _i < candidates.length; _i++) { - var originalCandidate = candidates[_i]; + for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { + var originalCandidate = candidates_2[_i]; if (!hasCorrectArity(node, args, originalCandidate)) { continue; } @@ -17541,7 +17911,7 @@ var ts; return resolveErrorCall(node); } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && valueDecl.flags & 256) { + if (valueDecl && valueDecl.flags & 128) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); return resolveErrorCall(node); } @@ -17827,32 +18197,24 @@ var ts; }); return aggregatedTypes; } - function bodyContainsAReturnStatement(funcBody) { - return ts.forEachReturnStatement(funcBody, function (returnStatement) { - return true; - }); - } - function bodyContainsSingleThrowStatement(body) { - return (body.statements.length === 1) && (body.statements[0].kind === 208); - } - function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func, returnType) { + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { if (!produceDiagnostics) { return; } if (returnType === voidType || isTypeAny(returnType)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 192) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 || !(func.flags & 524288)) { return; } - var bodyBlock = func.body; - if (bodyContainsAReturnStatement(bodyBlock)) { - return; + if (func.flags & 1048576) { + if (compilerOptions.noImplicitReturns) { + error(func.type, ts.Diagnostics.Not_all_code_paths_return_a_value); + } } - if (bodyContainsSingleThrowStatement(bodyBlock)) { - return; + else { + error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } - error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement); } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); @@ -17911,7 +18273,7 @@ var ts; promisedType = checkAsyncFunctionReturnType(node); } if (returnType && !node.asteriskToken) { - checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); } if (node.body) { if (!node.type) { @@ -17970,7 +18332,7 @@ var ts; case 69: case 166: { var symbol = findSymbol(n); - return symbol && (symbol.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 32768) !== 0; + return symbol && (symbol.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 16384) !== 0; } case 167: { var index = n.argumentExpression; @@ -17978,7 +18340,7 @@ var ts; if (symbol && index && index.kind === 9) { var name_12 = index.text; var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_12); - return prop && (prop.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 32768) !== 0; + return prop && (prop.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 16384) !== 0; } return false; } @@ -18058,8 +18420,8 @@ var ts; } if (type.flags & 49152) { var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; if (current.flags & kind) { return true; } @@ -18074,8 +18436,8 @@ var ts; } if (type.flags & 49152) { var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var current = types_10[_i]; if (!(current.flags & kind)) { return false; } @@ -18110,8 +18472,8 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { var properties = node.properties; - for (var _i = 0; _i < properties.length; _i++) { - var p = properties[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var p = properties_3[_i]; if (p.kind === 245 || p.kind === 246) { var name_13 = p.name; var type = isTypeAny(sourceType) @@ -18573,7 +18935,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 112) { + if (node.flags & 56) { func = ts.getContainingFunction(node); if (!(func.kind === 144 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -18754,7 +19116,7 @@ var ts; function checkMethodDeclaration(node) { checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); checkFunctionLikeDeclaration(node); - if (node.flags & 256 && node.body) { + if (node.flags & 128 && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -18801,7 +19163,7 @@ var ts; } function isInstancePropertyWithInitializer(n) { return n.kind === 141 && - !(n.flags & 128) && + !(n.flags & 64) && !!n.initializer; } var containingClassDecl = node.parent; @@ -18814,12 +19176,12 @@ var ts; error(node, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return p.flags & (16 | 32 | 64); }); + ts.forEach(node.parameters, function (p) { return p.flags & (8 | 16 | 32); }); if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement; - for (var _i = 0; _i < statements.length; _i++) { - var statement = statements[_i]; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; if (statement.kind === 195 && isSuperCallExpression(statement.expression)) { superCallStatement = statement; break; @@ -18845,15 +19207,22 @@ var ts; if (produceDiagnostics) { checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); if (node.kind === 145) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { - error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 524288)) { + if (node.flags & 1048576) { + if (compilerOptions.noImplicitReturns) { + error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + else { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } } } if (!ts.hasDynamicName(node)) { var otherKind = node.kind === 145 ? 146 : 145; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 112) !== (otherAccessor.flags & 112))) { + if (((node.flags & 56) !== (otherAccessor.flags & 56))) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } var currentAccessorType = getAnnotatedAccessorType(node); @@ -18920,7 +19289,7 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 32) && ts.isInAmbientContext(node); + return (node.flags & 16) && ts.isInAmbientContext(node); } function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { if (!produceDiagnostics) { @@ -18945,8 +19314,8 @@ var ts; else { signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); } - for (var _i = 0; _i < signaturesToCheck.length; _i++) { - var otherSignature = signaturesToCheck[_i]; + for (var _i = 0, signaturesToCheck_1 = signaturesToCheck; _i < signaturesToCheck_1.length; _i++) { + var otherSignature = signaturesToCheck_1[_i]; if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { return; } @@ -18959,10 +19328,10 @@ var ts; n.parent.kind !== 214 && n.parent.kind !== 186 && ts.isInAmbientContext(n)) { - if (!(flags & 2)) { - flags |= 1; + if (!(flags & 4)) { + flags |= 2; } - flags |= 2; + flags |= 4; } return flags & flagsToCheck; } @@ -18980,16 +19349,16 @@ var ts; var canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; - if (deviation & 1) { + if (deviation & 2) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); } - else if (deviation & 2) { + else if (deviation & 4) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } - else if (deviation & (32 | 64)) { + else if (deviation & (16 | 32)) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } - else if (deviation & 256) { + else if (deviation & 128) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_not_abstract); } }); @@ -19006,7 +19375,7 @@ var ts; }); } } - var flagsToCheck = 1 | 2 | 32 | 64 | 256; + var flagsToCheck = 2 | 4 | 16 | 32 | 128; var someNodeFlags = 0; var allNodeFlags = flagsToCheck; var someHaveQuestionToken = false; @@ -19035,8 +19404,8 @@ var ts; var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { ts.Debug.assert(node.kind === 143 || node.kind === 142); - ts.Debug.assert((node.flags & 128) !== (subsequentNode.flags & 128)); - var diagnostic = node.flags & 128 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + ts.Debug.assert((node.flags & 64) !== (subsequentNode.flags & 64)); + var diagnostic = node.flags & 64 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); return; } @@ -19051,7 +19420,7 @@ var ts; error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); } else { - if (node.flags & 256) { + if (node.flags & 128) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -19062,8 +19431,8 @@ var ts; var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; - for (var _i = 0; _i < declarations.length; _i++) { - var current = declarations[_i]; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); var inAmbientContextOrInterface = node.parent.kind === 215 || node.parent.kind === 155 || inAmbientContext; @@ -19112,7 +19481,7 @@ var ts; }); } if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(lastSeenNonAmbientDeclaration.flags & 256)) { + !(lastSeenNonAmbientDeclaration.flags & 128)) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -19122,8 +19491,8 @@ var ts; var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); if (!bodySignature.hasStringLiterals) { - for (var _a = 0; _a < signatures.length; _a++) { - var signature = signatures[_a]; + for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { + var signature = signatures_3[_a]; if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -19153,9 +19522,9 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var d = _a[_i]; var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 | 1024); - if (effectiveDeclarationFlags & 1) { - if (effectiveDeclarationFlags & 1024) { + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 2 | 512); + if (effectiveDeclarationFlags & 2) { + if (effectiveDeclarationFlags & 512) { defaultExportedDeclarationSpaces |= declarationSpaces; } else { @@ -19291,9 +19660,12 @@ var ts; if (promiseType === unknownType && compilerOptions.isolatedModules) { return unknownType; } - var promiseConstructor = getMergedSymbol(promiseType.symbol); + var promiseConstructor = getNodeLinks(node.type).resolvedSymbol; if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { - error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeToString(promiseType)); + var typeName = promiseConstructor + ? symbolToString(promiseConstructor) + : typeToString(promiseType); + error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } var promiseConstructorType = getTypeOfSymbol(promiseConstructor); @@ -19452,7 +19824,7 @@ var ts; if (isAsync) { promisedType = checkAsyncFunctionReturnType(node); } - checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); } if (produceDiagnostics && !node.type) { if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { @@ -19555,7 +19927,7 @@ var ts; } } function checkVarDeclaredNamesNotShadowed(node) { - if ((ts.getCombinedNodeFlags(node) & 49152) !== 0 || ts.isParameterDeclaration(node)) { + if ((ts.getCombinedNodeFlags(node) & 24576) !== 0 || ts.isParameterDeclaration(node)) { return; } if (node.kind === 211 && !node.initializer) { @@ -19567,7 +19939,7 @@ var ts; if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 49152) { + if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 24576) { var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 212); var container = varDeclList.parent.kind === 193 && varDeclList.parent.parent ? varDeclList.parent.parent @@ -19694,6 +20066,9 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 194) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } checkSourceElement(node.elseStatement); } function checkDoStatement(node) { @@ -19943,7 +20318,7 @@ var ts; error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } else if (func.kind === 144) { - if (!isTypeAssignableTo(exprType, returnType)) { + if (!checkTypeAssignableTo(exprType, returnType, node.expression)) { error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } @@ -20073,7 +20448,7 @@ var ts; var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!(member.flags & 128) && ts.hasDynamicName(member)) { + if (!(member.flags & 64) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); @@ -20149,7 +20524,7 @@ var ts; return getTypeOfSymbol(getSymbolOfNode(node)); } function checkClassDeclaration(node) { - if (!node.name && !(node.flags & 1024)) { + if (!node.name && !(node.flags & 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -20199,8 +20574,8 @@ var ts; } var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); if (implementedTypeNodes) { - for (var _b = 0; _b < implementedTypeNodes.length; _b++) { - var typeRefNode = implementedTypeNodes[_b]; + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } @@ -20232,8 +20607,8 @@ var ts; } function checkKindsOfPropertyMemberOverrides(type, baseType) { var baseProperties = getPropertiesOfObjectType(baseType); - for (var _i = 0; _i < baseProperties.length; _i++) { - var baseProperty = baseProperties[_i]; + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; var base = getTargetSymbol(baseProperty); if (base.flags & 134217728) { continue; @@ -20244,7 +20619,7 @@ var ts; if (derived) { if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 256 && (!derivedClassDecl || !(derivedClassDecl.flags & 256))) { + if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(derivedClassDecl.flags & 128))) { if (derivedClassDecl.kind === 186) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -20255,10 +20630,10 @@ var ts; } else { var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); - if ((baseDeclarationFlags & 32) || (derivedDeclarationFlags & 32)) { + if ((baseDeclarationFlags & 16) || (derivedDeclarationFlags & 16)) { continue; } - if ((baseDeclarationFlags & 128) !== (derivedDeclarationFlags & 128)) { + if ((baseDeclarationFlags & 64) !== (derivedDeclarationFlags & 64)) { continue; } if ((base.flags & derived.flags & 8192) || ((base.flags & 98308) && (derived.flags & 98308))) { @@ -20324,11 +20699,11 @@ var ts; var seen = {}; ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; - for (var _i = 0; _i < baseTypes.length; _i++) { - var base = baseTypes[_i]; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0; _a < properties.length; _a++) { - var prop = properties[_a]; + for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { + var prop = properties_4[_a]; if (!ts.hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } @@ -20597,8 +20972,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; if ((declaration.kind === 214 || (declaration.kind === 213 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { @@ -20726,7 +21101,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -20753,7 +21128,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 1) { + if (node.flags & 2) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -20781,7 +21156,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -20820,7 +21195,7 @@ var ts; error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69) { @@ -21205,7 +21580,7 @@ var ts; } case 214: case 215: - if (!(memberFlags & 128)) { + if (!(memberFlags & 64)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056); } break; @@ -21467,7 +21842,7 @@ var ts; } function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 128 + return node.flags & 64 ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -21753,7 +22128,7 @@ var ts; } function initializeTypeChecker() { ts.forEach(host.getSourceFiles(), function (file) { - ts.bindSourceFile(file); + ts.bindSourceFile(file, compilerOptions); }); ts.forEach(host.getSourceFiles(), function (file) { if (!ts.isExternalModule(file)) { @@ -21897,19 +22272,19 @@ var ts; text = "private"; lastPrivate = modifier; } - if (flags & 112) { + if (flags & 56) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (flags & 128) { + else if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } - else if (flags & 512) { + else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } else if (node.parent.kind === 219 || node.parent.kind === 248) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); } - else if (flags & 256) { + else if (flags & 128) { if (modifier.kind === 110) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } @@ -21920,10 +22295,10 @@ var ts; flags |= ts.modifierToFlag(modifier.kind); break; case 113: - if (flags & 128) { + if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } - else if (flags & 512) { + else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } else if (node.parent.kind === 219 || node.parent.kind === 248) { @@ -21932,23 +22307,23 @@ var ts; else if (node.kind === 138) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } - else if (flags & 256) { + else if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - flags |= 128; + flags |= 64; lastStatic = modifier; break; case 82: - if (flags & 1) { + if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } - else if (flags & 2) { + else if (flags & 4) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } - else if (flags & 256) { + else if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); } - else if (flags & 512) { + else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } else if (node.parent.kind === 214) { @@ -21957,13 +22332,13 @@ var ts; else if (node.kind === 138) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } - flags |= 1; + flags |= 2; break; case 122: - if (flags & 2) { + if (flags & 4) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } - else if (flags & 512) { + else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } else if (node.parent.kind === 214) { @@ -21975,69 +22350,69 @@ var ts; else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 219) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - flags |= 2; + flags |= 4; lastDeclare = modifier; break; case 115: - if (flags & 256) { + if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } if (node.kind !== 214) { if (node.kind !== 143) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); } - if (!(node.parent.kind === 214 && node.parent.flags & 256)) { + if (!(node.parent.kind === 214 && node.parent.flags & 128)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } - if (flags & 128) { + if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - if (flags & 32) { + if (flags & 16) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); } } - flags |= 256; + flags |= 128; break; case 118: - if (flags & 512) { + if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 2 || ts.isInAmbientContext(node.parent)) { + else if (flags & 4 || ts.isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } else if (node.kind === 138) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } - flags |= 512; + flags |= 256; lastAsync = modifier; break; } } if (node.kind === 144) { - if (flags & 128) { + if (flags & 64) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } - if (flags & 256) { + if (flags & 128) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } - else if (flags & 64) { + else if (flags & 32) { return grammarErrorOnNode(lastProtected, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "protected"); } - else if (flags & 32) { + else if (flags & 16) { return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); } - else if (flags & 512) { + else if (flags & 256) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } return; } - else if ((node.kind === 222 || node.kind === 221) && flags & 2) { + else if ((node.kind === 222 || node.kind === 221) && flags & 4) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 138 && (flags & 112) && ts.isBindingPattern(node.name)) { + else if (node.kind === 138 && (flags & 56) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); } - if (flags & 512) { + if (flags & 256) { return checkGrammarAsyncModifier(node, lastAsync); } } @@ -22137,7 +22512,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 2035) { + if (parameter.flags & 1022) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -22157,7 +22532,7 @@ var ts; } } function checkGrammarForIndexSignatureModifier(node) { - if (node.flags & 2035) { + if (node.flags & 1022) { grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_not_permitted_on_index_signature_members); } } @@ -22179,8 +22554,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0; _i < args.length; _i++) { - var arg = args[_i]; + for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { + var arg = args_1[_i]; if (arg.kind === 187) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -22420,7 +22795,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); } - else if (parameter.flags & 2035) { + else if (parameter.flags & 1022) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } else if (parameter.questionToken) { @@ -22554,8 +22929,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0; _i < elements.length; _i++) { - var element = elements[_i]; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; if (element.kind !== 187) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -22674,8 +23049,8 @@ var ts; node.kind === 221 || node.kind === 228 || node.kind === 227 || - (node.flags & 2) || - (node.flags & (1 | 1024))) { + (node.flags & 4) || + (node.flags & (2 | 512))) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -22713,7 +23088,7 @@ var ts; } } function checkGrammarNumericLiteral(node) { - if (node.flags & 65536 && languageVersion >= 1) { + if (node.flags & 32768 && languageVersion >= 1) { return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } @@ -22760,7 +23135,7 @@ var ts; var addedGlobalFileReference = false; ts.forEach(root.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); - if (referencedFile && ((referencedFile.flags & 8192) || + if (referencedFile && ((referencedFile.flags & 4096) || ts.shouldEmitToOwnFile(referencedFile, compilerOptions) || !addedGlobalFileReference)) { writeReferencePath(referencedFile); @@ -22938,15 +23313,15 @@ var ts; } } function emitLines(nodes) { - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; emit(node); } } function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { var currentWriterPos = writer.getTextPos(); - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; if (!canEmitFn || canEmitFn(node)) { if (currentWriterPos !== writer.getTextPos()) { write(separator); @@ -23088,6 +23463,7 @@ var ts; function emitSourceFile(node) { currentSourceFile = node; enclosingDeclaration = node; + ts.emitDetachedComments(currentSourceFile, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } function getExportDefaultTempVariableName() { @@ -23194,10 +23570,10 @@ var ts; } function emitModuleElementDeclarationFlags(node) { if (node.parent === currentSourceFile) { - if (node.flags & 1) { + if (node.flags & 2) { write("export "); } - if (node.flags & 1024) { + if (node.flags & 512) { write("default "); } else if (node.kind !== 215) { @@ -23206,22 +23582,22 @@ var ts; } } function emitClassMemberDeclarationFlags(node) { - if (node.flags & 32) { + if (node.flags & 16) { write("private "); } - else if (node.flags & 64) { + else if (node.flags & 32) { write("protected "); } - if (node.flags & 128) { + if (node.flags & 64) { write("static "); } - if (node.flags & 256) { + if (node.flags & 128) { write("abstract "); } } function writeImportEqualsDeclaration(node) { emitJsDocComments(node); - if (node.flags & 1) { + if (node.flags & 2) { write("export "); } write("import "); @@ -23256,11 +23632,11 @@ var ts; } } function writeImportDeclaration(node) { - if (!node.importClause && !(node.flags & 1)) { + if (!node.importClause && !(node.flags & 2)) { return; } emitJsDocComments(node); - if (node.flags & 1) { + if (node.flags & 2) { write("export "); } write("import "); @@ -23322,7 +23698,7 @@ var ts; function writeModuleDeclaration(node) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 131072) { + if (node.flags & 65536) { write("namespace "); } else { @@ -23394,7 +23770,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 143 && (node.parent.flags & 32); + return node.parent.kind === 143 && (node.parent.flags & 16); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -23436,7 +23812,7 @@ var ts; break; case 143: case 142: - if (node.parent.flags & 128) { + if (node.parent.flags & 64) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } else if (node.parent.parent.kind === 214) { @@ -23499,7 +23875,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 112) { + if (param.flags & 56) { emitPropertyDeclaration(param); } }); @@ -23507,7 +23883,7 @@ var ts; } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 256) { + if (node.flags & 128) { write("abstract "); } write("class "); @@ -23571,7 +23947,7 @@ var ts; if ((node.kind === 141 || node.kind === 140) && node.parent.kind === 155) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 32)) { + else if (!(node.flags & 16)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } @@ -23585,7 +23961,7 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } else if (node.kind === 141 || node.kind === 140) { - if (node.flags & 128) { + if (node.flags & 64) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -23680,7 +24056,7 @@ var ts; emitJsDocComments(accessors.setAccessor); emitClassMemberDeclarationFlags(node); writeTextOfNode(currentSourceFile, node.name); - if (!(node.flags & 32)) { + if (!(node.flags & 16)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { @@ -23707,7 +24083,7 @@ var ts; function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; if (accessorWithTypeAnnotation.kind === 146) { - if (accessorWithTypeAnnotation.parent.flags & 128) { + if (accessorWithTypeAnnotation.parent.flags & 64) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; @@ -23724,7 +24100,7 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 128) { + if (accessorWithTypeAnnotation.flags & 64) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -23805,7 +24181,7 @@ var ts; emitType(node.type); } } - else if (node.kind !== 144 && !(node.flags & 32)) { + else if (node.kind !== 144 && !(node.flags & 16)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -23833,7 +24209,7 @@ var ts; break; case 143: case 142: - if (node.flags & 128) { + if (node.flags & 64) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -23890,7 +24266,7 @@ var ts; node.parent.parent.kind === 155) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 32)) { + else if (!(node.parent.flags & 16)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { @@ -23919,7 +24295,7 @@ var ts; ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; case 143: case 142: - if (node.parent.flags & 128) { + if (node.parent.flags & 64) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -24035,7 +24411,7 @@ var ts; } } function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 8192 + var declFileName = referencedFile.flags & 4096 ? referencedFile.fileName : ts.shouldEmitToOwnFile(referencedFile, compilerOptions) ? ts.getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") @@ -24368,16 +24744,8 @@ var ts; diagnostics: diagnostics, sourceMaps: sourceMapDataList }; - function isNodeDescendentOf(node, ancestor) { - while (node) { - if (node === ancestor) - return true; - node = node.parent; - } - return false; - } function isUniqueLocalName(name, container) { - for (var node = container; isNodeDescendentOf(node, container); node = node.nextContainer) { + for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { if (node.locals && ts.hasProperty(node.locals, name)) { if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { return false; @@ -25670,7 +26038,7 @@ var ts; write("]"); } else { - emitListWithSpread(elements, true, (node.flags & 2048) !== 0, elements.hasTrailingComma, true); + emitListWithSpread(elements, true, (node.flags & 1024) !== 0, elements.hasTrailingComma, true); } } function emitObjectLiteralBody(node, numElements) { @@ -25685,7 +26053,7 @@ var ts; emitLinePreservingList(node, properties, languageVersion >= 1, true); } else { - var multiLine = (node.flags & 2048) !== 0; + var multiLine = (node.flags & 1024) !== 0; if (!multiLine) { write(" "); } @@ -25704,7 +26072,7 @@ var ts; write("}"); } function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = (node.flags & 2048) !== 0; + var multiLine = (node.flags & 1024) !== 0; var properties = node.properties; write("("); if (multiLine) { @@ -26222,7 +26590,7 @@ var ts; var current = node; while (current) { if (current.kind === 248) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 1) !== 0); + return !isExported || ((ts.getCombinedNodeFlags(node) & 2) !== 0); } else if (ts.isFunctionLike(current) || current.kind === 219) { return false; @@ -26440,7 +26808,7 @@ var ts; if (shouldHoistVariable(decl, true)) { return false; } - if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 49152) === 0) { + if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 24576) === 0) { for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { var varDecl = _b[_a]; hoistVariableDeclarationFromLoop(convertedLoopState, varDecl); @@ -26522,7 +26890,7 @@ var ts; break; } var loopParameters; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 49152)) { + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 24576)) { loopParameters = []; for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { var varDeclaration = _b[_a]; @@ -26779,22 +27147,22 @@ var ts; var endPos = emitToken(86, node.pos); write(" "); endPos = emitToken(17, endPos); - var rhsIsIdentifier = node.expression.kind === 69; var counter = createTempVariable(268435456); - var rhsReference = rhsIsIdentifier ? node.expression : createTempVariable(0); + var rhsReference = ts.createSynthesizedNode(69); + rhsReference.text = node.expression.kind === 69 ? + makeUniqueName(node.expression.text) : + makeTempVariableName(0); emitStart(node.expression); write("var "); emitNodeWithoutSourceMap(counter); write(" = 0"); emitEnd(node.expression); - if (!rhsIsIdentifier) { - write(", "); - emitStart(node.expression); - emitNodeWithoutSourceMap(rhsReference); - write(" = "); - emitNodeWithoutSourceMap(node.expression); - emitEnd(node.expression); - } + write(", "); + emitStart(node.expression); + emitNodeWithoutSourceMap(rhsReference); + write(" = "); + emitNodeWithoutSourceMap(node.expression); + emitEnd(node.expression); write("; "); emitStart(node.initializer); emitNodeWithoutSourceMap(counter); @@ -27029,7 +27397,7 @@ var ts; } function emitModuleMemberName(node) { emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 1) { + if (ts.getCombinedNodeFlags(node) & 2) { var container = getContainingModule(node); if (container) { write(getGeneratedNameForNode(container)); @@ -27051,7 +27419,7 @@ var ts; } function emitEs6ExportDefaultCompat(node) { if (node.parent.kind === 248) { - ts.Debug.assert(!!(node.flags & 1024) || node.kind === 227); + ts.Debug.assert(!!(node.flags & 512) || node.kind === 227); if (modulekind === 1 || modulekind === 2 || modulekind === 3) { if (!currentSourceFile.symbol.exports["___esModule"]) { if (languageVersion === 1) { @@ -27067,12 +27435,12 @@ var ts; } } function emitExportMemberAssignment(node) { - if (node.flags & 1) { + if (node.flags & 2) { writeLine(); emitStart(node); if (modulekind === 4 && node.parent === currentSourceFile) { write(exportFunctionForFile + "(\""); - if (node.flags & 1024) { + if (node.flags & 512) { write("default"); } else { @@ -27083,7 +27451,7 @@ var ts; write(")"); } else { - if (node.flags & 1024) { + if (node.flags & 512) { emitEs6ExportDefaultCompat(node); if (languageVersion === 0) { write("exports[\"default\"]"); @@ -27171,7 +27539,7 @@ var ts; var emitCount = 0; var canDefineTempVariablesInPlace = false; if (root.kind === 211) { - var isExported = ts.getCombinedNodeFlags(root) & 1; + var isExported = ts.getCombinedNodeFlags(root) & 2; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } @@ -27237,8 +27605,8 @@ var ts; if (properties.length !== 1) { value = ensureIdentifier(value, true); } - for (var _a = 0; _a < properties.length; _a++) { - var p = properties[_a]; + for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { + var p = properties_5[_a]; if (p.kind === 245 || p.kind === 246) { var propName = p.name; var target_1 = p.kind === 246 ? p : p.initializer || propName; @@ -27357,7 +27725,7 @@ var ts; var initializer = node.initializer; if (!initializer && languageVersion < 2) { var isLetDefinedInLoop = (resolver.getNodeCheckFlags(node) & 16384) && - (getCombinedFlagsForIdentifier(node.name) & 16384); + (getCombinedFlagsForIdentifier(node.name) & 8192); if (isLetDefinedInLoop && node.parent.parent.kind !== 200 && node.parent.parent.kind !== 201) { @@ -27396,13 +27764,13 @@ var ts; return ts.getCombinedNodeFlags(node.parent); } function isES6ExportedDeclaration(node) { - return !!(node.flags & 1) && + return !!(node.flags & 2) && modulekind === 5 && node.parent.kind === 248; } function emitVariableStatement(node) { var startIsEmitted = false; - if (node.flags & 1) { + if (node.flags & 2) { if (isES6ExportedDeclaration(node)) { write("export "); startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); @@ -27426,7 +27794,7 @@ var ts; } } function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { - if (!(node.flags & 1)) { + if (!(node.flags & 2)) { return true; } if (isES6ExportedDeclaration(node)) { @@ -27583,7 +27951,7 @@ var ts; if (!shouldEmitAsArrowFunction(node)) { if (isES6ExportedDeclaration(node)) { write("export "); - if (node.flags & 1024) { + if (node.flags & 512) { write("default "); } } @@ -27722,7 +28090,7 @@ var ts; emitRestParameter(node); } function emitExpressionFunctionBody(node, body) { - if (languageVersion < 2 || node.flags & 512) { + if (languageVersion < 2 || node.flags & 256) { emitDownLevelExpressionFunctionBody(node, body); return; } @@ -27738,7 +28106,7 @@ var ts; scopeEmitStart(node); increaseIndent(); var outPos = writer.getTextPos(); - emitDetachedComments(node.body); + emitDetachedCommentsAndUpdateCommentsInfo(node.body); emitFunctionBodyPreamble(node); var preambleEmitted = writer.getTextPos() !== outPos; decreaseIndent(); @@ -27774,7 +28142,7 @@ var ts; scopeEmitStart(node); var initialTextPos = writer.getTextPos(); increaseIndent(); - emitDetachedComments(body.statements); + emitDetachedCommentsAndUpdateCommentsInfo(body.statements); var startIndex = emitDirectivePrologues(body.statements, true); emitFunctionBodyPreamble(node); decreaseIndent(); @@ -27816,7 +28184,7 @@ var ts; } function emitParameterPropertyAssignments(node) { ts.forEach(node.parameters, function (param) { - if (param.flags & 112) { + if (param.flags & 56) { writeLine(); emitStart(param); emitStart(param.name); @@ -27848,15 +28216,15 @@ var ts; var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 141 && isStatic === ((member.flags & 128) !== 0) && member.initializer) { + if (member.kind === 141 && isStatic === ((member.flags & 64) !== 0) && member.initializer) { properties.push(member); } } return properties; } function emitPropertyDeclarations(node, properties) { - for (var _a = 0; _a < properties.length; _a++) { - var property = properties[_a]; + for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { + var property = properties_6[_a]; emitPropertyDeclaration(node, property); } } @@ -27869,7 +28237,7 @@ var ts; emit(receiver); } else { - if (property.flags & 128) { + if (property.flags & 64) { emitDeclarationName(node); } else { @@ -27968,7 +28336,7 @@ var ts; writeLine(); emitLeadingComments(member); emitStart(member); - if (member.flags & 128) { + if (member.flags & 64) { write("static "); } if (member.kind === 145) { @@ -28013,7 +28381,7 @@ var ts; if (member.kind === 144 && !member.body) { emitCommentsOnNotEmittedNode(member); } - if (member.kind === 141 && member.initializer && (member.flags & 128) === 0) { + if (member.kind === 141 && member.initializer && (member.flags & 64) === 0) { hasInstancePropertyWithInitializer = true; } }); @@ -28050,7 +28418,7 @@ var ts; increaseIndent(); if (ctor) { startIndex = emitDirectivePrologues(ctor.body.statements, true); - emitDetachedComments(ctor.body.statements); + emitDetachedCommentsAndUpdateCommentsInfo(ctor.body.statements); } emitCaptureThisForNodeIfNecessary(node); var superCall; @@ -28121,7 +28489,7 @@ var ts; var thisNodeIsDecorated = ts.nodeIsDecorated(node); if (node.kind === 214) { if (thisNodeIsDecorated) { - if (isES6ExportedDeclaration(node) && !(node.flags & 1024)) { + if (isES6ExportedDeclaration(node) && !(node.flags & 512)) { write("export "); } write("let "); @@ -28130,7 +28498,7 @@ var ts; } else if (isES6ExportedDeclaration(node)) { write("export "); - if (node.flags & 1024) { + if (node.flags & 512) { write("default "); } } @@ -28146,7 +28514,7 @@ var ts; write(" = "); } write("class"); - if ((node.name || (node.flags & 1024 && staticProperties.length > 0)) && !thisNodeIsDecorated) { + if ((node.name || (node.flags & 512 && staticProperties.length > 0)) && !thisNodeIsDecorated) { write(" "); emitDeclarationName(node); } @@ -28169,8 +28537,8 @@ var ts; write(";"); } if (isClassExpressionWithStaticProperties) { - for (var _a = 0; _a < staticProperties.length; _a++) { - var property = staticProperties[_a]; + for (var _a = 0, staticProperties_1 = staticProperties; _a < staticProperties_1.length; _a++) { + var property = staticProperties_1[_a]; write(","); writeLine(); emitPropertyDeclaration(node, property, tempVariable, true); @@ -28186,7 +28554,7 @@ var ts; emitPropertyDeclarations(node, staticProperties); emitDecoratorsOfClass(node); } - if (!isES6ExportedDeclaration(node) && (node.flags & 1)) { + if (!isES6ExportedDeclaration(node) && (node.flags & 2)) { writeLine(); emitStart(node); emitModuleMemberName(node); @@ -28195,7 +28563,7 @@ var ts; emitEnd(node); write(";"); } - else if (isES6ExportedDeclaration(node) && (node.flags & 1024) && thisNodeIsDecorated) { + else if (isES6ExportedDeclaration(node) && (node.flags & 512) && thisNodeIsDecorated) { writeLine(); write("export default "); emitDeclarationName(node); @@ -28275,13 +28643,13 @@ var ts; } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); - if (!(member.flags & 128)) { + if (!(member.flags & 64)) { write(".prototype"); } } function emitDecoratorsOfClass(node) { emitDecoratorsOfMembers(node, 0); - emitDecoratorsOfMembers(node, 128); + emitDecoratorsOfMembers(node, 64); emitDecoratorsOfConstructor(node); } function emitDecoratorsOfConstructor(node) { @@ -28316,7 +28684,7 @@ var ts; function emitDecoratorsOfMembers(node, staticFlag) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if ((member.flags & 128) !== staticFlag) { + if ((member.flags & 64) !== staticFlag) { continue; } if (!ts.nodeCanBeDecorated(member)) { @@ -28643,7 +29011,7 @@ var ts; return; } if (!shouldHoistDeclarationInSystemJsModule(node)) { - if (!(node.flags & 1) || isES6ExportedDeclaration(node)) { + if (!(node.flags & 2) || isES6ExportedDeclaration(node)) { emitStart(node); if (isES6ExportedDeclaration(node)) { write("export "); @@ -28674,7 +29042,7 @@ var ts; emitModuleMemberName(node); write(" = {}));"); emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 1 && !shouldHoistDeclarationInSystemJsModule(node)) { + if (!isES6ExportedDeclaration(node) && node.flags & 2 && !shouldHoistDeclarationInSystemJsModule(node)) { writeLine(); emitStart(node); write("var "); @@ -28685,7 +29053,7 @@ var ts; write(";"); } if (modulekind !== 5 && node.parent === currentSourceFile) { - if (modulekind === 4 && (node.flags & 1)) { + if (modulekind === 4 && (node.flags & 2)) { writeLine(); write(exportFunctionForFile + "(\""); emitDeclarationName(node); @@ -28787,7 +29155,7 @@ var ts; scopeEmitEnd(); } write(")("); - if ((node.flags & 1) && !isES6ExportedDeclaration(node)) { + if ((node.flags & 2) && !isES6ExportedDeclaration(node)) { emit(node.name); write(" = "); } @@ -28797,7 +29165,7 @@ var ts; write(" = {}));"); emitEnd(node); if (!isES6ExportedDeclaration(node) && node.name.kind === 69 && node.parent === currentSourceFile) { - if (modulekind === 4 && (node.flags & 1)) { + if (modulekind === 4 && (node.flags & 2)) { writeLine(); write(exportFunctionForFile + "(\""); emitDeclarationName(node); @@ -28895,7 +29263,7 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 221 && (node.flags & 1) !== 0; + var isExportedImport = node.kind === 221 && (node.flags & 2) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); if (modulekind !== 2) { emitLeadingComments(node); @@ -28961,7 +29329,7 @@ var ts; write("export "); write("var "); } - else if (!(node.flags & 1)) { + else if (!(node.flags & 2)) { write("var "); } } @@ -29049,8 +29417,8 @@ var ts; function emitExportOrImportSpecifierList(specifiers, shouldEmit) { ts.Debug.assert(modulekind === 5); var needsComma = false; - for (var _a = 0; _a < specifiers.length; _a++) { - var specifier = specifiers[_a]; + for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { + var specifier = specifiers_1[_a]; if (shouldEmit(specifier)) { if (needsComma) { write(", "); @@ -29184,8 +29552,8 @@ var ts; } writeLine(); var started = false; - for (var _a = 0; _a < externalImports.length; _a++) { - var importNode = externalImports[_a]; + for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { + var importNode = externalImports_1[_a]; var skipNode = importNode.kind === 228 || (importNode.kind === 222 && !importNode.importClause); if (skipNode) { @@ -29210,8 +29578,8 @@ var ts; } if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { var hasExportDeclarationWithExportClause = false; - for (var _a = 0; _a < externalImports.length; _a++) { - var externalImport = externalImports[_a]; + for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { + var externalImport = externalImports_2[_a]; if (externalImport.kind === 228 && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; @@ -29239,8 +29607,8 @@ var ts; } } } - for (var _d = 0; _d < externalImports.length; _d++) { - var externalImport = externalImports[_d]; + for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { + var externalImport = externalImports_3[_d]; if (externalImport.kind !== 228) { continue; } @@ -29284,7 +29652,7 @@ var ts; return exportStarFunction; } function writeExportedName(node) { - if (node.kind !== 69 && node.flags & 1024) { + if (node.kind !== 69 && node.flags & 512) { return; } if (started) { @@ -29337,7 +29705,7 @@ var ts; emit(local); } var flags = ts.getCombinedNodeFlags(local.kind === 69 ? local.parent : local); - if (flags & 1) { + if (flags & 2) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -29347,11 +29715,11 @@ var ts; write(";"); } if (hoistedFunctionDeclarations) { - for (var _a = 0; _a < hoistedFunctionDeclarations.length; _a++) { - var f = hoistedFunctionDeclarations[_a]; + for (var _a = 0, hoistedFunctionDeclarations_1 = hoistedFunctionDeclarations; _a < hoistedFunctionDeclarations_1.length; _a++) { + var f = hoistedFunctionDeclarations_1[_a]; writeLine(); emit(f); - if (f.flags & 1) { + if (f.flags & 2) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -29361,7 +29729,7 @@ var ts; } return exportedDeclarations; function visit(node) { - if (node.flags & 2) { + if (node.flags & 4) { return; } if (node.kind === 213) { @@ -29431,7 +29799,7 @@ var ts; if (checkIfSourceFileLevelDecl && !shouldHoistDeclarationInSystemJsModule(node)) { return false; } - return (ts.getCombinedNodeFlags(node) & 49152) === 0 || + return (ts.getCombinedNodeFlags(node) & 24576) === 0 || ts.getEnclosingBlockScopeContainer(node).kind === 248; } function isCurrentFileSystemExternalModule() { @@ -29466,8 +29834,8 @@ var ts; var parameterName = makeUniqueName(ts.forEach(group, getLocalNameForExternalImport) || ""); write("function (" + parameterName + ") {"); increaseIndent(); - for (var _a = 0; _a < group.length; _a++) { - var entry = group[_a]; + for (var _a = 0, group_1 = group; _a < group_1.length; _a++) { + var entry = group_1[_a]; var importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { case 222: @@ -29601,8 +29969,8 @@ var ts; unaliasedModuleNames.push("\"" + amdDependency.path + "\""); } } - for (var _c = 0; _c < externalImports.length; _c++) { - var importNode = externalImports[_c]; + for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { + var importNode = externalImports_4[_c]; var externalModuleName = getExternalModuleNameText(importNode); var importAliasName = getLocalNameForExternalImport(importNode); if (includeNonAmdDependencies && importAliasName) { @@ -29855,7 +30223,7 @@ var ts; function emitSourceFileNode(node) { writeLine(); emitShebang(); - emitDetachedComments(node); + emitDetachedCommentsAndUpdateCommentsInfo(node); if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1]; emitModule(node); @@ -29878,7 +30246,7 @@ var ts; } function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { if (node) { - if (node.flags & 2) { + if (node.flags & 4) { return emitCommentsOnNotEmittedNode(node); } if (isSpecializedCommentHandling(node)) { @@ -30111,10 +30479,6 @@ var ts; } return leadingComments; } - function isPinnedComments(comment) { - return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 && - currentSourceFile.text.charCodeAt(comment.pos + 2) === 33; - } function isTripleSlashComment(comment) { if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 && comment.pos + 2 < comment.end && @@ -30195,44 +30559,14 @@ var ts; ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments); ts.emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); } - function emitDetachedComments(node) { - var leadingComments; - if (compilerOptions.removeComments) { - if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComments); + function emitDetachedCommentsAndUpdateCommentsInfo(node) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); } - } - else { - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); - } - if (leadingComments) { - var detachedComments = []; - var lastComment; - ts.forEach(leadingComments, function (comment) { - if (lastComment) { - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, lastComment.end); - var commentLine = ts.getLineOfLocalPosition(currentSourceFile, comment.pos); - if (commentLine >= lastCommentLine + 2) { - return detachedComments; - } - } - detachedComments.push(comment); - lastComment = comment; - }); - if (detachedComments.length) { - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); - var nodeLine = ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); - if (nodeLine >= lastCommentLine + 2) { - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - ts.emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); - var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; } } } @@ -30535,7 +30869,7 @@ var ts; var resolveModuleNamesWorker = host.resolveModuleNames ? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }) : (function (moduleNames, containingFile) { return ts.map(moduleNames, function (moduleName) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }); }); - var filesByName = ts.createFileMap(getCanonicalFileName); + var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (oldProgram) { var oldOptions = oldProgram.getCompilerOptions(); @@ -30583,8 +30917,8 @@ var ts; if (!classifiableNames) { getTypeChecker(); classifiableNames = {}; - for (var _i = 0; _i < files.length; _i++) { - var sourceFile = files[_i]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var sourceFile = files_3[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -30600,7 +30934,7 @@ var ts; return false; } var newSourceFiles = []; - var normalizedAbsoluteFileNames = []; + var filePaths = []; var modifiedSourceFiles = []; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; @@ -30608,8 +30942,8 @@ var ts; if (!newSourceFile) { return false; } - var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); - normalizedAbsoluteFileNames.push(normalizedAbsolutePath); + newSourceFile.path = oldSourceFile.path; + filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { return false; @@ -30623,7 +30957,7 @@ var ts; } if (resolveModuleNamesWorker) { var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); - var resolutions = resolveModuleNamesWorker(moduleNames, normalizedAbsolutePath); + var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); for (var i = 0; i < moduleNames.length; ++i) { var newResolution = resolutions[i]; var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]); @@ -30646,12 +30980,12 @@ var ts; newSourceFiles.push(newSourceFile); } for (var i = 0, len = newSourceFiles.length; i < len; ++i) { - filesByName.set(normalizedAbsoluteFileNames[i], newSourceFiles[i]); + filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _b = 0; _b < modifiedSourceFiles.length; _b++) { - var modifiedFile = modifiedSourceFiles[_b]; + for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { + var modifiedFile = modifiedSourceFiles_1[_b]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); } oldProgram.structureIsReused = true; @@ -30690,7 +31024,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - return filesByName.get(ts.getNormalizedAbsolutePath(fileName, currentDirectory)); + return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); } function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { if (sourceFile) { @@ -30799,7 +31133,7 @@ var ts; } break; case 218: - if (node.name.kind === 9 && (node.flags & 2 || ts.isDeclarationFile(file))) { + if (node.name.kind === 9 && (node.flags & 4 || ts.isDeclarationFile(file))) { ts.forEachChild(node.body, function (node) { collect(node, false); }); @@ -30816,7 +31150,7 @@ var ts; diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"]; } - else if (!findSourceFile(fileName, ts.getNormalizedAbsolutePath(fileName, currentDirectory), isDefaultLib, refFile, refPos, refEnd)) { + else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } @@ -30826,13 +31160,13 @@ var ts; } } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.getNormalizedAbsolutePath(fileName, currentDirectory), isDefaultLib, refFile, refPos, refEnd); + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.getNormalizedAbsolutePath(fileName + extension, currentDirectory), isDefaultLib, refFile, refPos, refEnd); })) { + else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -30874,6 +31208,7 @@ var ts; }); filesByName.set(normalizedAbsolutePath, file); if (file) { + file.path = normalizedAbsolutePath; if (host.useCaseSensitiveFileNames()) { var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath); if (existingFile) { @@ -30918,11 +31253,7 @@ var ts; var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); if (resolution && !options.noResolve) { - var absoluteImportPath = ts.isRootedDiskPath(resolution.resolvedFileName) - ? resolution.resolvedFileName - : ts.getNormalizedAbsolutePath(resolution.resolvedFileName, currentDirectory); - var relativePath = ts.getRelativePathToDirectoryOrUrl(currentDirectory, absoluteImportPath, currentDirectory, getCanonicalFileName, false); - var importedFile = findSourceFile(relativePath, absoluteImportPath, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { if (!ts.isExternalModule(importedFile)) { var start_2 = ts.getTokenPosOfNode(file.imports[i], file); @@ -30973,8 +31304,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0; _i < sourceFiles.length; _i++) { - var sourceFile = sourceFiles[_i]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -31231,6 +31562,12 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code }, + { + name: "pretty", + paramType: ts.Diagnostics.KIND, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental, + type: "boolean" + }, { name: "project", shortName: "p", @@ -31329,11 +31666,31 @@ var ts; description: ts.Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, error: ts.Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic }, + { + name: "allowUnusedLabels", + type: "boolean", + description: ts.Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "noImplicitReturns", + type: "boolean", + description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + { + name: "allowUnreachableCode", + type: "boolean", + description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code + }, { name: "forceConsistentCasingInFileNames", type: "boolean", description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file - }, + } ]; var optionNameMapCache; function getOptionNameMap() { @@ -31459,13 +31816,31 @@ var ts; ts.readConfigFile = readConfigFile; function parseConfigFileTextToJson(fileName, jsonText) { try { - return { config: /\S/.test(jsonText) ? JSON.parse(jsonText) : {} }; + var jsonTextWithoutComments = removeComments(jsonText); + return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + function removeComments(jsonText) { + var output = ""; + var scanner = ts.createScanner(1, false, 0, jsonText); + var token; + while ((token = scanner.scan()) !== 1) { + switch (token) { + case 2: + case 3: + output += scanner.getTokenText().replace(/\S/g, " "); + break; + default: + output += scanner.getTokenText(); + break; + } + } + return output; + } function parseJsonConfigFileContent(json, host, basePath) { var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), options = _a.options, errors = _a.errors; return { @@ -31554,6 +31929,13 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var reportDiagnostic = reportDiagnosticSimply; + function reportDiagnostics(diagnostics, host) { + for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) { + var diagnostic = diagnostics_1[_i]; + reportDiagnostic(diagnostic, host); + } + } function validateLocaleAndSetLanguage(locale, errors) { var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); if (!matchResult) { @@ -31612,20 +31994,84 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - function reportDiagnostic(diagnostic) { + function reportDiagnosticSimply(diagnostic, host) { var output = ""; if (diagnostic.file) { - var loc = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); - output += diagnostic.file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + "): "; + var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; + var relativeFileName = host + ? ts.convertToRelativePath(diagnostic.file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) + : diagnostic.file.fileName; + output += diagnostic.file.fileName + "(" + (line + 1) + "," + (character + 1) + "): "; } var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); output += category + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine) + ts.sys.newLine; ts.sys.write(output); } - function reportDiagnostics(diagnostics) { - for (var i = 0; i < diagnostics.length; i++) { - reportDiagnostic(diagnostics[i]); + var redForegroundEscapeSequence = "\u001b[91m"; + var yellowForegroundEscapeSequence = "\u001b[93m"; + var blueForegroundEscapeSequence = "\u001b[93m"; + var gutterStyleSequence = "\u001b[100;30m"; + var gutterSeparator = " "; + var resetEscapeSequence = "\u001b[0m"; + var elipsis = "..."; + var categoryFormatMap = (_a = {}, + _a[ts.DiagnosticCategory.Warning] = yellowForegroundEscapeSequence, + _a[ts.DiagnosticCategory.Error] = redForegroundEscapeSequence, + _a[ts.DiagnosticCategory.Message] = blueForegroundEscapeSequence, + _a + ); + function formatAndReset(text, formatStyle) { + return formatStyle + text + resetEscapeSequence; + } + function reportDiagnosticWithColorAndContext(diagnostic, host) { + var output = ""; + if (diagnostic.file) { + var start = diagnostic.start, length_3 = diagnostic.length, file = diagnostic.file; + var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; + var _b = ts.getLineAndCharacterOfPosition(file, start + length_3), lastLine = _b.line, lastLineChar = _b.character; + var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line; + var hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + var gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(elipsis.length, gutterWidth); + } + output += ts.sys.newLine; + for (var i = firstLine; i <= lastLine; i++) { + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(elipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + ts.sys.newLine; + i = lastLine - 1; + } + var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0); + var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + var lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); + lineContent = lineContent.replace("\t", " "); + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + ts.sys.newLine; + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + var lastCharForLine = i === lastLine ? lastLineChar : undefined; + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + output += ts.sys.newLine; + } + output += ts.sys.newLine; + output += file.fileName + "(" + (firstLine + 1) + "," + (firstLineChar + 1) + "): "; } + var categoryColor = categoryFormatMap[diagnostic.category]; + var category = ts.DiagnosticCategory[diagnostic.category].toLowerCase(); + output += formatAndReset(category, categoryColor) + " TS" + diagnostic.code + ": " + ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine); + output += ts.sys.newLine + ts.sys.newLine; + ts.sys.write(output); } function reportWatchDiagnostic(diagnostic) { var output = new Date().toLocaleTimeString() + " - "; @@ -31677,13 +32123,13 @@ var ts; var hostFileExists; if (commandLine.options.locale) { if (!isJSONSupported()) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--locale")); + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--locale"), undefined); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } validateLocaleAndSetLanguage(commandLine.options.locale, commandLine.errors); } if (commandLine.errors.length > 0) { - reportDiagnostics(commandLine.errors); + reportDiagnostics(commandLine.errors, compilerHost); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (commandLine.options.init) { @@ -31691,7 +32137,7 @@ var ts; return ts.sys.exit(ts.ExitStatus.Success); } if (commandLine.options.version) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Version_0, ts.version)); + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Version_0, ts.version), undefined); return ts.sys.exit(ts.ExitStatus.Success); } if (commandLine.options.help) { @@ -31701,12 +32147,12 @@ var ts; } if (commandLine.options.project) { if (!isJSONSupported()) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--project")); + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--project"), undefined); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } configFileName = ts.normalizePath(ts.combinePaths(commandLine.options.project, "tsconfig.json")); if (commandLine.fileNames.length !== 0) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line)); + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line), undefined); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } } @@ -31721,7 +32167,7 @@ var ts; } if (commandLine.options.watch && commandLine.options.hasOwnProperty("watch")) { if (!ts.sys.watchFile) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--watch")); + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"), undefined); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (configFileName) { @@ -31749,7 +32195,7 @@ var ts; var configObject = result.config; var configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, ts.getDirectoryPath(configFileName)); if (configParseResult.errors.length > 0) { - reportDiagnostics(configParseResult.errors); + reportDiagnostics(configParseResult.errors, undefined); ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); return; } @@ -31772,6 +32218,9 @@ var ts; hostFileExists = compilerHost.fileExists; compilerHost.fileExists = cachedFileExists; } + if (compilerOptions.pretty) { + reportDiagnostic = reportDiagnosticWithColorAndContext; + } cachedExistingFiles = {}; var compileResult = compile(rootFileNames, compilerOptions, compilerHost); if (!compilerOptions.watch) { @@ -31906,14 +32355,14 @@ var ts; diagnostics = program.getSemanticDiagnostics(); } } - reportDiagnostics(diagnostics); + reportDiagnostics(diagnostics, compilerHost); if (compilerOptions.noEmit) { return diagnostics.length ? ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : ts.ExitStatus.Success; } var emitOutput = program.emit(); - reportDiagnostics(emitOutput.diagnostics); + reportDiagnostics(emitOutput.diagnostics, compilerHost); if (emitOutput.emitSkipped) { return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } @@ -31988,7 +32437,7 @@ var ts; var currentDirectory = ts.sys.getCurrentDirectory(); var file = ts.normalizePath(ts.combinePaths(currentDirectory, "tsconfig.json")); if (ts.sys.fileExists(file)) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file)); + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file), undefined); } else { var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions); @@ -32000,7 +32449,7 @@ var ts; configurations.files = fileNames; } ts.sys.writeFile(file, JSON.stringify(configurations, undefined, 4)); - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Successfully_created_a_tsconfig_json_file)); + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Successfully_created_a_tsconfig_json_file), undefined); } return; function serializeCompilerOptions(options) { @@ -32039,5 +32488,6 @@ var ts; return result; } } + var _a; })(ts || (ts = {})); ts.executeCommandLine(ts.sys.args); diff --git a/lib/tsserver.js b/lib/tsserver.js index ed62dd90686..2893dab82ef 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -49,40 +49,49 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function createFileMap(getCanonicalFileName) { + function createFileMap(keyMapper) { var files = {}; return { get: get, set: set, contains: contains, remove: remove, - clear: clear, - forEachValue: forEachValueInMap + forEachValue: forEachValueInMap, + clear: clear }; - function set(fileName, value) { - files[normalizeKey(fileName)] = value; - } - function get(fileName) { - return files[normalizeKey(fileName)]; - } - function contains(fileName) { - return hasProperty(files, normalizeKey(fileName)); - } - function remove(fileName) { - var key = normalizeKey(fileName); - delete files[key]; - } function forEachValueInMap(f) { - forEachValue(files, f); + for (var key in files) { + f(key, files[key]); + } } - function normalizeKey(key) { - return getCanonicalFileName(normalizeSlashes(key)); + function get(path) { + return files[toKey(path)]; + } + function set(path, value) { + files[toKey(path)] = value; + } + function contains(path) { + return hasProperty(files, toKey(path)); + } + function remove(path) { + var key = toKey(path); + delete files[key]; } function clear() { files = {}; } + function toKey(path) { + return keyMapper ? keyMapper(path) : path; + } } ts.createFileMap = createFileMap; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; function forEach(array, callback) { if (array) { for (var i = 0, len = array.length; i < len; i++) { @@ -97,8 +106,8 @@ var ts; ts.forEach = forEach; function contains(array, value) { if (array) { - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var v = array_1[_i]; if (v === value) { return true; } @@ -121,8 +130,8 @@ var ts; function countWhere(array, predicate) { var count = 0; if (array) { - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (predicate(v)) { count++; } @@ -135,8 +144,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var item = array[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; if (f(item)) { result.push(item); } @@ -149,8 +158,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; result.push(f(v)); } } @@ -169,8 +178,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var item = array[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; if (!contains(result, item)) { result.push(item); } @@ -181,8 +190,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -190,8 +199,8 @@ var ts; ts.sum = sum; function addRange(to, from) { if (to && from) { - for (var _i = 0; _i < from.length; _i++) { - var v = from[_i]; + for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { + var v = from_1[_i]; to.push(v); } } @@ -512,8 +521,8 @@ var ts; function getNormalizedParts(normalizedSlashedPath, rootLength) { var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); var normalized = []; - for (var _i = 0; _i < parts.length; _i++) { - var part = parts[_i]; + for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { + var part = parts_1[_i]; if (part !== ".") { if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { normalized.pop(); @@ -661,8 +670,8 @@ var ts; if (!fileName) { return false; } - for (var _i = 0; _i < ts.supportedExtensions.length; _i++) { - var extension = ts.supportedExtensions[_i]; + for (var _i = 0, supportedExtensions_1 = ts.supportedExtensions; _i < supportedExtensions_1.length; _i++) { + var extension = supportedExtensions_1[_i]; if (fileExtensionIs(fileName, extension)) { return true; } @@ -672,8 +681,8 @@ var ts; ts.isSupportedSourceFileName = isSupportedSourceFileName; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { - for (var _i = 0; _i < extensionsToRemove.length; _i++) { - var ext = extensionsToRemove[_i]; + for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { + var ext = extensionsToRemove_1[_i]; if (fileExtensionIs(path, ext)) { return path.substr(0, path.length - ext.length); } @@ -747,8 +756,8 @@ var ts; })(Debug = ts.Debug || (ts.Debug = {})); function copyListRemovingItem(item, list) { var copiedList = []; - for (var _i = 0; _i < list.length; _i++) { - var e = list[_i]; + for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { + var e = list_1[_i]; if (e !== item) { copiedList.push(e); } @@ -834,16 +843,16 @@ var ts; function visitDirectory(path) { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0; _i < files.length; _i++) { - var current = files[_i]; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; var name_1 = ts.combinePaths(path, current); if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { result.push(name_1); } } var subfolders = getNames(folder.subfolders); - for (var _a = 0; _a < subfolders.length; _a++) { - var current = subfolders[_a]; + for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { + var current = subfolders_1[_a]; var name_2 = ts.combinePaths(path, current); if (!ts.contains(exclude, getCanonicalPath(name_2))) { visitDirectory(name_2); @@ -894,6 +903,7 @@ var ts; var _fs = require("fs"); var _path = require("path"); var _os = require("os"); + var _tty = require("tty"); function createWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } if (chunkSize === void 0) { chunkSize = 30; } @@ -1006,8 +1016,8 @@ var ts; function visitDirectory(path) { var files = _fs.readdirSync(path || ".").sort(); var directories = []; - for (var _i = 0; _i < files.length; _i++) { - var current = files[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var current = files_2[_i]; var name_3 = ts.combinePaths(path, current); if (!ts.contains(exclude, getCanonicalPath(name_3))) { var stat = _fs.statSync(name_3); @@ -1021,8 +1031,8 @@ var ts; } } } - for (var _a = 0; _a < directories.length; _a++) { - var current = directories[_a]; + for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { + var current = directories_1[_a]; visitDirectory(current); } } @@ -1032,14 +1042,7 @@ var ts; newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, write: function (s) { - var buffer = new Buffer(s, "utf8"); - var offset = 0; - var toWrite = buffer.length; - var written = 0; - while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) { - offset += written; - toWrite -= written; - } + process.stdout.write(s); }, readFile: readFile, writeFile: writeFile, @@ -1306,6 +1309,7 @@ var ts; await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher_1311", message: "Async functions are only available when targeting ECMAScript 6 and higher." }, can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, + The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -1358,7 +1362,7 @@ var ts; Neither_type_0_nor_type_1_is_assignable_to_the_other: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Neither_type_0_nor_type_1_is_assignable_to_the_other_2352", message: "Neither type '{0}' nor type '{1}' is assignable to the other." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, No_best_common_type_exists_among_return_expressions: { code: 2354, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_return_expressions_2354", message: "No best common type exists among return expressions." }, - A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_th_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement." }, + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, @@ -1379,7 +1383,7 @@ var ts; Duplicate_number_index_signature: { code: 2375, category: ts.DiagnosticCategory.Error, key: "Duplicate_number_index_signature_2375", message: "Duplicate number index signature." }, A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: 2376, category: ts.DiagnosticCategory.Error, key: "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", message: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." }, Constructors_for_derived_classes_must_contain_a_super_call: { code: 2377, category: ts.DiagnosticCategory.Error, key: "Constructors_for_derived_classes_must_contain_a_super_call_2377", message: "Constructors for derived classes must contain a 'super' call." }, - A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement_2378", message: "A 'get' accessor must return a value or consist of a single 'throw' statement." }, + A_get_accessor_must_return_a_value: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_2378", message: "A 'get' accessor must return a value." }, Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2379, category: ts.DiagnosticCategory.Error, key: "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", message: "Getter and setter accessors do not agree in visibility." }, get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, @@ -1669,8 +1673,6 @@ var ts; NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "NEWLINE" }, Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: ts.DiagnosticCategory.Error, key: "Argument_for_newLine_option_must_be_CRLF_or_LF_6062", message: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, Argument_for_moduleResolution_option_must_be_node_or_classic: { code: 6063, category: ts.DiagnosticCategory.Error, key: "Argument_for_moduleResolution_option_must_be_node_or_classic_6063", message: "Argument for '--moduleResolution' option must be 'node' or 'classic'." }, - Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, - Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, @@ -1678,7 +1680,14 @@ var ts; Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: ts.DiagnosticCategory.Message, key: "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", message: "Initializes a TypeScript project and creates a tsconfig.json file." }, Successfully_created_a_tsconfig_json_file: { code: 6071, category: ts.DiagnosticCategory.Message, key: "Successfully_created_a_tsconfig_json_file_6071", message: "Successfully created a tsconfig.json file." }, Suppress_excess_property_checks_for_object_literals: { code: 6072, category: ts.DiagnosticCategory.Message, key: "Suppress_excess_property_checks_for_object_literals_6072", message: "Suppress excess property checks for object literals." }, - Disallow_inconsistently_cased_references_to_the_same_file: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6073", message: "Disallow inconsistently-cased references to the same file." }, + Stylize_errors_and_messages_using_color_and_context_experimental: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Stylize_errors_and_messages_using_color_and_context_experimental_6073", message: "Stylize errors and messages using color and context. (experimental)" }, + Do_not_report_errors_on_unused_labels: { code: 6074, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unused_labels_6074", message: "Do not report errors on unused labels." }, + Report_error_when_not_all_code_paths_in_function_return_a_value: { code: 6075, category: ts.DiagnosticCategory.Message, key: "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", message: "Report error when not all code paths in function return a value." }, + Report_errors_for_fallthrough_cases_in_switch_statement: { code: 6076, category: ts.DiagnosticCategory.Message, key: "Report_errors_for_fallthrough_cases_in_switch_statement_6076", message: "Report errors for fallthrough cases in switch statement." }, + Do_not_report_errors_on_unreachable_code: { code: 6077, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unreachable_code_6077", message: "Do not report errors on unreachable code." }, + Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, + Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, + Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -1696,6 +1705,10 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", message: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: ts.DiagnosticCategory.Error, key: "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", message: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." }, JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", message: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists" }, + Unreachable_code_detected: { code: 7027, category: ts.DiagnosticCategory.Error, key: "Unreachable_code_detected_7027", message: "Unreachable code detected." }, + Unused_label: { code: 7028, category: ts.DiagnosticCategory.Error, key: "Unused_label_7028", message: "Unused label." }, + Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, + Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -3225,6 +3238,12 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code }, + { + name: "pretty", + paramType: ts.Diagnostics.KIND, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental, + type: "boolean" + }, { name: "project", shortName: "p", @@ -3323,11 +3342,31 @@ var ts; description: ts.Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, error: ts.Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic }, + { + name: "allowUnusedLabels", + type: "boolean", + description: ts.Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "noImplicitReturns", + type: "boolean", + description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + { + name: "allowUnreachableCode", + type: "boolean", + description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code + }, { name: "forceConsistentCasingInFileNames", type: "boolean", description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file - }, + } ]; var optionNameMapCache; function getOptionNameMap() { @@ -3453,13 +3492,31 @@ var ts; ts.readConfigFile = readConfigFile; function parseConfigFileTextToJson(fileName, jsonText) { try { - return { config: /\S/.test(jsonText) ? JSON.parse(jsonText) : {} }; + var jsonTextWithoutComments = removeComments(jsonText); + return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + function removeComments(jsonText) { + var output = ""; + var scanner = ts.createScanner(1, false, 0, jsonText); + var token; + while ((token = scanner.scan()) !== 1) { + switch (token) { + case 2: + case 3: + output += scanner.getTokenText().replace(/\S/g, " "); + break; + default: + output += scanner.getTokenText(); + break; + } + } + return output; + } function parseJsonConfigFileContent(json, host, basePath) { var _a = convertCompilerOptionsFromJson(json["compilerOptions"], basePath), options = _a.options, errors = _a.errors; return { @@ -3551,8 +3608,8 @@ var ts; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; if (declaration.kind === kind) { return declaration; } @@ -3722,7 +3779,7 @@ var ts; } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 49152) !== 0 || + return (getCombinedNodeFlags(declaration) & 24576) !== 0 || isCatchClauseVariableDeclaration(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; @@ -3823,7 +3880,7 @@ var ts; } ts.isExternalModule = isExternalModule; function isDeclarationFile(file) { - return (file.flags & 8192) !== 0; + return (file.flags & 4096) !== 0; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { @@ -3853,11 +3910,11 @@ var ts; } ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(getCombinedNodeFlags(node) & 32768); + return !!(getCombinedNodeFlags(node) & 16384); } ts.isConst = isConst; function isLet(node) { - return !!(getCombinedNodeFlags(node) & 16384); + return !!(getCombinedNodeFlags(node) & 8192); } ts.isLet = isLet; function isPrologueDirective(node) { @@ -4036,27 +4093,28 @@ var ts; } ts.isClassLike = isClassLike; function isFunctionLike(node) { - if (node) { - switch (node.kind) { - case 144: - case 173: - case 213: - case 174: - case 143: - case 142: - case 145: - case 146: - case 147: - case 148: - case 149: - case 152: - case 153: - return true; - } - } - return false; + return node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; + function isFunctionLikeKind(kind) { + switch (kind) { + case 144: + case 173: + case 213: + case 174: + case 143: + case 142: + case 145: + case 146: + case 147: + case 148: + case 149: + case 152: + case 153: + return true; + } + } + ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 143: @@ -4520,9 +4578,18 @@ var ts; return !!node && (node.kind === 162 || node.kind === 161); } ts.isBindingPattern = isBindingPattern; + function isNodeDescendentOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + ts.isNodeDescendentOf = isNodeDescendentOf; function isInAmbientContext(node) { while (node) { - if (node.flags & (2 | 8192)) { + if (node.flags & (4 | 4096)) { return true; } node = node.parent; @@ -4580,7 +4647,7 @@ var ts; case 207: case 204: case 206: - case 98: + case 208: case 209: case 193: case 198: @@ -4679,8 +4746,8 @@ var ts; ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; function getHeritageClause(clauses, kind) { if (clauses) { - for (var _i = 0; _i < clauses.length; _i++) { - var clause = clauses[_i]; + for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { + var clause = clauses_1[_i]; if (clause.token === kind) { return clause; } @@ -4692,7 +4759,6 @@ var ts; function tryResolveScriptReference(host, sourceFile, reference) { if (!host.getCompilerOptions().noResolve) { var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); - referenceFileName = ts.getNormalizedAbsolutePath(referenceFileName, host.getCurrentDirectory()); return host.getSourceFile(referenceFileName); } } @@ -4750,7 +4816,7 @@ var ts; } ts.isTrivia = isTrivia; function isAsyncFunctionLike(node) { - return isFunctionLike(node) && (node.flags & 512) !== 0 && !isAccessor(node); + return isFunctionLike(node) && (node.flags & 256) !== 0 && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; function hasDynamicName(declaration) { @@ -5108,7 +5174,7 @@ var ts; else { ts.forEach(declarations, function (member) { if ((member.kind === 145 || member.kind === 146) - && (member.flags & 128) === (accessor.flags & 128)) { + && (member.flags & 64) === (accessor.flags & 64)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -5163,6 +5229,49 @@ var ts; }); } ts.emitComments = emitComments; + function emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, removeComments) { + var leadingComments; + var currentDetachedCommentInfo; + if (removeComments) { + if (node.pos === 0) { + leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment); + } + } + else { + leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment; + for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { + var comment = leadingComments_1[_i]; + if (lastComment) { + var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); + var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); + if (commentLine >= lastCommentLine + 2) { + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + var lastCommentLine = getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); + var nodeLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedComment(comment) { + return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 && + currentSourceFile.text.charCodeAt(comment.pos + 2) === 33; + } + } + ts.emitDetachedComments = emitDetachedComments; function writeCommentRange(currentSourceFile, writer, comment, newLine) { if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42) { var firstCommentLineAndCharacter = ts.getLineAndCharacterOfPosition(currentSourceFile, comment.pos); @@ -5227,16 +5336,16 @@ var ts; ts.writeCommentRange = writeCommentRange; function modifierToFlag(token) { switch (token) { - case 113: return 128; - case 112: return 16; - case 111: return 64; - case 110: return 32; - case 115: return 256; - case 82: return 1; - case 122: return 2; - case 74: return 32768; - case 77: return 1024; - case 118: return 512; + case 113: return 64; + case 112: return 8; + case 111: return 32; + case 110: return 16; + case 115: return 128; + case 82: return 2; + case 122: return 4; + case 74: return 16384; + case 77: return 512; + case 118: return 256; } return 0; } @@ -5315,7 +5424,7 @@ var ts; } ts.isEmptyObjectLiteralOrArrayLiteral = isEmptyObjectLiteralOrArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 1024) ? symbol.valueDeclaration.localSymbol : undefined; + return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function isJavaScript(fileName) { @@ -5379,6 +5488,12 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !ts.isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -5551,8 +5666,8 @@ var ts; } function visitEachNode(cbNode, nodes) { if (nodes) { - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; var result = cbNode(node); if (result) { return result; @@ -6013,8 +6128,8 @@ var ts; function addJSDocComment(node) { var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); if (comments) { - for (var _i = 0; _i < comments.length; _i++) { - var comment = comments[_i]; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); if (jsDocComment) { node.jsDocComment = jsDocComment; @@ -6045,7 +6160,7 @@ var ts; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); - sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 8192 : 0; + sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 : 0; sourceFile.languageVariant = ts.isTsx(sourceFile.fileName) ? 1 : 0; return sourceFile; } @@ -6881,7 +6996,7 @@ var ts; if (node.kind === 8 && sourceText.charCodeAt(tokenPos) === 48 && ts.isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { - node.flags |= 65536; + node.flags |= 32768; } return node; } @@ -7450,7 +7565,7 @@ var ts; if (!arrowFunction) { return undefined; } - var isAsync = !!(arrowFunction.flags & 512); + var isAsync = !!(arrowFunction.flags & 256); var lastToken = token; arrowFunction.equalsGreaterThanToken = parseExpectedToken(34, false, ts.Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === 34 || lastToken === 15) @@ -7542,7 +7657,7 @@ var ts; function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(174); setModifiers(node, parseModifiersForArrowFunction()); - var isAsync = !!(node.flags & 512); + var isAsync = !!(node.flags & 256); fillSignature(54, false, isAsync, !allowAmbiguity, node); if (!node.parameters) { return undefined; @@ -8156,7 +8271,7 @@ var ts; var node = createNode(164); parseExpected(19); if (scanner.hasPrecedingLineBreak()) - node.flags |= 2048; + node.flags |= 1024; node.elements = parseDelimitedList(15, parseArgumentOrArrayLiteralElement); parseExpected(20); return finishNode(node); @@ -8211,7 +8326,7 @@ var ts; var node = createNode(165); parseExpected(15); if (scanner.hasPrecedingLineBreak()) { - node.flags |= 2048; + node.flags |= 1024; } node.properties = parseDelimitedList(12, parseObjectLiteralElement, true); parseExpected(16); @@ -8227,7 +8342,7 @@ var ts; parseExpected(87); node.asteriskToken = parseOptionalToken(37); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 512); + var isAsync = !!(node.flags & 256); node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -8765,10 +8880,10 @@ var ts; case 102: break; case 108: - node.flags |= 16384; + node.flags |= 8192; break; case 74: - node.flags |= 32768; + node.flags |= 16384; break; default: ts.Debug.fail(); @@ -8802,9 +8917,9 @@ var ts; setModifiers(node, modifiers); parseExpected(87); node.asteriskToken = parseOptionalToken(37); - node.name = node.flags & 1024 ? parseOptionalIdentifier() : parseIdentifier(); + node.name = node.flags & 512 ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 512); + var isAsync = !!(node.flags & 256); fillSignature(54, isGenerator, isAsync, false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return finishNode(node); @@ -8826,7 +8941,7 @@ var ts; method.name = name; method.questionToken = questionToken; var isGenerator = !!asteriskToken; - var isAsync = !!(method.flags & 512); + var isAsync = !!(method.flags & 256); fillSignature(54, isGenerator, isAsync, false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return finishNode(method); @@ -8838,7 +8953,7 @@ var ts; property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); - property.initializer = modifiers && modifiers.flags & 128 + property.initializer = modifiers && modifiers.flags & 64 ? allowInAnd(parseNonParameterInitializer) : doOutsideOfContext(2 | 1, parseNonParameterInitializer); parseSemicolon(); @@ -9128,13 +9243,13 @@ var ts; } function parseModuleOrNamespaceDeclaration(fullStart, decorators, modifiers, flags) { var node = createNode(218, fullStart); - var namespaceFlag = flags & 131072; + var namespaceFlag = flags & 65536; node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(21) - ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 1 | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), undefined, undefined, 2 | namespaceFlag) : parseModuleBlock(); return finishNode(node); } @@ -9149,7 +9264,7 @@ var ts; function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; if (parseOptional(126)) { - flags |= 131072; + flags |= 65536; } else { parseExpected(125); @@ -9363,7 +9478,7 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return node.flags & 1 + return node.flags & 2 || node.kind === 221 && node.moduleReference.kind === 232 || node.kind === 222 || node.kind === 227 @@ -9937,8 +10052,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0; _i < array.length; _i++) { - var node = array[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var node = array_7[_i]; visitNode(node); } } @@ -10010,8 +10125,8 @@ var ts; array.intersectsChange = true; array._children = undefined; adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0; _i < array.length; _i++) { - var node = array[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } return; @@ -10164,6 +10279,13 @@ var ts; var ts; (function (ts) { ts.bindTime = 0; + function or(state1, state2) { + return (state1 | state2) & 2 + ? 2 + : (state1 & state2) & 8 + ? 8 + : 4; + } function getModuleInstanceState(node) { if (node.kind === 215 || node.kind === 216) { return 0; @@ -10171,7 +10293,7 @@ var ts; else if (ts.isConstEnumDeclaration(node)) { return 2; } - else if ((node.kind === 222 || node.kind === 221) && !(node.flags & 1)) { + else if ((node.kind === 222 || node.kind === 221) && !(node.flags & 2)) { return 0; } else if (node.kind === 219) { @@ -10198,28 +10320,52 @@ var ts; } } ts.getModuleInstanceState = getModuleInstanceState; - function bindSourceFile(file) { + var binder = createBinder(); + function bindSourceFile(file, options) { var start = new Date().getTime(); - bindSourceFileWorker(file); + binder(file, options); ts.bindTime += new Date().getTime() - start; } ts.bindSourceFile = bindSourceFile; - function bindSourceFileWorker(file) { + function createBinder() { + var file; + var options; var parent; var container; var blockScopeContainer; var lastContainer; var seenThisKeyword; - var inStrictMode = !!file.externalModuleIndicator; + var hasExplicitReturn; + var currentReachabilityState; + var labelStack; + var labelIndexMap; + var implicitLabels; + var inStrictMode; var symbolCount = 0; - var Symbol = ts.objectAllocator.getSymbolConstructor(); - var classifiableNames = {}; - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; + var Symbol; + var classifiableNames; + function bindSourceFile(f, opts) { + file = f; + options = opts; + inStrictMode = !!file.externalModuleIndicator; + classifiableNames = {}; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + hasExplicitReturn = false; + labelStack = undefined; + labelIndexMap = undefined; + implicitLabels = undefined; } - return; + return bindSourceFile; function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -10270,7 +10416,7 @@ var ts; return node.isExportEquals ? "export=" : "default"; case 213: case 214: - return node.flags & 1024 ? "default" : undefined; + return node.flags & 512 ? "default" : undefined; } } function getDisplayName(node) { @@ -10278,7 +10424,7 @@ var ts; } function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = node.flags & 1024; + var isDefaultExport = node.flags & 512; var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; if (name !== undefined) { @@ -10296,7 +10442,7 @@ var ts; ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 1024) { + if (declaration.flags & 512) { message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } }); @@ -10315,7 +10461,7 @@ var ts; return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedNodeFlags(node) & 1; + var hasExportModifier = ts.getCombinedNodeFlags(node) & 2; if (symbolFlags & 8388608) { if (node.kind === 230 || (node.kind === 221 && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -10325,7 +10471,7 @@ var ts; } } else { - if (hasExportModifier || container.flags & 262144) { + if (hasExportModifier || container.flags & 131072) { var exportKind = (symbolFlags & 107455 ? 1048576 : 0) | (symbolFlags & 793056 ? 2097152 : 0) | (symbolFlags & 1536 ? 4194304 : 0); @@ -10356,18 +10502,202 @@ var ts; blockScopeContainer = node; blockScopeContainer.locals = undefined; } - if (node.kind === 215) { + var savedReachabilityState; + var savedLabelStack; + var savedLabels; + var savedImplicitLabels; + var savedHasExplicitReturn; + var kind = node.kind; + var flags = node.flags; + flags &= ~1572864; + if (kind === 215) { seenThisKeyword = false; - ts.forEachChild(node, bind); - node.flags = seenThisKeyword ? node.flags | 524288 : node.flags & ~524288; } - else { - ts.forEachChild(node, bind); + var saveState = kind === 248 || kind === 219 || ts.isFunctionLikeKind(kind); + if (saveState) { + savedReachabilityState = currentReachabilityState; + savedLabelStack = labelStack; + savedLabels = labelIndexMap; + savedImplicitLabels = implicitLabels; + savedHasExplicitReturn = hasExplicitReturn; + currentReachabilityState = 2; + hasExplicitReturn = false; + labelStack = labelIndexMap = implicitLabels = undefined; + } + bindReachableStatement(node); + if (currentReachabilityState === 2 && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) { + flags |= 524288; + if (hasExplicitReturn) { + flags |= 1048576; + } + } + if (kind === 215) { + flags = seenThisKeyword ? flags | 262144 : flags & ~262144; + } + node.flags = flags; + if (saveState) { + hasExplicitReturn = savedHasExplicitReturn; + currentReachabilityState = savedReachabilityState; + labelStack = savedLabelStack; + labelIndexMap = savedLabels; + implicitLabels = savedImplicitLabels; } container = saveContainer; parent = saveParent; blockScopeContainer = savedBlockScopeContainer; } + function bindReachableStatement(node) { + if (checkUnreachable(node)) { + ts.forEachChild(node, bind); + return; + } + switch (node.kind) { + case 198: + bindWhileStatement(node); + break; + case 197: + bindDoStatement(node); + break; + case 199: + bindForStatement(node); + break; + case 200: + case 201: + bindForInOrForOfStatement(node); + break; + case 196: + bindIfStatement(node); + break; + case 204: + case 208: + bindReturnOrThrow(node); + break; + case 203: + case 202: + bindBreakOrContinueStatement(node); + break; + case 209: + bindTryStatement(node); + break; + case 206: + bindSwitchStatement(node); + break; + case 220: + bindCaseBlock(node); + break; + case 207: + bindLabeledStatement(node); + break; + default: + ts.forEachChild(node, bind); + break; + } + } + function bindWhileStatement(n) { + var preWhileState = n.expression.kind === 84 ? 4 : currentReachabilityState; + var postWhileState = n.expression.kind === 99 ? 4 : currentReachabilityState; + bind(n.expression); + currentReachabilityState = preWhileState; + var postWhileLabel = pushImplicitLabel(); + bind(n.statement); + popImplicitLabel(postWhileLabel, postWhileState); + } + function bindDoStatement(n) { + var preDoState = currentReachabilityState; + var postDoLabel = pushImplicitLabel(); + bind(n.statement); + var postDoState = n.expression.kind === 99 ? 4 : preDoState; + popImplicitLabel(postDoLabel, postDoState); + bind(n.expression); + } + function bindForStatement(n) { + var preForState = currentReachabilityState; + var postForLabel = pushImplicitLabel(); + bind(n.initializer); + bind(n.condition); + bind(n.incrementor); + bind(n.statement); + var isInfiniteLoop = (!n.condition || n.condition.kind === 99); + var postForState = isInfiniteLoop ? 4 : preForState; + popImplicitLabel(postForLabel, postForState); + } + function bindForInOrForOfStatement(n) { + var preStatementState = currentReachabilityState; + var postStatementLabel = pushImplicitLabel(); + bind(n.initializer); + bind(n.expression); + bind(n.statement); + popImplicitLabel(postStatementLabel, preStatementState); + } + function bindIfStatement(n) { + var ifTrueState = n.expression.kind === 84 ? 4 : currentReachabilityState; + var ifFalseState = n.expression.kind === 99 ? 4 : currentReachabilityState; + currentReachabilityState = ifTrueState; + bind(n.expression); + bind(n.thenStatement); + if (n.elseStatement) { + var preElseState = currentReachabilityState; + currentReachabilityState = ifFalseState; + bind(n.elseStatement); + currentReachabilityState = or(currentReachabilityState, preElseState); + } + else { + currentReachabilityState = or(currentReachabilityState, ifFalseState); + } + } + function bindReturnOrThrow(n) { + bind(n.expression); + if (n.kind === 204) { + hasExplicitReturn = true; + } + currentReachabilityState = 4; + } + function bindBreakOrContinueStatement(n) { + bind(n.label); + var isValidJump = jumpToLabel(n.label, n.kind === 203 ? currentReachabilityState : 4); + if (isValidJump) { + currentReachabilityState = 4; + } + } + function bindTryStatement(n) { + var preTryState = currentReachabilityState; + bind(n.tryBlock); + var postTryState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.catchClause); + var postCatchState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.finallyBlock); + currentReachabilityState = or(postTryState, postCatchState); + } + function bindSwitchStatement(n) { + var preSwitchState = currentReachabilityState; + var postSwitchLabel = pushImplicitLabel(); + bind(n.expression); + bind(n.caseBlock); + var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242; }); + var postSwitchState = hasDefault && currentReachabilityState !== 2 ? 4 : preSwitchState; + popImplicitLabel(postSwitchLabel, postSwitchState); + } + function bindCaseBlock(n) { + var startState = currentReachabilityState; + for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + currentReachabilityState = startState; + bind(clause); + if (clause.statements.length && currentReachabilityState === 2 && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + } + function bindLabeledStatement(n) { + bind(n.label); + var ok = pushNamedLabel(n.label); + bind(n.statement); + if (ok) { + popNamedLabel(n.label, currentReachabilityState); + } + } function getContainerFlags(node) { switch (node.kind) { case 186: @@ -10447,7 +10777,7 @@ var ts; } } function declareClassMember(node, symbolFlags, symbolExcludes) { - return node.flags & 128 + return node.flags & 64 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } @@ -10456,15 +10786,6 @@ var ts; ? declareModuleMember(node, symbolFlags, symbolExcludes) : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } - function isAmbientContext(node) { - while (node) { - if (node.flags & 2) { - return true; - } - node = node.parent; - } - return false; - } function hasExportDeclarations(node) { var body = node.kind === 248 ? node : node.body; if (body.kind === 248 || body.kind === 219) { @@ -10478,11 +10799,11 @@ var ts; return false; } function setExportContextFlag(node) { - if (isAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 262144; + if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 131072; } else { - node.flags &= ~262144; + node.flags &= ~131072; } } function bindModuleDeclaration(node) { @@ -10633,7 +10954,7 @@ var ts; } } function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.flags & 65536) { + if (inStrictMode && node.flags & 32768) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } @@ -10651,10 +10972,10 @@ var ts; } function checkStrictModeWithStatement(node) { if (inStrictMode) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); } } - function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + function errorOnFirstToken(node, message, arg0, arg1, arg2) { var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } @@ -10662,6 +10983,9 @@ var ts; return "__" + ts.indexOf(node.parent.parameters, node); } function bind(node) { + if (!node) { + return; + } node.parent = parent; var savedInStrictMode = inStrictMode; if (!savedInStrictMode) { @@ -10689,8 +11013,8 @@ var ts; } } function updateStrictModeStatementList(statements) { - for (var _i = 0; _i < statements.length; _i++) { - var statement = statements[_i]; + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; if (!ts.isPrologueDirective(statement)) { return; } @@ -10877,7 +11201,7 @@ var ts; else { declareSymbolAndAddToSymbolTable(node, 1, 107455); } - if (node.flags & 112 && + if (node.flags & 56 && node.parent.kind === 144 && ts.isClassLike(node.parent.parent)) { var classDeclaration = node.parent.parent; @@ -10889,6 +11213,95 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } + function pushNamedLabel(name) { + initializeReachabilityStateIfNecessary(); + if (ts.hasProperty(labelIndexMap, name.text)) { + return false; + } + labelIndexMap[name.text] = labelStack.push(1) - 1; + return true; + } + function pushImplicitLabel() { + initializeReachabilityStateIfNecessary(); + var index = labelStack.push(1) - 1; + implicitLabels.push(index); + return index; + } + function popNamedLabel(label, outerState) { + var index = labelIndexMap[label.text]; + ts.Debug.assert(index !== undefined); + ts.Debug.assert(labelStack.length == index + 1); + labelIndexMap[label.text] = undefined; + setCurrentStateAtLabel(labelStack.pop(), outerState, label); + } + function popImplicitLabel(implicitLabelIndex, outerState) { + if (labelStack.length !== implicitLabelIndex + 1) { + ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex); + } + var i = implicitLabels.pop(); + if (implicitLabelIndex !== i) { + ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex); + } + setCurrentStateAtLabel(labelStack.pop(), outerState, undefined); + } + function setCurrentStateAtLabel(innerMergedState, outerState, label) { + if (innerMergedState === 1) { + if (label && !options.allowUnusedLabels) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label)); + } + currentReachabilityState = outerState; + } + else { + currentReachabilityState = or(innerMergedState, outerState); + } + } + function jumpToLabel(label, outerState) { + initializeReachabilityStateIfNecessary(); + var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels); + if (index === undefined) { + return false; + } + var stateAtLabel = labelStack[index]; + labelStack[index] = stateAtLabel === 1 ? outerState : or(stateAtLabel, outerState); + return true; + } + function checkUnreachable(node) { + switch (currentReachabilityState) { + case 4: + var reportError = ts.isStatement(node) || + node.kind === 214 || + (node.kind === 218 && shouldReportErrorOnModuleDeclaration(node)) || + (node.kind === 217 && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + if (reportError) { + currentReachabilityState = 8; + var reportUnreachableCode = !options.allowUnreachableCode && + !ts.isInAmbientContext(node) && + (node.kind !== 193 || + ts.getCombinedNodeFlags(node.declarationList) & 24576 || + ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); + if (reportUnreachableCode) { + errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + } + } + case 8: + return true; + default: + return false; + } + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 || (instanceState === 2 && options.preserveConstEnums); + } + } + function initializeReachabilityStateIfNecessary() { + if (labelIndexMap) { + return; + } + currentReachabilityState = 2; + labelIndexMap = {}; + labelStack = []; + implicitLabels = []; + } } })(ts || (ts = {})); var ts; @@ -11014,6 +11427,7 @@ var ts; var getInstantiatedGlobalPromiseLikeType; var getGlobalPromiseConstructorLikeType; var getGlobalThenableType; + var jsxElementClassType; var tupleTypes = {}; var unionTypes = {}; var intersectionTypes = {}; @@ -11262,7 +11676,7 @@ var ts; } var initializerOfNonStaticProperty = current.parent && current.parent.kind === 141 && - (current.parent.flags & 128) === 0 && + (current.parent.flags & 64) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -11321,7 +11735,7 @@ var ts; break; case 141: case 140: - if (ts.isClassLike(location.parent) && !(location.flags & 128)) { + if (ts.isClassLike(location.parent) && !(location.flags & 64)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455)) { @@ -11334,7 +11748,7 @@ var ts; case 186: case 215: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056)) { - if (lastLocation && lastLocation.flags & 128) { + if (lastLocation && lastLocation.flags & 64) { error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters); return undefined; } @@ -11768,8 +12182,8 @@ var ts; } function findConstructorDeclaration(node) { var members = node.members; - for (var _i = 0; _i < members.length; _i++) { - var member = members[_i]; + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var member = members_1[_i]; if (member.kind === 144 && ts.nodeIsPresent(member.body)) { return member; } @@ -11975,7 +12389,7 @@ var ts; if (!isDeclarationVisible(declaration)) { var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 1) && + !(anyImportSyntax.flags & 2) && isDeclarationVisible(anyImportSyntax.parent)) { getNodeLinks(declaration).isVisible = true; if (aliasesToMakeVisible) { @@ -12105,8 +12519,8 @@ var ts; walkSymbol(getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol), getQualifiedLeftMeaning(meaning)); } if (accessibleSymbolChain) { - for (var _i = 0; _i < accessibleSymbolChain.length; _i++) { - var accessibleSymbol = accessibleSymbolChain[_i]; + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } @@ -12272,7 +12686,7 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 128; })); + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 64; })); var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { @@ -12378,8 +12792,8 @@ var ts; var t = getTypeOfSymbol(p); if (p.flags & (16 | 8192) && !getPropertiesOfObjectType(t).length) { var signatures = getSignaturesOfType(t, 0); - for (var _f = 0; _f < signatures.length; _f++) { - var signature = signatures[_f]; + for (var _f = 0, signatures_1 = signatures; _f < signatures_1.length; _f++) { + var signature = signatures_1[_f]; buildSymbolDisplay(p, writer); if (p.flags & 536870912) { writePunctuation(writer, 53); @@ -12582,7 +12996,7 @@ var ts; case 217: case 221: var parent_4 = getDeclarationContainer(node); - if (!(ts.getCombinedNodeFlags(node) & 1) && + if (!(ts.getCombinedNodeFlags(node) & 2) && !(node.kind !== 221 && parent_4.kind !== 248 && ts.isInAmbientContext(parent_4))) { return isGlobalSourceFile(parent_4); } @@ -12593,7 +13007,7 @@ var ts; case 146: case 143: case 142: - if (node.flags & (32 | 64)) { + if (node.flags & (16 | 32)) { return false; } case 144: @@ -13022,8 +13436,8 @@ var ts; } } function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); if (!typeParameters) { typeParameters = [tp]; @@ -13204,13 +13618,13 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 215) { - if (declaration.flags & 524288) { + if (declaration.flags & 262144) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { - for (var _b = 0; _b < baseTypeNodes.length; _b++) { - var node = baseTypeNodes[_b]; + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; if (ts.isSupportedExpressionWithTypeArguments(node)) { var baseSymbol = resolveEntityName(node.expression, 793056, true); if (!baseSymbol || !(baseSymbol.flags & 64) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { @@ -13378,23 +13792,23 @@ var ts; } function createSymbolTable(symbols) { var result = {}; - for (var _i = 0; _i < symbols.length; _i++) { - var symbol = symbols[_i]; + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; result[symbol.name] = symbol; } return result; } function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { var result = {}; - for (var _i = 0; _i < symbols.length; _i++) { - var symbol = symbols[_i]; + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); } return result; } function addInheritedMembers(symbols, baseSymbols) { - for (var _i = 0; _i < baseSymbols.length; _i++) { - var s = baseSymbols[_i]; + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; if (!ts.hasProperty(symbols, s.name)) { symbols[s.name] = s; } @@ -13402,8 +13816,8 @@ var ts; } function addInheritedSignatures(signatures, baseSignatures) { if (baseSignatures) { - for (var _i = 0; _i < baseSignatures.length; _i++) { - var signature = baseSignatures[_i]; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var signature = baseSignatures_1[_i]; signatures.push(signature); } } @@ -13446,8 +13860,8 @@ var ts; members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); - for (var _i = 0; _i < baseTypes.length; _i++) { - var baseType = baseTypes[_i]; + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0)); @@ -13493,8 +13907,8 @@ var ts; var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; - for (var _i = 0; _i < baseSignatures.length; _i++) { - var baseSig = baseSignatures[_i]; + for (var _i = 0, baseSignatures_2 = baseSignatures; _i < baseSignatures_2.length; _i++) { + var baseSig = baseSignatures_2[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); @@ -13522,8 +13936,8 @@ var ts; setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); } function findMatchingSignature(signatureList, signature, partialMatch, ignoreReturnTypes) { - for (var _i = 0; _i < signatureList.length; _i++) { - var s = signatureList[_i]; + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { return s; } @@ -13577,8 +13991,8 @@ var ts; } function getUnionIndexType(types, kind) { var indexTypes = []; - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexType = getIndexTypeOfType(type, kind); if (!indexType) { return undefined; @@ -13742,12 +14156,12 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (32 | 64))) { + if (prop && !(getDeclarationFlagsFromSymbol(prop) & (16 | 32))) { if (!props) { props = [prop]; } @@ -13768,8 +14182,8 @@ var ts; } var propTypes = []; var declarations = []; - for (var _a = 0; _a < props.length; _a++) { - var prop = props[_a]; + for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { + var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } @@ -14102,8 +14516,8 @@ var ts; } function getPropagatingFlagsOfTypes(types) { var result = 0; - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type = types_3[_i]; result |= type.flags; } return result & 14680064; @@ -14224,8 +14638,8 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; switch (declaration.kind) { case 214: case 215: @@ -14323,8 +14737,8 @@ var ts; } } function addTypesToSet(typeSet, types, typeSetKind) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; addTypeToSet(typeSet, type, typeSetKind); } } @@ -14346,8 +14760,8 @@ var ts; } } function containsTypeAny(types) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (isTypeAny(type)) { return true; } @@ -14450,7 +14864,8 @@ var ts; var container = ts.getThisContainer(node, false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 215)) { - if (!(container.flags & 128)) { + if (!(container.flags & 64) && + (container.kind !== 144 || ts.isNodeDescendentOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -14515,8 +14930,8 @@ var ts; function instantiateList(items, mapper, instantiator) { if (items && items.length) { var result = []; - for (var _i = 0; _i < items.length; _i++) { - var v = items[_i]; + for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { + var v = items_1[_i]; result.push(instantiator(v, mapper)); } return result; @@ -14555,8 +14970,8 @@ var ts; case 2: return createBinaryTypeEraser(sources[0], sources[1]); } return function (t) { - for (var _i = 0; _i < sources.length; _i++) { - var source = sources[_i]; + for (var _i = 0, sources_1 = sources; _i < sources_1.length; _i++) { + var source = sources_1[_i]; if (t === source) { return anyType; } @@ -14921,8 +15336,8 @@ var ts; function eachTypeRelatedToSomeType(source, target) { var result = -1; var sourceTypes = source.types; - for (var _i = 0; _i < sourceTypes.length; _i++) { - var sourceType = sourceTypes[_i]; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; var related = typeRelatedToSomeType(sourceType, target, false); if (!related) { return 0; @@ -14944,8 +15359,8 @@ var ts; function typeRelatedToEachType(source, target, reportErrors) { var result = -1; var targetTypes = target.types; - for (var _i = 0; _i < targetTypes.length; _i++) { - var targetType = targetTypes[_i]; + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var targetType = targetTypes_1[_i]; var related = isRelatedTo(source, targetType, reportErrors); if (!related) { return 0; @@ -14967,8 +15382,8 @@ var ts; function eachTypeRelatedToType(source, target, reportErrors) { var result = -1; var sourceTypes = source.types; - for (var _i = 0; _i < sourceTypes.length; _i++) { - var sourceType = sourceTypes[_i]; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; var related = isRelatedTo(sourceType, target, reportErrors); if (!related) { return 0; @@ -15081,8 +15496,8 @@ var ts; var result = -1; var properties = getPropertiesOfObjectType(target); var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288); - for (var _i = 0; _i < properties.length; _i++) { - var targetProp = properties[_i]; + for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { + var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -15096,20 +15511,20 @@ var ts; else if (!(targetProp.flags & 134217728)) { var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); - if (sourcePropFlags & 32 || targetPropFlags & 32) { + if (sourcePropFlags & 16 || targetPropFlags & 16) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { - if (sourcePropFlags & 32 && targetPropFlags & 32) { + if (sourcePropFlags & 16 && targetPropFlags & 16) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); } else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 32 ? source : target), typeToString(sourcePropFlags & 32 ? target : source)); + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 16 ? source : target), typeToString(sourcePropFlags & 16 ? target : source)); } } return 0; } } - else if (targetPropFlags & 64) { + else if (targetPropFlags & 32) { var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32; var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; var targetClass = getDeclaredTypeOfSymbol(targetProp.parent); @@ -15120,7 +15535,7 @@ var ts; return 0; } } - else if (sourcePropFlags & 64) { + else if (sourcePropFlags & 32) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -15155,8 +15570,8 @@ var ts; return 0; } var result = -1; - for (var _i = 0; _i < sourceProperties.length; _i++) { - var sourceProp = sourceProperties[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return 0; @@ -15188,13 +15603,13 @@ var ts; return result; } } - outer: for (var _i = 0; _i < targetSignatures.length; _i++) { - var t = targetSignatures[_i]; + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; if (!t.hasStringLiterals || target.flags & 262144) { var localErrors = reportErrors; var checkedAbstractAssignability = false; - for (var _a = 0; _a < sourceSignatures.length; _a++) { - var s = sourceSignatures[_a]; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; if (!s.hasStringLiterals || source.flags & 262144) { var related = signatureRelatedTo(s, t, localErrors); if (related) { @@ -15222,8 +15637,8 @@ var ts; var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 256; - var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 256; + var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 128; + var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 128; if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { if (reportErrors) { reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type); @@ -15424,8 +15839,8 @@ var ts; if (sourceProp === targetProp) { return -1; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (32 | 64); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (32 | 64); + var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (16 | 32); + var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (16 | 32); if (sourcePropAccessibility !== targetPropAccessibility) { return 0; } @@ -15491,8 +15906,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; if (candidate !== type && !isTypeSubtypeOf(type, candidate)) return false; } @@ -15705,8 +16120,8 @@ var ts; } function createInferenceContext(typeParameters, inferUnionTypes) { var inferences = []; - for (var _i = 0; _i < typeParameters.length; _i++) { - var unused = typeParameters[_i]; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var unused = typeParameters_1[_i]; inferences.push({ primary: undefined, secondary: undefined, isFixed: false }); @@ -15772,8 +16187,8 @@ var ts; var targetTypes = target.types; var typeParameterCount = 0; var typeParameter; - for (var _i = 0; _i < targetTypes.length; _i++) { - var t = targetTypes[_i]; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var t = targetTypes_2[_i]; if (t.flags & 512 && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; @@ -15790,8 +16205,8 @@ var ts; } else if (source.flags & 49152) { var sourceTypes = source.types; - for (var _a = 0; _a < sourceTypes.length; _a++) { - var sourceType = sourceTypes[_a]; + for (var _a = 0, sourceTypes_3 = sourceTypes; _a < sourceTypes_3.length; _a++) { + var sourceType = sourceTypes_3[_a]; inferFromTypes(sourceType, target); } } @@ -15824,8 +16239,8 @@ var ts; } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0; _i < properties.length; _i++) { - var targetProp = properties[_i]; + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var targetProp = properties_2[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -16316,7 +16731,7 @@ var ts; break; case 141: case 140: - if (container.flags & 128) { + if (container.flags & 64) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; @@ -16329,7 +16744,7 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - return container.flags & 128 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return container.flags & 64 ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; } return anyType; } @@ -16357,7 +16772,7 @@ var ts; var canUseSuperExpression = isLegalUsageOfSuperExpression(container); var nodeCheckFlag = 0; if (canUseSuperExpression) { - if ((container.flags & 128) || isCallExpression) { + if ((container.flags & 64) || isCallExpression) { nodeCheckFlag = 512; } else { @@ -16402,7 +16817,7 @@ var ts; } else { if (container && ts.isClassLike(container.parent)) { - if (container.flags & 128) { + if (container.flags & 64) { return container.kind === 143 || container.kind === 142 || container.kind === 145 || @@ -16541,8 +16956,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var current = types_7[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -16706,8 +17121,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -16758,8 +17173,8 @@ var ts; var hasSpreadElement = false; var elementTypes = []; var inDestructuringPattern = isAssignmentTarget(node); - for (var _i = 0; _i < elements.length; _i++) { - var e = elements[_i]; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var e = elements_1[_i]; if (inDestructuringPattern && e.kind === 185) { var restArrayType = checkExpression(e.expression, contextualMapper); var restElementType = getIndexTypeOfType(restArrayType, 1) || @@ -17018,8 +17433,8 @@ var ts; function checkJsxSpreadAttribute(node, elementAttributesType, nameTable) { var type = checkExpression(node.expression); var props = getPropertiesOfType(type); - for (var _i = 0; _i < props.length; _i++) { - var prop = props[_i]; + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; if (!nameTable[prop.name]) { var targetPropSym = getPropertyOfType(elementAttributesType, prop.name); if (targetPropSym) { @@ -17188,7 +17603,6 @@ var ts; var prop = getPropertyOfType(attributesType, attrib.name.text); return prop || unknownSymbol; } - var jsxElementClassType = undefined; function getJsxGlobalElementClassType() { if (!jsxElementClassType) { jsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); @@ -17255,7 +17669,7 @@ var ts; return s.valueDeclaration ? s.valueDeclaration.kind : 141; } function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 ? 16 | 128 : 0; + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 ? 8 | 64 : 0; } function checkClassPropertyAccess(node, left, type, prop) { var flags = getDeclarationFlagsFromSymbol(prop); @@ -17268,17 +17682,17 @@ var ts; error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } - if (flags & 256) { + if (flags & 128) { error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass)); return false; } } - if (!(flags & (32 | 64))) { + if (!(flags & (16 | 32))) { return true; } var enclosingClassDeclaration = ts.getContainingClass(node); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; - if (flags & 32) { + if (flags & 16) { if (declaringClass !== enclosingClass) { error(node, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); return false; @@ -17292,7 +17706,7 @@ var ts; error(node, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass)); return false; } - if (flags & 128) { + if (flags & 64) { return true; } if (type.flags & 33554432) { @@ -17472,8 +17886,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0; _i < signatures.length; _i++) { - var signature = signatures[_i]; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent_5 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -17884,8 +18298,8 @@ var ts; reportError(ts.Diagnostics.Supplied_parameters_do_not_match_any_signature_of_call_target); } if (!produceDiagnostics) { - for (var _i = 0; _i < candidates.length; _i++) { - var candidate = candidates[_i]; + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -17904,8 +18318,8 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); } function chooseOverload(candidates, relation) { - for (var _i = 0; _i < candidates.length; _i++) { - var originalCandidate = candidates[_i]; + for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { + var originalCandidate = candidates_2[_i]; if (!hasCorrectArity(node, args, originalCandidate)) { continue; } @@ -18008,7 +18422,7 @@ var ts; return resolveErrorCall(node); } var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && valueDecl.flags & 256) { + if (valueDecl && valueDecl.flags & 128) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); return resolveErrorCall(node); } @@ -18294,32 +18708,24 @@ var ts; }); return aggregatedTypes; } - function bodyContainsAReturnStatement(funcBody) { - return ts.forEachReturnStatement(funcBody, function (returnStatement) { - return true; - }); - } - function bodyContainsSingleThrowStatement(body) { - return (body.statements.length === 1) && (body.statements[0].kind === 208); - } - function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func, returnType) { + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { if (!produceDiagnostics) { return; } if (returnType === voidType || isTypeAny(returnType)) { return; } - if (ts.nodeIsMissing(func.body) || func.body.kind !== 192) { + if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 || !(func.flags & 524288)) { return; } - var bodyBlock = func.body; - if (bodyContainsAReturnStatement(bodyBlock)) { - return; + if (func.flags & 1048576) { + if (compilerOptions.noImplicitReturns) { + error(func.type, ts.Diagnostics.Not_all_code_paths_return_a_value); + } } - if (bodyContainsSingleThrowStatement(bodyBlock)) { - return; + else { + error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } - error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement); } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { ts.Debug.assert(node.kind !== 143 || ts.isObjectLiteralMethod(node)); @@ -18378,7 +18784,7 @@ var ts; promisedType = checkAsyncFunctionReturnType(node); } if (returnType && !node.asteriskToken) { - checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); } if (node.body) { if (!node.type) { @@ -18437,7 +18843,7 @@ var ts; case 69: case 166: { var symbol = findSymbol(n); - return symbol && (symbol.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 32768) !== 0; + return symbol && (symbol.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 16384) !== 0; } case 167: { var index = n.argumentExpression; @@ -18445,7 +18851,7 @@ var ts; if (symbol && index && index.kind === 9) { var name_13 = index.text; var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_13); - return prop && (prop.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 32768) !== 0; + return prop && (prop.flags & 3) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 16384) !== 0; } return false; } @@ -18525,8 +18931,8 @@ var ts; } if (type.flags & 49152) { var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; if (current.flags & kind) { return true; } @@ -18541,8 +18947,8 @@ var ts; } if (type.flags & 49152) { var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var current = types_10[_i]; if (!(current.flags & kind)) { return false; } @@ -18577,8 +18983,8 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { var properties = node.properties; - for (var _i = 0; _i < properties.length; _i++) { - var p = properties[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var p = properties_3[_i]; if (p.kind === 245 || p.kind === 246) { var name_14 = p.name; var type = isTypeAny(sourceType) @@ -19040,7 +19446,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 112) { + if (node.flags & 56) { func = ts.getContainingFunction(node); if (!(func.kind === 144 && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -19221,7 +19627,7 @@ var ts; function checkMethodDeclaration(node) { checkGrammarMethod(node) || checkGrammarComputedPropertyName(node.name); checkFunctionLikeDeclaration(node); - if (node.flags & 256 && node.body) { + if (node.flags & 128 && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -19268,7 +19674,7 @@ var ts; } function isInstancePropertyWithInitializer(n) { return n.kind === 141 && - !(n.flags & 128) && + !(n.flags & 64) && !!n.initializer; } var containingClassDecl = node.parent; @@ -19281,12 +19687,12 @@ var ts; error(node, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); } var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return p.flags & (16 | 32 | 64); }); + ts.forEach(node.parameters, function (p) { return p.flags & (8 | 16 | 32); }); if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement; - for (var _i = 0; _i < statements.length; _i++) { - var statement = statements[_i]; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; if (statement.kind === 195 && isSuperCallExpression(statement.expression)) { superCallStatement = statement; break; @@ -19312,15 +19718,22 @@ var ts; if (produceDiagnostics) { checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); if (node.kind === 145) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { - error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 524288)) { + if (node.flags & 1048576) { + if (compilerOptions.noImplicitReturns) { + error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + else { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } } } if (!ts.hasDynamicName(node)) { var otherKind = node.kind === 145 ? 146 : 145; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 112) !== (otherAccessor.flags & 112))) { + if (((node.flags & 56) !== (otherAccessor.flags & 56))) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } var currentAccessorType = getAnnotatedAccessorType(node); @@ -19387,7 +19800,7 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 32) && ts.isInAmbientContext(node); + return (node.flags & 16) && ts.isInAmbientContext(node); } function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { if (!produceDiagnostics) { @@ -19412,8 +19825,8 @@ var ts; else { signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); } - for (var _i = 0; _i < signaturesToCheck.length; _i++) { - var otherSignature = signaturesToCheck[_i]; + for (var _i = 0, signaturesToCheck_1 = signaturesToCheck; _i < signaturesToCheck_1.length; _i++) { + var otherSignature = signaturesToCheck_1[_i]; if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { return; } @@ -19426,10 +19839,10 @@ var ts; n.parent.kind !== 214 && n.parent.kind !== 186 && ts.isInAmbientContext(n)) { - if (!(flags & 2)) { - flags |= 1; + if (!(flags & 4)) { + flags |= 2; } - flags |= 2; + flags |= 4; } return flags & flagsToCheck; } @@ -19447,16 +19860,16 @@ var ts; var canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; - if (deviation & 1) { + if (deviation & 2) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); } - else if (deviation & 2) { + else if (deviation & 4) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } - else if (deviation & (32 | 64)) { + else if (deviation & (16 | 32)) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } - else if (deviation & 256) { + else if (deviation & 128) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_not_abstract); } }); @@ -19473,7 +19886,7 @@ var ts; }); } } - var flagsToCheck = 1 | 2 | 32 | 64 | 256; + var flagsToCheck = 2 | 4 | 16 | 32 | 128; var someNodeFlags = 0; var allNodeFlags = flagsToCheck; var someHaveQuestionToken = false; @@ -19502,8 +19915,8 @@ var ts; var errorNode_1 = subsequentNode.name || subsequentNode; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { ts.Debug.assert(node.kind === 143 || node.kind === 142); - ts.Debug.assert((node.flags & 128) !== (subsequentNode.flags & 128)); - var diagnostic = node.flags & 128 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + ts.Debug.assert((node.flags & 64) !== (subsequentNode.flags & 64)); + var diagnostic = node.flags & 64 ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); return; } @@ -19518,7 +19931,7 @@ var ts; error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing); } else { - if (node.flags & 256) { + if (node.flags & 128) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -19529,8 +19942,8 @@ var ts; var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; - for (var _i = 0; _i < declarations.length; _i++) { - var current = declarations[_i]; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); var inAmbientContextOrInterface = node.parent.kind === 215 || node.parent.kind === 155 || inAmbientContext; @@ -19579,7 +19992,7 @@ var ts; }); } if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(lastSeenNonAmbientDeclaration.flags & 256)) { + !(lastSeenNonAmbientDeclaration.flags & 128)) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -19589,8 +20002,8 @@ var ts; var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); if (!bodySignature.hasStringLiterals) { - for (var _a = 0; _a < signatures.length; _a++) { - var signature = signatures[_a]; + for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { + var signature = signatures_3[_a]; if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -19620,9 +20033,9 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var d = _a[_i]; var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 | 1024); - if (effectiveDeclarationFlags & 1) { - if (effectiveDeclarationFlags & 1024) { + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 2 | 512); + if (effectiveDeclarationFlags & 2) { + if (effectiveDeclarationFlags & 512) { defaultExportedDeclarationSpaces |= declarationSpaces; } else { @@ -19758,9 +20171,12 @@ var ts; if (promiseType === unknownType && compilerOptions.isolatedModules) { return unknownType; } - var promiseConstructor = getMergedSymbol(promiseType.symbol); + var promiseConstructor = getNodeLinks(node.type).resolvedSymbol; if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { - error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeToString(promiseType)); + var typeName = promiseConstructor + ? symbolToString(promiseConstructor) + : typeToString(promiseType); + error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } var promiseConstructorType = getTypeOfSymbol(promiseConstructor); @@ -19919,7 +20335,7 @@ var ts; if (isAsync) { promisedType = checkAsyncFunctionReturnType(node); } - checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); } if (produceDiagnostics && !node.type) { if (compilerOptions.noImplicitAny && ts.nodeIsMissing(node.body) && !isPrivateWithinAmbient(node)) { @@ -20022,7 +20438,7 @@ var ts; } } function checkVarDeclaredNamesNotShadowed(node) { - if ((ts.getCombinedNodeFlags(node) & 49152) !== 0 || ts.isParameterDeclaration(node)) { + if ((ts.getCombinedNodeFlags(node) & 24576) !== 0 || ts.isParameterDeclaration(node)) { return; } if (node.kind === 211 && !node.initializer) { @@ -20034,7 +20450,7 @@ var ts; if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 49152) { + if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 24576) { var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 212); var container = varDeclList.parent.kind === 193 && varDeclList.parent.parent ? varDeclList.parent.parent @@ -20161,6 +20577,9 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 194) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } checkSourceElement(node.elseStatement); } function checkDoStatement(node) { @@ -20410,7 +20829,7 @@ var ts; error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } else if (func.kind === 144) { - if (!isTypeAssignableTo(exprType, returnType)) { + if (!checkTypeAssignableTo(exprType, returnType, node.expression)) { error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } @@ -20540,7 +20959,7 @@ var ts; var classDeclaration = type.symbol.valueDeclaration; for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) { var member = _a[_i]; - if (!(member.flags & 128) && ts.hasDynamicName(member)) { + if (!(member.flags & 64) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1); @@ -20616,7 +21035,7 @@ var ts; return getTypeOfSymbol(getSymbolOfNode(node)); } function checkClassDeclaration(node) { - if (!node.name && !(node.flags & 1024)) { + if (!node.name && !(node.flags & 512)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -20666,8 +21085,8 @@ var ts; } var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); if (implementedTypeNodes) { - for (var _b = 0; _b < implementedTypeNodes.length; _b++) { - var typeRefNode = implementedTypeNodes[_b]; + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } @@ -20699,8 +21118,8 @@ var ts; } function checkKindsOfPropertyMemberOverrides(type, baseType) { var baseProperties = getPropertiesOfObjectType(baseType); - for (var _i = 0; _i < baseProperties.length; _i++) { - var baseProperty = baseProperties[_i]; + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; var base = getTargetSymbol(baseProperty); if (base.flags & 134217728) { continue; @@ -20711,7 +21130,7 @@ var ts; if (derived) { if (derived === base) { var derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); - if (baseDeclarationFlags & 256 && (!derivedClassDecl || !(derivedClassDecl.flags & 256))) { + if (baseDeclarationFlags & 128 && (!derivedClassDecl || !(derivedClassDecl.flags & 128))) { if (derivedClassDecl.kind === 186) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -20722,10 +21141,10 @@ var ts; } else { var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); - if ((baseDeclarationFlags & 32) || (derivedDeclarationFlags & 32)) { + if ((baseDeclarationFlags & 16) || (derivedDeclarationFlags & 16)) { continue; } - if ((baseDeclarationFlags & 128) !== (derivedDeclarationFlags & 128)) { + if ((baseDeclarationFlags & 64) !== (derivedDeclarationFlags & 64)) { continue; } if ((base.flags & derived.flags & 8192) || ((base.flags & 98308) && (derived.flags & 98308))) { @@ -20791,11 +21210,11 @@ var ts; var seen = {}; ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; - for (var _i = 0; _i < baseTypes.length; _i++) { - var base = baseTypes[_i]; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0; _a < properties.length; _a++) { - var prop = properties[_a]; + for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { + var prop = properties_4[_a]; if (!ts.hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } @@ -21064,8 +21483,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; if ((declaration.kind === 214 || (declaration.kind === 213 && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { @@ -21193,7 +21612,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -21220,7 +21639,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 1) { + if (node.flags & 2) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -21248,7 +21667,7 @@ var ts; if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) { return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -21287,7 +21706,7 @@ var ts; error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69) { @@ -21672,7 +22091,7 @@ var ts; } case 214: case 215: - if (!(memberFlags & 128)) { + if (!(memberFlags & 64)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056); } break; @@ -21934,7 +22353,7 @@ var ts; } function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 128 + return node.flags & 64 ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -22220,7 +22639,7 @@ var ts; } function initializeTypeChecker() { ts.forEach(host.getSourceFiles(), function (file) { - ts.bindSourceFile(file); + ts.bindSourceFile(file, compilerOptions); }); ts.forEach(host.getSourceFiles(), function (file) { if (!ts.isExternalModule(file)) { @@ -22364,19 +22783,19 @@ var ts; text = "private"; lastPrivate = modifier; } - if (flags & 112) { + if (flags & 56) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (flags & 128) { + else if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } - else if (flags & 512) { + else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } else if (node.parent.kind === 219 || node.parent.kind === 248) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); } - else if (flags & 256) { + else if (flags & 128) { if (modifier.kind === 110) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } @@ -22387,10 +22806,10 @@ var ts; flags |= ts.modifierToFlag(modifier.kind); break; case 113: - if (flags & 128) { + if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } - else if (flags & 512) { + else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } else if (node.parent.kind === 219 || node.parent.kind === 248) { @@ -22399,23 +22818,23 @@ var ts; else if (node.kind === 138) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } - else if (flags & 256) { + else if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - flags |= 128; + flags |= 64; lastStatic = modifier; break; case 82: - if (flags & 1) { + if (flags & 2) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } - else if (flags & 2) { + else if (flags & 4) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } - else if (flags & 256) { + else if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); } - else if (flags & 512) { + else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } else if (node.parent.kind === 214) { @@ -22424,13 +22843,13 @@ var ts; else if (node.kind === 138) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } - flags |= 1; + flags |= 2; break; case 122: - if (flags & 2) { + if (flags & 4) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } - else if (flags & 512) { + else if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } else if (node.parent.kind === 214) { @@ -22442,69 +22861,69 @@ var ts; else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 219) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - flags |= 2; + flags |= 4; lastDeclare = modifier; break; case 115: - if (flags & 256) { + if (flags & 128) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } if (node.kind !== 214) { if (node.kind !== 143) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); } - if (!(node.parent.kind === 214 && node.parent.flags & 256)) { + if (!(node.parent.kind === 214 && node.parent.flags & 128)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } - if (flags & 128) { + if (flags & 64) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - if (flags & 32) { + if (flags & 16) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); } } - flags |= 256; + flags |= 128; break; case 118: - if (flags & 512) { + if (flags & 256) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 2 || ts.isInAmbientContext(node.parent)) { + else if (flags & 4 || ts.isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } else if (node.kind === 138) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } - flags |= 512; + flags |= 256; lastAsync = modifier; break; } } if (node.kind === 144) { - if (flags & 128) { + if (flags & 64) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } - if (flags & 256) { + if (flags & 128) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } - else if (flags & 64) { + else if (flags & 32) { return grammarErrorOnNode(lastProtected, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "protected"); } - else if (flags & 32) { + else if (flags & 16) { return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); } - else if (flags & 512) { + else if (flags & 256) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } return; } - else if ((node.kind === 222 || node.kind === 221) && flags & 2) { + else if ((node.kind === 222 || node.kind === 221) && flags & 4) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 138 && (flags & 112) && ts.isBindingPattern(node.name)) { + else if (node.kind === 138 && (flags & 56) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); } - if (flags & 512) { + if (flags & 256) { return checkGrammarAsyncModifier(node, lastAsync); } } @@ -22604,7 +23023,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 2035) { + if (parameter.flags & 1022) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -22624,7 +23043,7 @@ var ts; } } function checkGrammarForIndexSignatureModifier(node) { - if (node.flags & 2035) { + if (node.flags & 1022) { grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_not_permitted_on_index_signature_members); } } @@ -22646,8 +23065,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0; _i < args.length; _i++) { - var arg = args[_i]; + for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { + var arg = args_1[_i]; if (arg.kind === 187) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -22887,7 +23306,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); } - else if (parameter.flags & 2035) { + else if (parameter.flags & 1022) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } else if (parameter.questionToken) { @@ -23021,8 +23440,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0; _i < elements.length; _i++) { - var element = elements[_i]; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; if (element.kind !== 187) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -23141,8 +23560,8 @@ var ts; node.kind === 221 || node.kind === 228 || node.kind === 227 || - (node.flags & 2) || - (node.flags & (1 | 1024))) { + (node.flags & 4) || + (node.flags & (2 | 512))) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -23180,7 +23599,7 @@ var ts; } } function checkGrammarNumericLiteral(node) { - if (node.flags & 65536 && languageVersion >= 1) { + if (node.flags & 32768 && languageVersion >= 1) { return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } @@ -23227,7 +23646,7 @@ var ts; var addedGlobalFileReference = false; ts.forEach(root.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); - if (referencedFile && ((referencedFile.flags & 8192) || + if (referencedFile && ((referencedFile.flags & 4096) || ts.shouldEmitToOwnFile(referencedFile, compilerOptions) || !addedGlobalFileReference)) { writeReferencePath(referencedFile); @@ -23405,15 +23824,15 @@ var ts; } } function emitLines(nodes) { - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; emit(node); } } function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { var currentWriterPos = writer.getTextPos(); - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; if (!canEmitFn || canEmitFn(node)) { if (currentWriterPos !== writer.getTextPos()) { write(separator); @@ -23555,6 +23974,7 @@ var ts; function emitSourceFile(node) { currentSourceFile = node; enclosingDeclaration = node; + ts.emitDetachedComments(currentSourceFile, writer, ts.writeCommentRange, node, newLine, true); emitLines(node.statements); } function getExportDefaultTempVariableName() { @@ -23661,10 +24081,10 @@ var ts; } function emitModuleElementDeclarationFlags(node) { if (node.parent === currentSourceFile) { - if (node.flags & 1) { + if (node.flags & 2) { write("export "); } - if (node.flags & 1024) { + if (node.flags & 512) { write("default "); } else if (node.kind !== 215) { @@ -23673,22 +24093,22 @@ var ts; } } function emitClassMemberDeclarationFlags(node) { - if (node.flags & 32) { + if (node.flags & 16) { write("private "); } - else if (node.flags & 64) { + else if (node.flags & 32) { write("protected "); } - if (node.flags & 128) { + if (node.flags & 64) { write("static "); } - if (node.flags & 256) { + if (node.flags & 128) { write("abstract "); } } function writeImportEqualsDeclaration(node) { emitJsDocComments(node); - if (node.flags & 1) { + if (node.flags & 2) { write("export "); } write("import "); @@ -23723,11 +24143,11 @@ var ts; } } function writeImportDeclaration(node) { - if (!node.importClause && !(node.flags & 1)) { + if (!node.importClause && !(node.flags & 2)) { return; } emitJsDocComments(node); - if (node.flags & 1) { + if (node.flags & 2) { write("export "); } write("import "); @@ -23789,7 +24209,7 @@ var ts; function writeModuleDeclaration(node) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 131072) { + if (node.flags & 65536) { write("namespace "); } else { @@ -23861,7 +24281,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 143 && (node.parent.flags & 32); + return node.parent.kind === 143 && (node.parent.flags & 16); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -23903,7 +24323,7 @@ var ts; break; case 143: case 142: - if (node.parent.flags & 128) { + if (node.parent.flags & 64) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } else if (node.parent.parent.kind === 214) { @@ -23966,7 +24386,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 112) { + if (param.flags & 56) { emitPropertyDeclaration(param); } }); @@ -23974,7 +24394,7 @@ var ts; } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 256) { + if (node.flags & 128) { write("abstract "); } write("class "); @@ -24038,7 +24458,7 @@ var ts; if ((node.kind === 141 || node.kind === 140) && node.parent.kind === 155) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 32)) { + else if (!(node.flags & 16)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } @@ -24052,7 +24472,7 @@ var ts; ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; } else if (node.kind === 141 || node.kind === 140) { - if (node.flags & 128) { + if (node.flags & 64) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -24147,7 +24567,7 @@ var ts; emitJsDocComments(accessors.setAccessor); emitClassMemberDeclarationFlags(node); writeTextOfNode(currentSourceFile, node.name); - if (!(node.flags & 32)) { + if (!(node.flags & 16)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { @@ -24174,7 +24594,7 @@ var ts; function getAccessorDeclarationTypeVisibilityError(symbolAccesibilityResult) { var diagnosticMessage; if (accessorWithTypeAnnotation.kind === 146) { - if (accessorWithTypeAnnotation.parent.flags & 128) { + if (accessorWithTypeAnnotation.parent.flags & 64) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; @@ -24191,7 +24611,7 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 128) { + if (accessorWithTypeAnnotation.flags & 64) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -24272,7 +24692,7 @@ var ts; emitType(node.type); } } - else if (node.kind !== 144 && !(node.flags & 32)) { + else if (node.kind !== 144 && !(node.flags & 16)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -24300,7 +24720,7 @@ var ts; break; case 143: case 142: - if (node.flags & 128) { + if (node.flags & 64) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -24357,7 +24777,7 @@ var ts; node.parent.parent.kind === 155) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 32)) { + else if (!(node.parent.flags & 16)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { @@ -24386,7 +24806,7 @@ var ts; ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; case 143: case 142: - if (node.parent.flags & 128) { + if (node.parent.flags & 64) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -24502,7 +24922,7 @@ var ts; } } function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 8192 + var declFileName = referencedFile.flags & 4096 ? referencedFile.fileName : ts.shouldEmitToOwnFile(referencedFile, compilerOptions) ? ts.getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") @@ -24835,16 +25255,8 @@ var ts; diagnostics: diagnostics, sourceMaps: sourceMapDataList }; - function isNodeDescendentOf(node, ancestor) { - while (node) { - if (node === ancestor) - return true; - node = node.parent; - } - return false; - } function isUniqueLocalName(name, container) { - for (var node = container; isNodeDescendentOf(node, container); node = node.nextContainer) { + for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { if (node.locals && ts.hasProperty(node.locals, name)) { if (node.locals[name].flags & (107455 | 1048576 | 8388608)) { return false; @@ -26137,7 +26549,7 @@ var ts; write("]"); } else { - emitListWithSpread(elements, true, (node.flags & 2048) !== 0, elements.hasTrailingComma, true); + emitListWithSpread(elements, true, (node.flags & 1024) !== 0, elements.hasTrailingComma, true); } } function emitObjectLiteralBody(node, numElements) { @@ -26152,7 +26564,7 @@ var ts; emitLinePreservingList(node, properties, languageVersion >= 1, true); } else { - var multiLine = (node.flags & 2048) !== 0; + var multiLine = (node.flags & 1024) !== 0; if (!multiLine) { write(" "); } @@ -26171,7 +26583,7 @@ var ts; write("}"); } function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = (node.flags & 2048) !== 0; + var multiLine = (node.flags & 1024) !== 0; var properties = node.properties; write("("); if (multiLine) { @@ -26689,7 +27101,7 @@ var ts; var current = node; while (current) { if (current.kind === 248) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 1) !== 0); + return !isExported || ((ts.getCombinedNodeFlags(node) & 2) !== 0); } else if (ts.isFunctionLike(current) || current.kind === 219) { return false; @@ -26907,7 +27319,7 @@ var ts; if (shouldHoistVariable(decl, true)) { return false; } - if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 49152) === 0) { + if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 24576) === 0) { for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { var varDecl = _b[_a]; hoistVariableDeclarationFromLoop(convertedLoopState, varDecl); @@ -26989,7 +27401,7 @@ var ts; break; } var loopParameters; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 49152)) { + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 24576)) { loopParameters = []; for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { var varDeclaration = _b[_a]; @@ -27246,22 +27658,22 @@ var ts; var endPos = emitToken(86, node.pos); write(" "); endPos = emitToken(17, endPos); - var rhsIsIdentifier = node.expression.kind === 69; var counter = createTempVariable(268435456); - var rhsReference = rhsIsIdentifier ? node.expression : createTempVariable(0); + var rhsReference = ts.createSynthesizedNode(69); + rhsReference.text = node.expression.kind === 69 ? + makeUniqueName(node.expression.text) : + makeTempVariableName(0); emitStart(node.expression); write("var "); emitNodeWithoutSourceMap(counter); write(" = 0"); emitEnd(node.expression); - if (!rhsIsIdentifier) { - write(", "); - emitStart(node.expression); - emitNodeWithoutSourceMap(rhsReference); - write(" = "); - emitNodeWithoutSourceMap(node.expression); - emitEnd(node.expression); - } + write(", "); + emitStart(node.expression); + emitNodeWithoutSourceMap(rhsReference); + write(" = "); + emitNodeWithoutSourceMap(node.expression); + emitEnd(node.expression); write("; "); emitStart(node.initializer); emitNodeWithoutSourceMap(counter); @@ -27496,7 +27908,7 @@ var ts; } function emitModuleMemberName(node) { emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 1) { + if (ts.getCombinedNodeFlags(node) & 2) { var container = getContainingModule(node); if (container) { write(getGeneratedNameForNode(container)); @@ -27518,7 +27930,7 @@ var ts; } function emitEs6ExportDefaultCompat(node) { if (node.parent.kind === 248) { - ts.Debug.assert(!!(node.flags & 1024) || node.kind === 227); + ts.Debug.assert(!!(node.flags & 512) || node.kind === 227); if (modulekind === 1 || modulekind === 2 || modulekind === 3) { if (!currentSourceFile.symbol.exports["___esModule"]) { if (languageVersion === 1) { @@ -27534,12 +27946,12 @@ var ts; } } function emitExportMemberAssignment(node) { - if (node.flags & 1) { + if (node.flags & 2) { writeLine(); emitStart(node); if (modulekind === 4 && node.parent === currentSourceFile) { write(exportFunctionForFile + "(\""); - if (node.flags & 1024) { + if (node.flags & 512) { write("default"); } else { @@ -27550,7 +27962,7 @@ var ts; write(")"); } else { - if (node.flags & 1024) { + if (node.flags & 512) { emitEs6ExportDefaultCompat(node); if (languageVersion === 0) { write("exports[\"default\"]"); @@ -27638,7 +28050,7 @@ var ts; var emitCount = 0; var canDefineTempVariablesInPlace = false; if (root.kind === 211) { - var isExported = ts.getCombinedNodeFlags(root) & 1; + var isExported = ts.getCombinedNodeFlags(root) & 2; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } @@ -27704,8 +28116,8 @@ var ts; if (properties.length !== 1) { value = ensureIdentifier(value, true); } - for (var _a = 0; _a < properties.length; _a++) { - var p = properties[_a]; + for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { + var p = properties_5[_a]; if (p.kind === 245 || p.kind === 246) { var propName = p.name; var target_1 = p.kind === 246 ? p : p.initializer || propName; @@ -27824,7 +28236,7 @@ var ts; var initializer = node.initializer; if (!initializer && languageVersion < 2) { var isLetDefinedInLoop = (resolver.getNodeCheckFlags(node) & 16384) && - (getCombinedFlagsForIdentifier(node.name) & 16384); + (getCombinedFlagsForIdentifier(node.name) & 8192); if (isLetDefinedInLoop && node.parent.parent.kind !== 200 && node.parent.parent.kind !== 201) { @@ -27863,13 +28275,13 @@ var ts; return ts.getCombinedNodeFlags(node.parent); } function isES6ExportedDeclaration(node) { - return !!(node.flags & 1) && + return !!(node.flags & 2) && modulekind === 5 && node.parent.kind === 248; } function emitVariableStatement(node) { var startIsEmitted = false; - if (node.flags & 1) { + if (node.flags & 2) { if (isES6ExportedDeclaration(node)) { write("export "); startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); @@ -27893,7 +28305,7 @@ var ts; } } function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { - if (!(node.flags & 1)) { + if (!(node.flags & 2)) { return true; } if (isES6ExportedDeclaration(node)) { @@ -28050,7 +28462,7 @@ var ts; if (!shouldEmitAsArrowFunction(node)) { if (isES6ExportedDeclaration(node)) { write("export "); - if (node.flags & 1024) { + if (node.flags & 512) { write("default "); } } @@ -28189,7 +28601,7 @@ var ts; emitRestParameter(node); } function emitExpressionFunctionBody(node, body) { - if (languageVersion < 2 || node.flags & 512) { + if (languageVersion < 2 || node.flags & 256) { emitDownLevelExpressionFunctionBody(node, body); return; } @@ -28205,7 +28617,7 @@ var ts; scopeEmitStart(node); increaseIndent(); var outPos = writer.getTextPos(); - emitDetachedComments(node.body); + emitDetachedCommentsAndUpdateCommentsInfo(node.body); emitFunctionBodyPreamble(node); var preambleEmitted = writer.getTextPos() !== outPos; decreaseIndent(); @@ -28241,7 +28653,7 @@ var ts; scopeEmitStart(node); var initialTextPos = writer.getTextPos(); increaseIndent(); - emitDetachedComments(body.statements); + emitDetachedCommentsAndUpdateCommentsInfo(body.statements); var startIndex = emitDirectivePrologues(body.statements, true); emitFunctionBodyPreamble(node); decreaseIndent(); @@ -28283,7 +28695,7 @@ var ts; } function emitParameterPropertyAssignments(node) { ts.forEach(node.parameters, function (param) { - if (param.flags & 112) { + if (param.flags & 56) { writeLine(); emitStart(param); emitStart(param.name); @@ -28315,15 +28727,15 @@ var ts; var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 141 && isStatic === ((member.flags & 128) !== 0) && member.initializer) { + if (member.kind === 141 && isStatic === ((member.flags & 64) !== 0) && member.initializer) { properties.push(member); } } return properties; } function emitPropertyDeclarations(node, properties) { - for (var _a = 0; _a < properties.length; _a++) { - var property = properties[_a]; + for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { + var property = properties_6[_a]; emitPropertyDeclaration(node, property); } } @@ -28336,7 +28748,7 @@ var ts; emit(receiver); } else { - if (property.flags & 128) { + if (property.flags & 64) { emitDeclarationName(node); } else { @@ -28435,7 +28847,7 @@ var ts; writeLine(); emitLeadingComments(member); emitStart(member); - if (member.flags & 128) { + if (member.flags & 64) { write("static "); } if (member.kind === 145) { @@ -28480,7 +28892,7 @@ var ts; if (member.kind === 144 && !member.body) { emitCommentsOnNotEmittedNode(member); } - if (member.kind === 141 && member.initializer && (member.flags & 128) === 0) { + if (member.kind === 141 && member.initializer && (member.flags & 64) === 0) { hasInstancePropertyWithInitializer = true; } }); @@ -28517,7 +28929,7 @@ var ts; increaseIndent(); if (ctor) { startIndex = emitDirectivePrologues(ctor.body.statements, true); - emitDetachedComments(ctor.body.statements); + emitDetachedCommentsAndUpdateCommentsInfo(ctor.body.statements); } emitCaptureThisForNodeIfNecessary(node); var superCall; @@ -28588,7 +29000,7 @@ var ts; var thisNodeIsDecorated = ts.nodeIsDecorated(node); if (node.kind === 214) { if (thisNodeIsDecorated) { - if (isES6ExportedDeclaration(node) && !(node.flags & 1024)) { + if (isES6ExportedDeclaration(node) && !(node.flags & 512)) { write("export "); } write("let "); @@ -28597,7 +29009,7 @@ var ts; } else if (isES6ExportedDeclaration(node)) { write("export "); - if (node.flags & 1024) { + if (node.flags & 512) { write("default "); } } @@ -28613,7 +29025,7 @@ var ts; write(" = "); } write("class"); - if ((node.name || (node.flags & 1024 && staticProperties.length > 0)) && !thisNodeIsDecorated) { + if ((node.name || (node.flags & 512 && staticProperties.length > 0)) && !thisNodeIsDecorated) { write(" "); emitDeclarationName(node); } @@ -28636,8 +29048,8 @@ var ts; write(";"); } if (isClassExpressionWithStaticProperties) { - for (var _a = 0; _a < staticProperties.length; _a++) { - var property = staticProperties[_a]; + for (var _a = 0, staticProperties_1 = staticProperties; _a < staticProperties_1.length; _a++) { + var property = staticProperties_1[_a]; write(","); writeLine(); emitPropertyDeclaration(node, property, tempVariable, true); @@ -28653,7 +29065,7 @@ var ts; emitPropertyDeclarations(node, staticProperties); emitDecoratorsOfClass(node); } - if (!isES6ExportedDeclaration(node) && (node.flags & 1)) { + if (!isES6ExportedDeclaration(node) && (node.flags & 2)) { writeLine(); emitStart(node); emitModuleMemberName(node); @@ -28662,7 +29074,7 @@ var ts; emitEnd(node); write(";"); } - else if (isES6ExportedDeclaration(node) && (node.flags & 1024) && thisNodeIsDecorated) { + else if (isES6ExportedDeclaration(node) && (node.flags & 512) && thisNodeIsDecorated) { writeLine(); write("export default "); emitDeclarationName(node); @@ -28742,13 +29154,13 @@ var ts; } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); - if (!(member.flags & 128)) { + if (!(member.flags & 64)) { write(".prototype"); } } function emitDecoratorsOfClass(node) { emitDecoratorsOfMembers(node, 0); - emitDecoratorsOfMembers(node, 128); + emitDecoratorsOfMembers(node, 64); emitDecoratorsOfConstructor(node); } function emitDecoratorsOfConstructor(node) { @@ -28783,7 +29195,7 @@ var ts; function emitDecoratorsOfMembers(node, staticFlag) { for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if ((member.flags & 128) !== staticFlag) { + if ((member.flags & 64) !== staticFlag) { continue; } if (!ts.nodeCanBeDecorated(member)) { @@ -29110,7 +29522,7 @@ var ts; return; } if (!shouldHoistDeclarationInSystemJsModule(node)) { - if (!(node.flags & 1) || isES6ExportedDeclaration(node)) { + if (!(node.flags & 2) || isES6ExportedDeclaration(node)) { emitStart(node); if (isES6ExportedDeclaration(node)) { write("export "); @@ -29141,7 +29553,7 @@ var ts; emitModuleMemberName(node); write(" = {}));"); emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 1 && !shouldHoistDeclarationInSystemJsModule(node)) { + if (!isES6ExportedDeclaration(node) && node.flags & 2 && !shouldHoistDeclarationInSystemJsModule(node)) { writeLine(); emitStart(node); write("var "); @@ -29152,7 +29564,7 @@ var ts; write(";"); } if (modulekind !== 5 && node.parent === currentSourceFile) { - if (modulekind === 4 && (node.flags & 1)) { + if (modulekind === 4 && (node.flags & 2)) { writeLine(); write(exportFunctionForFile + "(\""); emitDeclarationName(node); @@ -29254,7 +29666,7 @@ var ts; scopeEmitEnd(); } write(")("); - if ((node.flags & 1) && !isES6ExportedDeclaration(node)) { + if ((node.flags & 2) && !isES6ExportedDeclaration(node)) { emit(node.name); write(" = "); } @@ -29264,7 +29676,7 @@ var ts; write(" = {}));"); emitEnd(node); if (!isES6ExportedDeclaration(node) && node.name.kind === 69 && node.parent === currentSourceFile) { - if (modulekind === 4 && (node.flags & 1)) { + if (modulekind === 4 && (node.flags & 2)) { writeLine(); write(exportFunctionForFile + "(\""); emitDeclarationName(node); @@ -29362,7 +29774,7 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 221 && (node.flags & 1) !== 0; + var isExportedImport = node.kind === 221 && (node.flags & 2) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); if (modulekind !== 2) { emitLeadingComments(node); @@ -29428,7 +29840,7 @@ var ts; write("export "); write("var "); } - else if (!(node.flags & 1)) { + else if (!(node.flags & 2)) { write("var "); } } @@ -29516,8 +29928,8 @@ var ts; function emitExportOrImportSpecifierList(specifiers, shouldEmit) { ts.Debug.assert(modulekind === 5); var needsComma = false; - for (var _a = 0; _a < specifiers.length; _a++) { - var specifier = specifiers[_a]; + for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { + var specifier = specifiers_1[_a]; if (shouldEmit(specifier)) { if (needsComma) { write(", "); @@ -29651,8 +30063,8 @@ var ts; } writeLine(); var started = false; - for (var _a = 0; _a < externalImports.length; _a++) { - var importNode = externalImports[_a]; + for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { + var importNode = externalImports_1[_a]; var skipNode = importNode.kind === 228 || (importNode.kind === 222 && !importNode.importClause); if (skipNode) { @@ -29677,8 +30089,8 @@ var ts; } if (!exportedDeclarations && ts.isEmpty(exportSpecifiers)) { var hasExportDeclarationWithExportClause = false; - for (var _a = 0; _a < externalImports.length; _a++) { - var externalImport = externalImports[_a]; + for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { + var externalImport = externalImports_2[_a]; if (externalImport.kind === 228 && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; @@ -29706,8 +30118,8 @@ var ts; } } } - for (var _d = 0; _d < externalImports.length; _d++) { - var externalImport = externalImports[_d]; + for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { + var externalImport = externalImports_3[_d]; if (externalImport.kind !== 228) { continue; } @@ -29751,7 +30163,7 @@ var ts; return exportStarFunction; } function writeExportedName(node) { - if (node.kind !== 69 && node.flags & 1024) { + if (node.kind !== 69 && node.flags & 512) { return; } if (started) { @@ -29804,7 +30216,7 @@ var ts; emit(local); } var flags = ts.getCombinedNodeFlags(local.kind === 69 ? local.parent : local); - if (flags & 1) { + if (flags & 2) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -29814,11 +30226,11 @@ var ts; write(";"); } if (hoistedFunctionDeclarations) { - for (var _a = 0; _a < hoistedFunctionDeclarations.length; _a++) { - var f = hoistedFunctionDeclarations[_a]; + for (var _a = 0, hoistedFunctionDeclarations_1 = hoistedFunctionDeclarations; _a < hoistedFunctionDeclarations_1.length; _a++) { + var f = hoistedFunctionDeclarations_1[_a]; writeLine(); emit(f); - if (f.flags & 1) { + if (f.flags & 2) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -29828,7 +30240,7 @@ var ts; } return exportedDeclarations; function visit(node) { - if (node.flags & 2) { + if (node.flags & 4) { return; } if (node.kind === 213) { @@ -29898,7 +30310,7 @@ var ts; if (checkIfSourceFileLevelDecl && !shouldHoistDeclarationInSystemJsModule(node)) { return false; } - return (ts.getCombinedNodeFlags(node) & 49152) === 0 || + return (ts.getCombinedNodeFlags(node) & 24576) === 0 || ts.getEnclosingBlockScopeContainer(node).kind === 248; } function isCurrentFileSystemExternalModule() { @@ -29933,8 +30345,8 @@ var ts; var parameterName = makeUniqueName(ts.forEach(group, getLocalNameForExternalImport) || ""); write("function (" + parameterName + ") {"); increaseIndent(); - for (var _a = 0; _a < group.length; _a++) { - var entry = group[_a]; + for (var _a = 0, group_1 = group; _a < group_1.length; _a++) { + var entry = group_1[_a]; var importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { case 222: @@ -30068,8 +30480,8 @@ var ts; unaliasedModuleNames.push("\"" + amdDependency.path + "\""); } } - for (var _c = 0; _c < externalImports.length; _c++) { - var importNode = externalImports[_c]; + for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { + var importNode = externalImports_4[_c]; var externalModuleName = getExternalModuleNameText(importNode); var importAliasName = getLocalNameForExternalImport(importNode); if (includeNonAmdDependencies && importAliasName) { @@ -30322,7 +30734,7 @@ var ts; function emitSourceFileNode(node) { writeLine(); emitShebang(); - emitDetachedComments(node); + emitDetachedCommentsAndUpdateCommentsInfo(node); if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1]; emitModule(node); @@ -30345,7 +30757,7 @@ var ts; } function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { if (node) { - if (node.flags & 2) { + if (node.flags & 4) { return emitCommentsOnNotEmittedNode(node); } if (isSpecializedCommentHandling(node)) { @@ -30578,10 +30990,6 @@ var ts; } return leadingComments; } - function isPinnedComments(comment) { - return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 && - currentSourceFile.text.charCodeAt(comment.pos + 2) === 33; - } function isTripleSlashComment(comment) { if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 && comment.pos + 2 < comment.end && @@ -30662,44 +31070,14 @@ var ts; ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments); ts.emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); } - function emitDetachedComments(node) { - var leadingComments; - if (compilerOptions.removeComments) { - if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComments); + function emitDetachedCommentsAndUpdateCommentsInfo(node) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); } - } - else { - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); - } - if (leadingComments) { - var detachedComments = []; - var lastComment; - ts.forEach(leadingComments, function (comment) { - if (lastComment) { - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, lastComment.end); - var commentLine = ts.getLineOfLocalPosition(currentSourceFile, comment.pos); - if (commentLine >= lastCommentLine + 2) { - return detachedComments; - } - } - detachedComments.push(comment); - lastComment = comment; - }); - if (detachedComments.length) { - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); - var nodeLine = ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); - if (nodeLine >= lastCommentLine + 2) { - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - ts.emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); - var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; } } } @@ -31002,7 +31380,7 @@ var ts; var resolveModuleNamesWorker = host.resolveModuleNames ? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }) : (function (moduleNames, containingFile) { return ts.map(moduleNames, function (moduleName) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }); }); - var filesByName = ts.createFileMap(getCanonicalFileName); + var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (oldProgram) { var oldOptions = oldProgram.getCompilerOptions(); @@ -31050,8 +31428,8 @@ var ts; if (!classifiableNames) { getTypeChecker(); classifiableNames = {}; - for (var _i = 0; _i < files.length; _i++) { - var sourceFile = files[_i]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var sourceFile = files_3[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -31067,7 +31445,7 @@ var ts; return false; } var newSourceFiles = []; - var normalizedAbsoluteFileNames = []; + var filePaths = []; var modifiedSourceFiles = []; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; @@ -31075,8 +31453,8 @@ var ts; if (!newSourceFile) { return false; } - var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); - normalizedAbsoluteFileNames.push(normalizedAbsolutePath); + newSourceFile.path = oldSourceFile.path; + filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { return false; @@ -31090,7 +31468,7 @@ var ts; } if (resolveModuleNamesWorker) { var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); - var resolutions = resolveModuleNamesWorker(moduleNames, normalizedAbsolutePath); + var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); for (var i = 0; i < moduleNames.length; ++i) { var newResolution = resolutions[i]; var oldResolution = ts.getResolvedModule(oldSourceFile, moduleNames[i]); @@ -31113,12 +31491,12 @@ var ts; newSourceFiles.push(newSourceFile); } for (var i = 0, len = newSourceFiles.length; i < len; ++i) { - filesByName.set(normalizedAbsoluteFileNames[i], newSourceFiles[i]); + filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _b = 0; _b < modifiedSourceFiles.length; _b++) { - var modifiedFile = modifiedSourceFiles[_b]; + for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { + var modifiedFile = modifiedSourceFiles_1[_b]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); } oldProgram.structureIsReused = true; @@ -31157,7 +31535,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - return filesByName.get(ts.getNormalizedAbsolutePath(fileName, currentDirectory)); + return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); } function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { if (sourceFile) { @@ -31266,7 +31644,7 @@ var ts; } break; case 218: - if (node.name.kind === 9 && (node.flags & 2 || ts.isDeclarationFile(file))) { + if (node.name.kind === 9 && (node.flags & 4 || ts.isDeclarationFile(file))) { ts.forEachChild(node.body, function (node) { collect(node, false); }); @@ -31283,7 +31661,7 @@ var ts; diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"]; } - else if (!findSourceFile(fileName, ts.getNormalizedAbsolutePath(fileName, currentDirectory), isDefaultLib, refFile, refPos, refEnd)) { + else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } @@ -31293,13 +31671,13 @@ var ts; } } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.getNormalizedAbsolutePath(fileName, currentDirectory), isDefaultLib, refFile, refPos, refEnd); + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.getNormalizedAbsolutePath(fileName + extension, currentDirectory), isDefaultLib, refFile, refPos, refEnd); })) { + else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -31341,6 +31719,7 @@ var ts; }); filesByName.set(normalizedAbsolutePath, file); if (file) { + file.path = normalizedAbsolutePath; if (host.useCaseSensitiveFileNames()) { var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath); if (existingFile) { @@ -31385,11 +31764,7 @@ var ts; var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); if (resolution && !options.noResolve) { - var absoluteImportPath = ts.isRootedDiskPath(resolution.resolvedFileName) - ? resolution.resolvedFileName - : ts.getNormalizedAbsolutePath(resolution.resolvedFileName, currentDirectory); - var relativePath = ts.getRelativePathToDirectoryOrUrl(currentDirectory, absoluteImportPath, currentDirectory, getCanonicalFileName, false); - var importedFile = findSourceFile(relativePath, absoluteImportPath, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { if (!ts.isExternalModule(importedFile)) { var start_2 = ts.getTokenPosOfNode(file.imports[i], file); @@ -31440,8 +31815,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0; _i < sourceFiles.length; _i++) { - var sourceFile = sourceFiles[_i]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -31557,7 +31932,7 @@ var ts; var BreakpointResolver; (function (BreakpointResolver) { function spanInSourceFileAtLocation(sourceFile, position) { - if (sourceFile.flags & 8192) { + if (sourceFile.flags & 4096) { return undefined; } var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); @@ -31732,7 +32107,7 @@ var ts; : isDeclarationOfForStatement ? variableDeclaration.parent.parent.initializer.declarations : undefined; - if (variableDeclaration.initializer || (variableDeclaration.flags & 1)) { + if (variableDeclaration.initializer || (variableDeclaration.flags & 2)) { if (declarations && declarations[0] === variableDeclaration) { if (isParentVariableStatement) { return textSpan(variableDeclaration.parent, variableDeclaration); @@ -31753,7 +32128,7 @@ var ts; } function canHaveSpanInParameterDeclaration(parameter) { return !!parameter.initializer || parameter.dotDotDotToken !== undefined || - !!(parameter.flags & 16) || !!(parameter.flags & 32); + !!(parameter.flags & 8) || !!(parameter.flags & 16); } function spanInParameterDeclaration(parameter) { if (canHaveSpanInParameterDeclaration(parameter)) { @@ -31771,7 +32146,7 @@ var ts; } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return !!(functionDeclaration.flags & 1) || + return !!(functionDeclaration.flags & 2) || (functionDeclaration.parent.kind === 214 && functionDeclaration.kind !== 144); } function spanInFunctionDeclaration(functionDeclaration) { @@ -31853,7 +32228,6 @@ var ts; } case 244: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - ; case 220: var caseBlock = node.parent; var lastClause = ts.lastOrUndefined(caseBlock.clauses); @@ -31888,7 +32262,6 @@ var ts; default: return spanInNode(node.parent); } - return spanInNode(node.parent); } function spanInColonToken(node) { if (ts.isFunctionLike(node.parent) || node.parent.kind === 245) { @@ -31949,8 +32322,8 @@ var ts; var lastSingleLineCommentEnd = -1; var isFirstSingleLineComment = true; var singleLineCommentCount = 0; - for (var _i = 0; _i < comments.length; _i++) { - var currentComment = comments[_i]; + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var currentComment = comments_2[_i]; if (currentComment.kind === 2) { if (isFirstSingleLineComment) { firstSingleLineCommentStart = currentComment.pos; @@ -32071,6 +32444,7 @@ var ts; function getNavigateToItems(program, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; + var baseSensitivity = { sensitivity: "base" }; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); @@ -32081,8 +32455,8 @@ var ts; if (!matches) { continue; } - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; if (patternMatcher.patternContainsDots) { var containers = getContainers(declaration); if (!containers) { @@ -32108,8 +32482,8 @@ var ts; return items; function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); - for (var _i = 0; _i < matches.length; _i++) { - var match = matches[_i]; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; if (!match.isCaseSensitive) { return false; } @@ -32177,8 +32551,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0; _i < matches.length; _i++) { - var match = matches[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -32186,7 +32560,6 @@ var ts; } return bestMatchKind; } - var baseSensitivity = { sensitivity: "base" }; function compareNavigateToItems(i1, i2) { return i1.matchKind - i2.matchKind || i1.name.localeCompare(i2.name, undefined, baseSensitivity) || @@ -32314,8 +32687,8 @@ var ts; } function addTopLevelNodes(nodes, topLevelNodes) { nodes = sortNodes(nodes); - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; switch (node.kind) { case 214: case 217: @@ -32353,8 +32726,8 @@ var ts; function getItemsWorker(nodes, createItem) { var items = []; var keyToItem = {}; - for (var _i = 0; _i < nodes.length; _i++) { - var child = nodes[_i]; + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var child = nodes_5[_i]; var item = createItem(child); if (item !== undefined) { if (item.text.length > 0) { @@ -32397,7 +32770,7 @@ var ts; if (ts.isBindingPattern(node.name)) { break; } - if ((node.flags & 2035) === 0) { + if ((node.flags & 1022) === 0) { return undefined; } return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); @@ -32661,8 +33034,8 @@ var ts; if (isLowercase) { if (index > 0) { var wordSpans = getWordSpans(candidate); - for (var _i = 0; _i < wordSpans.length; _i++) { - var span = wordSpans[_i]; + for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { + var span = wordSpans_1[_i]; if (partStartsWith(candidate, span, chunk.text, true)) { return createPatternMatch(PatternMatchKind.substring, punctuationStripped, partStartsWith(candidate, span, chunk.text, false)); } @@ -32714,8 +33087,8 @@ var ts; } var subWordTextChunks = segment.subWordTextChunks; var matches = undefined; - for (var _i = 0; _i < subWordTextChunks.length; _i++) { - var subWordTextChunk = subWordTextChunks[_i]; + for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { + var subWordTextChunk = subWordTextChunks_1[_i]; var result = matchTextChunk(candidate, subWordTextChunk, true); if (!result) { return undefined; @@ -33078,8 +33451,8 @@ var ts; var nameToDeclarations = sourceFile_1.getNamedDeclarations(); var declarations = ts.getProperty(nameToDeclarations, name.text); if (declarations) { - for (var _b = 0; _b < declarations.length; _b++) { - var declaration = declarations[_b]; + for (var _b = 0, declarations_7 = declarations; _b < declarations_7.length; _b++) { + var declaration = declarations_7[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -33155,8 +33528,8 @@ var ts; function getArgumentIndex(argumentsList, node) { var argumentIndex = 0; var listChildren = argumentsList.getChildren(); - for (var _i = 0; _i < listChildren.length; _i++) { - var child = listChildren[_i]; + for (var _i = 0, listChildren_1 = listChildren; _i < listChildren_1.length; _i++) { + var child = listChildren_1[_i]; if (child === node) { break; } @@ -33598,8 +33971,8 @@ var ts; return n; } var children = n.getChildren(); - for (var _i = 0; _i < children.length; _i++) { - var child = children[_i]; + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; var shouldDiveInChildNode = (child.pos <= previousToken.pos && child.end > previousToken.end) || (child.pos === previousToken.end); if (shouldDiveInChildNode && nodeHasTokens(child)) { @@ -33722,17 +34095,17 @@ var ts; function getNodeModifiers(node) { var flags = ts.getCombinedNodeFlags(node); var result = []; - if (flags & 32) - result.push(ts.ScriptElementKindModifier.privateMemberModifier); - if (flags & 64) - result.push(ts.ScriptElementKindModifier.protectedMemberModifier); if (flags & 16) + result.push(ts.ScriptElementKindModifier.privateMemberModifier); + if (flags & 32) + result.push(ts.ScriptElementKindModifier.protectedMemberModifier); + if (flags & 8) result.push(ts.ScriptElementKindModifier.publicMemberModifier); - if (flags & 128) + if (flags & 64) result.push(ts.ScriptElementKindModifier.staticModifier); - if (flags & 256) + if (flags & 128) result.push(ts.ScriptElementKindModifier.abstractModifier); - if (flags & 1) + if (flags & 2) result.push(ts.ScriptElementKindModifier.exportedModifier); if (ts.isInAmbientContext(node)) result.push(ts.ScriptElementKindModifier.ambientModifier); @@ -35533,8 +35906,8 @@ var ts; } } var inheritedIndentation = -1; - for (var _i = 0; _i < nodes.length; _i++) { - var child = nodes[_i]; + for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { + var child = nodes_6[_i]; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, true); } if (listEndToken !== 0) { @@ -35616,8 +35989,8 @@ var ts; } } function processTrivia(trivia, parent, contextNode, dynamicIndentation) { - for (var _i = 0; _i < trivia.length; _i++) { - var triviaItem = trivia[_i]; + for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { + var triviaItem = trivia_1[_i]; if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); @@ -36146,7 +36519,6 @@ var ts; return node; } } - return node; } } function deriveActualIndentationFromList(list, index, sourceFile, options) { @@ -36374,17 +36746,17 @@ var ts; while (pos < end) { var token = scanner.scan(); var textPos = scanner.getTextPos(); - nodes.push(createNode(token, pos, textPos, 4096, this)); + nodes.push(createNode(token, pos, textPos, 2048, this)); pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(271, nodes.pos, nodes.end, 4096, this); + var list = createNode(271, nodes.pos, nodes.end, 2048, this); list._children = []; var pos = nodes.pos; - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -36890,7 +37262,7 @@ var ts; } break; case 138: - if (!(node.flags & 112)) { + if (!(node.flags & 56)) { break; } case 211: @@ -37089,18 +37461,20 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; - this.fileNameToEntry = ts.createFileMap(getCanonicalFileName); + this.getCanonicalFileName = getCanonicalFileName; + this.currentDirectory = host.getCurrentDirectory(); + this.fileNameToEntry = ts.createFileMap(); var rootFileNames = host.getScriptFileNames(); - for (var _i = 0; _i < rootFileNames.length; _i++) { - var fileName = rootFileNames[_i]; - this.createEntry(fileName); + for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { + var fileName = rootFileNames_1[_i]; + this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); } this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); } HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; - HostCache.prototype.createEntry = function (fileName) { + HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); if (scriptSnapshot) { @@ -37110,36 +37484,37 @@ var ts; scriptSnapshot: scriptSnapshot }; } - this.fileNameToEntry.set(fileName, entry); + this.fileNameToEntry.set(path, entry); return entry; }; - HostCache.prototype.getEntry = function (fileName) { - return this.fileNameToEntry.get(fileName); + HostCache.prototype.getEntry = function (path) { + return this.fileNameToEntry.get(path); }; - HostCache.prototype.contains = function (fileName) { - return this.fileNameToEntry.contains(fileName); + HostCache.prototype.contains = function (path) { + return this.fileNameToEntry.contains(path); }; HostCache.prototype.getOrCreateEntry = function (fileName) { - if (this.contains(fileName)) { - return this.getEntry(fileName); + var path = ts.toPath(fileName, this.currentDirectory, this.getCanonicalFileName); + if (this.contains(path)) { + return this.getEntry(path); } - return this.createEntry(fileName); + return this.createEntry(fileName, path); }; HostCache.prototype.getRootFileNames = function () { var fileNames = []; - this.fileNameToEntry.forEachValue(function (value) { + this.fileNameToEntry.forEachValue(function (path, value) { if (value) { fileNames.push(value.hostFileName); } }); return fileNames; }; - HostCache.prototype.getVersion = function (fileName) { - var file = this.getEntry(fileName); + HostCache.prototype.getVersion = function (path) { + var file = this.getEntry(path); return file && file.version; }; - HostCache.prototype.getScriptSnapshot = function (fileName) { - var file = this.getEntry(fileName); + HostCache.prototype.getScriptSnapshot = function (path) { + var file = this.getEntry(path); return file && file.scriptSnapshot; }; return HostCache; @@ -37282,7 +37657,8 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; - function createDocumentRegistry(useCaseSensitiveFileNames) { + function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } var buckets = {}; var getCanonicalFileName = createGetCanonicalFileName(!!useCaseSensitiveFileNames); function getKeyFromCompilationSettings(settings) { @@ -37292,7 +37668,7 @@ var ts; var key = getKeyFromCompilationSettings(settings); var bucket = ts.lookUp(buckets, key); if (!bucket && createIfMissing) { - buckets[key] = bucket = ts.createFileMap(getCanonicalFileName); + buckets[key] = bucket = ts.createFileMap(); } return bucket; } @@ -37300,14 +37676,13 @@ var ts; var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === '_'; }).map(function (name) { var entries = ts.lookUp(buckets, name); var sourceFiles = []; - for (var i in entries) { - var entry = entries.get(i); + entries.forEachValue(function (key, entry) { sourceFiles.push({ - name: i, + name: key, refCount: entry.languageServiceRefCount, references: entry.owners.slice(0) }); - } + }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); return { bucket: name, @@ -37324,7 +37699,8 @@ var ts; } function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { var bucket = getBucketForCompilationSettings(compilationSettings, true); - var entry = bucket.get(fileName); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = bucket.get(path); if (!entry) { ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); var sourceFile = createLanguageServiceSourceFile(fileName, scriptSnapshot, compilationSettings.target, version, false); @@ -37333,7 +37709,7 @@ var ts; languageServiceRefCount: 0, owners: [] }; - bucket.set(fileName, entry); + bucket.set(path, entry); } else { if (entry.sourceFile.version !== version) { @@ -37348,11 +37724,12 @@ var ts; function releaseDocument(fileName, compilationSettings) { var bucket = getBucketForCompilationSettings(compilationSettings, false); ts.Debug.assert(bucket !== undefined); - var entry = bucket.get(fileName); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = bucket.get(path); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.remove(fileName); + bucket.remove(path); } } return { @@ -37705,7 +38082,7 @@ var ts; case 144: return ScriptElementKind.constructorImplementationElement; case 137: return ScriptElementKind.typeParameterElement; case 247: return ScriptElementKind.variableElement; - case 138: return (node.flags & 112) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; + case 138: return (node.flags & 56) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; case 221: case 226: case 223: @@ -37731,13 +38108,14 @@ var ts; return CancellationTokenObject; })(); function createLanguageService(host, documentRegistry) { - if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(); } + if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); var ruleProvider; var program; var lastProjectVersion; var useCaseSensitivefileNames = false; var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); + var currentDirectory = host.getCurrentDirectory(); if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); } @@ -37748,8 +38126,7 @@ var ts; } var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName) { - fileName = ts.normalizeSlashes(fileName); - var sourceFile = program.getSourceFile(getCanonicalFileName(fileName)); + var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { throw new Error("Could not find file: '" + fileName + "'."); } @@ -37791,7 +38168,7 @@ var ts; getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: function (fileName, data, writeByteOrderMark) { }, - getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { ts.Debug.assert(!host.resolveModuleNames); return hostCache.getOrCreateEntry(fileName) !== undefined; @@ -37807,11 +38184,10 @@ var ts; var newProgram = ts.createProgram(hostCache.getRootFileNames(), newSettings, compilerHost, program); if (program) { var oldSourceFiles = program.getSourceFiles(); - for (var _i = 0; _i < oldSourceFiles.length; _i++) { - var oldSourceFile = oldSourceFiles[_i]; - var fileName = oldSourceFile.fileName; - if (!newProgram.getSourceFile(fileName) || changesInCompilationSettingsAffectSyntax) { - documentRegistry.releaseDocument(fileName, oldSettings); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; + if (!newProgram.getSourceFile(oldSourceFile.fileName) || changesInCompilationSettingsAffectSyntax) { + documentRegistry.releaseDocument(oldSourceFile.fileName, oldSettings); } } } @@ -37834,7 +38210,8 @@ var ts; return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); } function sourceFileUpToDate(sourceFile) { - return sourceFile && sourceFile.version === hostCache.getVersion(sourceFile.fileName); + var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); + return sourceFile && sourceFile.version === hostCache.getVersion(path); } function programUpToDate() { if (!program) { @@ -37844,8 +38221,8 @@ var ts; if (program.getSourceFiles().length !== rootFileNames.length) { return false; } - for (var _i = 0; _i < rootFileNames.length; _i++) { - var fileName = rootFileNames[_i]; + for (var _i = 0, rootFileNames_2 = rootFileNames; _i < rootFileNames_2.length; _i++) { + var fileName = rootFileNames_2[_i]; if (!sourceFileUpToDate(program.getSourceFile(fileName))) { return false; } @@ -38007,8 +38384,8 @@ var ts; } function checkModifiers(modifiers) { if (modifiers) { - for (var _i = 0; _i < modifiers.length; _i++) { - var modifier = modifiers[_i]; + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; switch (modifier.kind) { case 112: case 110: @@ -38571,8 +38948,8 @@ var ts; } function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { var exisingImportsOrExports = {}; - for (var _i = 0; _i < namedImportsOrExports.length; _i++) { - var element = namedImportsOrExports[_i]; + for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { + var element = namedImportsOrExports_1[_i]; if (element.getStart() <= position && position <= element.getEnd()) { continue; } @@ -38589,8 +38966,8 @@ var ts; return contextualMemberSymbols; } var existingMemberNames = {}; - for (var _i = 0; _i < existingMembers.length; _i++) { - var m = existingMembers[_i]; + for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { + var m = existingMembers_1[_i]; if (m.kind !== 245 && m.kind !== 246 && m.kind !== 163) { @@ -38612,8 +38989,8 @@ var ts; } function filterJsxAttributes(symbols, attributes) { var seenNames = {}; - for (var _i = 0; _i < attributes.length; _i++) { - var attr = attributes[_i]; + for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { + var attr = attributes_1[_i]; if (attr.getStart() <= position && position <= attr.getEnd()) { continue; } @@ -38701,8 +39078,8 @@ var ts; var entries = []; if (symbols) { var nameToSymbol = {}; - for (var _i = 0; _i < symbols.length; _i++) { - var symbol = symbols[_i]; + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var symbol = symbols_3[_i]; var entry = createCompletionEntry(symbol, location); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -39385,8 +39762,8 @@ var ts; } var fileNameToDocumentHighlights = {}; var result = []; - for (var _i = 0; _i < referencedSymbols.length; _i++) { - var referencedSymbol = referencedSymbols[_i]; + for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { + var referencedSymbol = referencedSymbols_1[_i]; for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { var referenceEntry = _b[_a]; var fileName_1 = referenceEntry.fileName; @@ -39522,7 +39899,6 @@ var ts; ts.forEachChild(node, aggregate); } } - ; } function getThrowStatementOwner(throwStatement) { var child = throwStatement; @@ -39553,7 +39929,6 @@ var ts; ts.forEachChild(node, aggregate); } } - ; } function ownsBreakOrContinueStatement(owner, statement) { var actualOwner = getBreakOrContinueOwner(statement); @@ -39617,7 +39992,7 @@ var ts; switch (container.kind) { case 219: case 248: - if (modifierFlag & 256) { + if (modifierFlag & 128) { nodes = declaration.members.concat(declaration); } else { @@ -39630,7 +40005,7 @@ var ts; case 214: case 186: nodes = container.members; - if (modifierFlag & 112) { + if (modifierFlag & 56) { var constructor = ts.forEach(container.members, function (member) { return member.kind === 144 && member; }); @@ -39638,7 +40013,7 @@ var ts; nodes = nodes.concat(constructor.parameters); } } - else if (modifierFlag & 256) { + else if (modifierFlag & 128) { nodes = nodes.concat(container); } break; @@ -39654,19 +40029,19 @@ var ts; function getFlagFromModifier(modifier) { switch (modifier) { case 112: - return 16; + return 8; case 110: - return 32; + return 16; case 111: - return 64; + return 32; case 113: - return 128; + return 64; case 82: - return 1; - case 122: return 2; + case 122: + return 4; case 115: - return 256; + return 128; default: ts.Debug.fail(); } @@ -39851,8 +40226,8 @@ var ts; return undefined; } var result = []; - for (var _i = 0; _i < documentHighlights.length; _i++) { - var entry = documentHighlights[_i]; + for (var _i = 0, documentHighlights_1 = documentHighlights; _i < documentHighlights_1.length; _i++) { + var entry = documentHighlights_1[_i]; for (var _a = 0, _b = entry.highlightSpans; _a < _b.length; _a++) { var highlightSpan = _b[_a]; result.push({ @@ -39870,8 +40245,8 @@ var ts; return undefined; } var referenceEntries = []; - for (var _i = 0; _i < referenceSymbols.length; _i++) { - var referenceSymbol = referenceSymbols[_i]; + for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) { + var referenceSymbol = referenceSymbols_1[_i]; ts.addRange(referenceEntries, referenceSymbol.references); } return referenceEntries; @@ -39939,8 +40314,8 @@ var ts; } else { var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0; _i < sourceFiles.length; _i++) { - var sourceFile = sourceFiles[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); if (ts.lookUp(nameTable, internedName)) { @@ -39985,7 +40360,7 @@ var ts; return valueDeclaration; } if (symbol.flags & (4 | 8192)) { - var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 32) ? d : undefined; }); + var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 16) ? d : undefined; }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 214); } @@ -39999,8 +40374,8 @@ var ts; var scope = undefined; var declarations = symbol.getDeclarations(); if (declarations) { - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; @@ -40153,7 +40528,7 @@ var ts; if (!searchSpaceNode) { return undefined; } - var staticFlag = 128; + var staticFlag = 64; switch (searchSpaceNode.kind) { case 141: case 140: @@ -40178,7 +40553,7 @@ var ts; return; } var container = ts.getSuperContainer(node, false); - if (container && (128 & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { + if (container && (64 & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { references.push(getReferenceEntryFromNode(node)); } }); @@ -40187,7 +40562,7 @@ var ts; } function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, false); - var staticFlag = 128; + var staticFlag = 64; switch (searchSpaceNode.kind) { case 143: case 142: @@ -40259,7 +40634,7 @@ var ts; break; case 186: case 214: - if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 128) === staticFlag) { + if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 64) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; @@ -40386,8 +40761,8 @@ var ts; var lastIterationMeaning; do { lastIterationMeaning = meaning; - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; var declarationMeaning = getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -40500,7 +40875,6 @@ var ts; return 4 | 1; } return 1 | 2 | 4; - ts.Debug.fail("Unknown declaration type"); } function isTypeReference(node) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { @@ -41007,8 +41381,8 @@ var ts; if (matchKind) { var parentElement = token.parent; var childNodes = parentElement.getChildren(sourceFile); - for (var _i = 0; _i < childNodes.length; _i++) { - var current = childNodes[_i]; + for (var _i = 0, childNodes_1 = childNodes; _i < childNodes_1.length; _i++) { + var current = childNodes_1[_i]; if (current.kind === matchKind) { var range1 = ts.createTextSpan(token.getStart(sourceFile), token.getWidth(sourceFile)); var range2 = ts.createTextSpan(current.getStart(sourceFile), current.getWidth(sourceFile)); @@ -41224,8 +41598,8 @@ var ts; if (declarations && declarations.length > 0) { var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); if (defaultLibFileName) { - for (var _i = 0; _i < declarations.length; _i++) { - var current = declarations[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var current = declarations_10[_i]; var sourceFile_2 = current.getSourceFile(); var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); if (sourceFile_2 && getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)) === getCanonicalFileName(ts.normalizePath(defaultLibFileName))) { @@ -41962,8 +42336,8 @@ var ts; if (this.logger.isVerbose()) { this.logger.info(msg.type + ": " + json); } - this.sendLineToClient('Content-Length: ' + (1 + this.byteLength(json, 'utf8')) + - '\r\n\r\n' + json); + this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) + + "\r\n\r\n" + json); }; Session.prototype.event = function (info, eventName) { var ev = { @@ -42346,7 +42720,8 @@ var ts; }; var preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); var hasIndent = 0; - for (var i = 0, len = lineText.length; i < len; i++) { + var i, len; + for (i = 0, len = lineText.length; i < len; i++) { if (lineText.charAt(i) == " ") { hasIndent++; } @@ -42553,7 +42928,7 @@ var ts; if (navItem.kindModifiers && (navItem.kindModifiers != "")) { bakedItem.kindModifiers = navItem.kindModifiers; } - if (navItem.matchKind != 'none') { + if (navItem.matchKind !== "none") { bakedItem.matchKind = navItem.matchKind; } if (navItem.containerName && (navItem.containerName.length > 0)) { @@ -42592,8 +42967,8 @@ var ts; var veryLowPriorityFiles = []; var normalizedFileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(normalizedFileName); - for (var _i = 0; _i < fileNamesInProject.length; _i++) { - var fileNameInProject = fileNamesInProject[_i]; + for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { + var fileNameInProject = fileNamesInProject_1[_i]; if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName)) highPriorityFiles.push(fileNameInProject); else { @@ -42641,12 +43016,14 @@ var ts; } }; Session.prototype.onMessage = function (message) { + var start; if (this.logger.isVerbose()) { this.logger.info("request: " + message); - var start = this.hrtime(); + start = this.hrtime(); } + var request; try { - var request = JSON.parse(message); + request = JSON.parse(message); var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; if (this.logger.isVerbose()) { var elapsed = this.hrtime(start); @@ -42701,6 +43078,7 @@ var ts; this.isOpen = isOpen; this.children = []; this.formatCodeOptions = ts.clone(CompilerService.defaultFormatCodeOptions); + this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); this.svc = ScriptVersionCache.fromString(host, content); } ScriptInfo.prototype.setFormatOptions = function (formatOptions) { @@ -42742,23 +43120,23 @@ var ts; var _this = this; this.host = host; this.project = project; - this.ls = null; this.roots = []; - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - this.resolvedModuleNames = ts.createFileMap(getCanonicalFileName); - this.filenameToScript = ts.createFileMap(getCanonicalFileName); + this.getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + this.resolvedModuleNames = ts.createFileMap(); + this.filenameToScript = ts.createFileMap(); this.moduleResolutionHost = { fileExists: function (fileName) { return _this.fileExists(fileName); }, readFile: function (fileName) { return _this.host.readFile(fileName); } }; } LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { - var currentResolutionsInFile = this.resolvedModuleNames.get(containingFile); + var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var currentResolutionsInFile = this.resolvedModuleNames.get(path); var newResolutions = {}; var resolvedModules = []; var compilerOptions = this.getCompilationSettings(); - for (var _i = 0; _i < moduleNames.length; _i++) { - var moduleName = moduleNames[_i]; + for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) { + var moduleName = moduleNames_1[_i]; var resolution = ts.lookUp(newResolutions, moduleName); if (!resolution) { var existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, moduleName); @@ -42774,7 +43152,7 @@ var ts; ts.Debug.assert(resolution !== undefined); resolvedModules.push(resolution.resolvedModule); } - this.resolvedModuleNames.set(containingFile, newResolutions); + this.resolvedModuleNames.set(path, newResolutions); return resolvedModules; function moduleResolutionIsValid(resolution) { if (!resolution) { @@ -42825,31 +43203,32 @@ var ts; }; LSHost.prototype.removeReferencedFile = function (info) { if (!info.isOpen) { - this.filenameToScript.remove(info.fileName); - this.resolvedModuleNames.remove(info.fileName); + this.filenameToScript.remove(info.path); + this.resolvedModuleNames.remove(info.path); } }; LSHost.prototype.getScriptInfo = function (filename) { - var scriptInfo = this.filenameToScript.get(filename); + var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var scriptInfo = this.filenameToScript.get(path); if (!scriptInfo) { scriptInfo = this.project.openReferencedFile(filename); if (scriptInfo) { - this.filenameToScript.set(scriptInfo.fileName, scriptInfo); + this.filenameToScript.set(path, scriptInfo); } } return scriptInfo; }; LSHost.prototype.addRoot = function (info) { - if (!this.filenameToScript.contains(info.fileName)) { - this.filenameToScript.set(info.fileName, info); + if (!this.filenameToScript.contains(info.path)) { + this.filenameToScript.set(info.path, info); this.roots.push(info); } }; LSHost.prototype.removeRoot = function (info) { - if (!this.filenameToScript.contains(info.fileName)) { - this.filenameToScript.remove(info.fileName); + if (!this.filenameToScript.contains(info.path)) { + this.filenameToScript.remove(info.path); this.roots = copyListRemovingItem(info, this.roots); - this.resolvedModuleNames.remove(info.fileName); + this.resolvedModuleNames.remove(info.path); } }; LSHost.prototype.saveTo = function (filename, tmpfilename) { @@ -42887,7 +43266,8 @@ var ts; return this.host.directoryExists(path); }; LSHost.prototype.lineToTextSpan = function (filename, line) { - var script = this.filenameToScript.get(filename); + var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var script = this.filenameToScript.get(path); var index = script.snap().index; var lineInfo = index.lineNumberToInfo(line + 1); var len; @@ -42901,13 +43281,15 @@ var ts; return ts.createTextSpan(lineInfo.offset, len); }; LSHost.prototype.lineOffsetToPosition = function (filename, line, offset) { - var script = this.filenameToScript.get(filename); + var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var script = this.filenameToScript.get(path); var index = script.snap().index; var lineInfo = index.lineNumberToInfo(line); return (lineInfo.offset + offset - 1); }; LSHost.prototype.positionToLineOffset = function (filename, position) { - var script = this.filenameToScript.get(filename); + var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var script = this.filenameToScript.get(path); var index = script.snap().index; var lineOffset = index.charOffsetToLineNumberAndPos(position); return { line: lineOffset.line, offset: lineOffset.offset + 1 }; @@ -42921,22 +43303,22 @@ var ts; return filename; } else { - var splitFilename = filename.split('/'); - var splitDir = directory.split('/'); + var splitFilename = filename.split("/"); + var splitDir = directory.split("/"); var i = 0; var dirTail = 0; var sflen = splitFilename.length; - while ((i < sflen) && (splitFilename[i].charAt(0) == '.')) { + while ((i < sflen) && (splitFilename[i].charAt(0) == ".")) { var dots = splitFilename[i]; - if (dots == '..') { + if (dots == "..") { dirTail++; } - else if (dots != '.') { + else if (dots != ".") { return undefined; } i++; } - return splitDir.slice(0, splitDir.length - dirTail).concat(splitFilename.slice(i)).join('/'); + return splitDir.slice(0, splitDir.length - dirTail).concat(splitFilename.slice(i)).join("/"); } } var Project = (function () { @@ -43111,8 +43493,8 @@ var ts; var _a = this.configFileToProjectOptions(fileName), succeeded = _a.succeeded, projectOptions = _a.projectOptions, error = _a.error; var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); }); var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); }); - for (var _i = 0; _i < openFileRoots.length; _i++) { - var openFileRoot = openFileRoots[_i]; + for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) { + var openFileRoot = openFileRoots_1[_i]; if (rootFilesInTsconfig.indexOf(openFileRoot) >= 0) { this.reloadProjects(); return; @@ -43236,8 +43618,8 @@ var ts; this.inferredProjects = copyListRemovingItem(project, this.inferredProjects); } var fileNames = project.getFileNames(); - for (var _b = 0; _b < fileNames.length; _b++) { - var fileName = fileNames[_b]; + for (var _b = 0, fileNames_1 = fileNames; _b < fileNames_1.length; _b++) { + var fileName = fileNames_1[_b]; var info = this.getScriptInfo(fileName); if (info.defaultProject == project) { info.defaultProject = undefined; @@ -43591,10 +43973,11 @@ var ts; } else { var parsedCommandLine = ts.parseJsonConfigFileContent(rawConfig.config, this.host, dirPath); + ts.Debug.assert(!!parsedCommandLine.fileNames); if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) { return { succeeded: false, error: { errorMsg: "tsconfig option errors" } }; } - else if (parsedCommandLine.fileNames == null) { + else if (parsedCommandLine.fileNames.length === 0) { return { succeeded: false, error: { errorMsg: "no files found" } }; } else { @@ -43646,15 +44029,15 @@ var ts; var newFileNames = projectOptions.files; var fileNamesToRemove = oldFileNames.filter(function (f) { return newFileNames.indexOf(f) < 0; }); var fileNamesToAdd = newFileNames.filter(function (f) { return oldFileNames.indexOf(f) < 0; }); - for (var _i = 0; _i < fileNamesToRemove.length; _i++) { - var fileName = fileNamesToRemove[_i]; + for (var _i = 0, fileNamesToRemove_1 = fileNamesToRemove; _i < fileNamesToRemove_1.length; _i++) { + var fileName = fileNamesToRemove_1[_i]; var info = this.getScriptInfo(fileName); if (info) { project.removeRoot(info); } } - for (var _b = 0; _b < fileNamesToAdd.length; _b++) { - var fileName = fileNamesToAdd[_b]; + for (var _b = 0, fileNamesToAdd_1 = fileNamesToAdd; _b < fileNamesToAdd_1.length; _b++) { + var fileName = fileNamesToAdd_1[_b]; var info = this.getScriptInfo(fileName); if (!info) { info = this.openFile(fileName, false); @@ -43714,7 +44097,7 @@ var ts; CompilerService.defaultFormatCodeOptions = { IndentSize: 4, TabSize: 4, - NewLineCharacter: ts.sys ? ts.sys.newLine : '\n', + NewLineCharacter: ts.sys ? ts.sys.newLine : "\n", ConvertTabsToSpaces: true, IndentStyle: ts.IndentStyle.Smart, InsertSpaceAfterCommaDelimiter: true, @@ -43804,7 +44187,7 @@ var ts; if (len > 1) { var insertedNodes = new Array(len - 1); var startNode = leafNode; - for (var i = 1, len = lines.length; i < len; i++) { + for (var i = 1, len_1 = lines.length; i < len_1; i++) { insertedNodes[i - 1] = new LineLeaf(lines[i]); } var pathIndex = this.startPath.length - 2; @@ -44172,8 +44555,9 @@ var ts; } } else { + var checkText; if (this.checkEdits) { - var checkText = editFlat(this.getText(0, this.root.charCount()), pos, deleteLength, newText); + checkText = editFlat(this.getText(0, this.root.charCount()), pos, deleteLength, newText); } var walker = new EditWalker(); if (pos >= this.root.charCount()) { @@ -44399,7 +44783,9 @@ var ts; LineNode.prototype.childFromLineNumber = function (lineNumber, charOffset) { var child; var relativeLineNumber = lineNumber; - for (var i = 0, len = this.children.length; i < len; i++) { + var i; + var len; + for (i = 0, len = this.children.length; i < len; i++) { child = this.children[i]; var childLineCount = child.lineCount(); if (childLineCount >= relativeLineNumber) { @@ -44419,7 +44805,9 @@ var ts; }; LineNode.prototype.childFromCharOffset = function (lineNumber, charOffset) { var child; - for (var i = 0, len = this.children.length; i < len; i++) { + var i; + var len; + for (i = 0, len = this.children.length; i < len; i++) { child = this.children[i]; if (child.charCount() > charOffset) { break; @@ -44501,7 +44889,7 @@ var ts; splitNode = splitNodes[splitNodeIndex]; } } - for (i = splitNodes.length - 1; i >= 0; i--) { + for (var i = splitNodes.length - 1; i >= 0; i--) { if (splitNodes[i].children.length === 0) { splitNodes.length--; } @@ -44511,7 +44899,7 @@ var ts; splitNodes[splitNodes.length] = shiftNode; } this.updateCounts(); - for (i = 0; i < splitNodeCount; i++) { + for (var i = 0; i < splitNodeCount; i++) { splitNodes[i].updateCounts(); } return splitNodes; @@ -44561,10 +44949,10 @@ var ts; (function (ts) { var server; (function (server) { - var nodeproto = require('_debugger'); - var readline = require('readline'); - var path = require('path'); - var fs = require('fs'); + var nodeproto = require("_debugger"); + var readline = require("readline"); + var path = require("path"); + var fs = require("fs"); var rl = readline.createInterface({ input: process.stdin, output: process.stdout, @@ -44644,11 +45032,11 @@ var ts; }; IOSession.prototype.listen = function () { var _this = this; - rl.on('line', function (input) { + rl.on("line", function (input) { var message = input.trim(); _this.onMessage(message); }); - rl.on('close', function () { + rl.on("close", function () { _this.exit(); }); }; @@ -44656,7 +45044,7 @@ var ts; })(server.Session); function parseLoggingEnvironmentString(logEnvStr) { var logEnv = {}; - var args = logEnvStr.split(' '); + var args = logEnvStr.split(" "); for (var i = 0, len = args.length; i < (len - 1); i += 2) { var option = args[i]; var value = args[i + 1]; @@ -44711,7 +45099,7 @@ var ts; } ts.sys.write = function (s) { return writeMessage(s); }; var ioSession = new IOSession(ts.sys, logger); - process.on('uncaughtException', function (err) { + process.on("uncaughtException", function (err) { ioSession.logError(err, "unknown"); }); ioSession.listen(); @@ -44794,7 +45182,6 @@ var ts; var settingsJson = this.shimHost.getCompilationSettings(); if (settingsJson == null || settingsJson == "") { throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); - return null; } return JSON.parse(settingsJson); }; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index d94e55eb48f..972ebfa472d 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -17,19 +17,22 @@ declare namespace ts { interface Map { [index: string]: T; } + type Path = string & { + __pathBrand: any; + }; interface FileMap { - get(fileName: string): T; - set(fileName: string, value: T): void; - contains(fileName: string): boolean; - remove(fileName: string): void; - forEachValue(f: (v: T) => void): void; + get(fileName: Path): T; + set(fileName: Path, value: T): void; + contains(fileName: Path): boolean; + remove(fileName: Path): void; + forEachValue(f: (key: Path, v: T) => void): void; clear(): void; } interface TextRange { pos: number; end: number; } - const enum SyntaxKind { + enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, SingleLineCommentTrivia = 2, @@ -327,31 +330,34 @@ declare namespace ts { LastBinaryOperator = 68, FirstNode = 135, } - const enum NodeFlags { + enum NodeFlags { None = 0, - Export = 1, - Ambient = 2, - Public = 16, - Private = 32, - Protected = 64, - Static = 128, - Abstract = 256, - Async = 512, - Default = 1024, - MultiLine = 2048, - Synthetic = 4096, - DeclarationFile = 8192, - Let = 16384, - Const = 32768, - OctalLiteral = 65536, - Namespace = 131072, - ExportContext = 262144, - ContainsThis = 524288, - Modifier = 2035, - AccessibilityModifier = 112, - BlockScoped = 49152, + Export = 2, + Ambient = 4, + Public = 8, + Private = 16, + Protected = 32, + Static = 64, + Abstract = 128, + Async = 256, + Default = 512, + MultiLine = 1024, + Synthetic = 2048, + DeclarationFile = 4096, + Let = 8192, + Const = 16384, + OctalLiteral = 32768, + Namespace = 65536, + ExportContext = 131072, + ContainsThis = 262144, + HasImplicitReturn = 524288, + HasExplicitReturn = 1048576, + Modifier = 1022, + AccessibilityModifier = 56, + BlockScoped = 24576, + ReachabilityCheckFlags = 1572864, } - const enum JsxFlags { + enum JsxFlags { None = 0, IntrinsicNamedElement = 1, IntrinsicIndexedElement = 2, @@ -931,6 +937,7 @@ declare namespace ts { statements: NodeArray; endOfFileToken: Node; fileName: string; + path: Path; text: string; amdDependencies: { path: string; @@ -1093,7 +1100,7 @@ declare namespace ts { trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; reportInaccessibleThisError(): void; } - const enum TypeFormatFlags { + enum TypeFormatFlags { None = 0, WriteArrayAsGenericType = 1, UseTypeOfFunction = 2, @@ -1104,7 +1111,7 @@ declare namespace ts { InElementType = 64, UseFullyQualifiedType = 128, } - const enum SymbolFormatFlags { + enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, @@ -1114,7 +1121,7 @@ declare namespace ts { parameterIndex: number; type: Type; } - const enum SymbolFlags { + enum SymbolFlags { None = 0, FunctionScopedVariable = 1, BlockScopedVariable = 2, @@ -1191,7 +1198,7 @@ declare namespace ts { interface SymbolTable { [index: string]: Symbol; } - const enum TypeFlags { + enum TypeFlags { Any = 1, String = 2, Number = 4, @@ -1262,7 +1269,7 @@ declare namespace ts { interface TypeParameter extends Type { constraint: Type; } - const enum SignatureKind { + enum SignatureKind { Call = 0, Construct = 1, } @@ -1272,7 +1279,7 @@ declare namespace ts { parameters: Symbol[]; typePredicate?: TypePredicate; } - const enum IndexKind { + enum IndexKind { String = 0, Number = 1, } @@ -1307,7 +1314,7 @@ declare namespace ts { Error = 1, Message = 2, } - const enum ModuleResolutionKind { + enum ModuleResolutionKind { Classic = 1, NodeJs = 2, } @@ -1352,10 +1359,14 @@ declare namespace ts { experimentalDecorators?: boolean; emitDecoratorMetadata?: boolean; moduleResolution?: ModuleResolutionKind; + allowUnusedLabels?: boolean; + allowUnreachableCode?: boolean; + noImplicitReturns?: boolean; + noFallthroughCasesInSwitch?: boolean; forceConsistentCasingInFileNames?: boolean; [option: string]: string | number | boolean; } - const enum ModuleKind { + enum ModuleKind { None = 0, CommonJS = 1, AMD = 2, @@ -1364,12 +1375,12 @@ declare namespace ts { ES6 = 5, ES2015 = 5, } - const enum JsxEmit { + enum JsxEmit { None = 0, Preserve = 1, React = 2, } - const enum NewLineKind { + enum NewLineKind { CarriageReturnLineFeed = 0, LineFeed = 1, } @@ -1377,14 +1388,14 @@ declare namespace ts { line: number; character: number; } - const enum ScriptTarget { + enum ScriptTarget { ES3 = 0, ES5 = 1, ES6 = 2, ES2015 = 2, Latest = 2, } - const enum LanguageVariant { + enum LanguageVariant { Standard = 0, JSX = 1, } @@ -1938,7 +1949,7 @@ declare namespace ts { outputFiles: OutputFile[]; emitSkipped: boolean; } - const enum OutputFileType { + enum OutputFileType { JavaScript = 0, SourceMap = 1, Declaration = 2, @@ -1948,7 +1959,7 @@ declare namespace ts { writeByteOrderMark: boolean; text: string; } - const enum EndOfLineState { + enum EndOfLineState { None = 0, InMultiLineCommentTrivia = 1, InSingleQuoteStringLiteral = 2, @@ -2116,7 +2127,7 @@ declare namespace ts { static parameterName: string; static docCommentTagName: string; } - const enum ClassificationType { + enum ClassificationType { comment = 1, identifier = 2, keyword = 3, @@ -2159,7 +2170,7 @@ declare namespace ts { let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; - function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; function createClassifier(): Classifier; diff --git a/lib/typescript.js b/lib/typescript.js index 1e0c0edad05..8b0ef04f96e 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -350,27 +350,30 @@ var ts; var SyntaxKind = ts.SyntaxKind; (function (NodeFlags) { NodeFlags[NodeFlags["None"] = 0] = "None"; - NodeFlags[NodeFlags["Export"] = 1] = "Export"; - NodeFlags[NodeFlags["Ambient"] = 2] = "Ambient"; - NodeFlags[NodeFlags["Public"] = 16] = "Public"; - NodeFlags[NodeFlags["Private"] = 32] = "Private"; - NodeFlags[NodeFlags["Protected"] = 64] = "Protected"; - NodeFlags[NodeFlags["Static"] = 128] = "Static"; - NodeFlags[NodeFlags["Abstract"] = 256] = "Abstract"; - NodeFlags[NodeFlags["Async"] = 512] = "Async"; - NodeFlags[NodeFlags["Default"] = 1024] = "Default"; - NodeFlags[NodeFlags["MultiLine"] = 2048] = "MultiLine"; - NodeFlags[NodeFlags["Synthetic"] = 4096] = "Synthetic"; - NodeFlags[NodeFlags["DeclarationFile"] = 8192] = "DeclarationFile"; - NodeFlags[NodeFlags["Let"] = 16384] = "Let"; - NodeFlags[NodeFlags["Const"] = 32768] = "Const"; - NodeFlags[NodeFlags["OctalLiteral"] = 65536] = "OctalLiteral"; - NodeFlags[NodeFlags["Namespace"] = 131072] = "Namespace"; - NodeFlags[NodeFlags["ExportContext"] = 262144] = "ExportContext"; - NodeFlags[NodeFlags["ContainsThis"] = 524288] = "ContainsThis"; - NodeFlags[NodeFlags["Modifier"] = 2035] = "Modifier"; - NodeFlags[NodeFlags["AccessibilityModifier"] = 112] = "AccessibilityModifier"; - NodeFlags[NodeFlags["BlockScoped"] = 49152] = "BlockScoped"; + NodeFlags[NodeFlags["Export"] = 2] = "Export"; + NodeFlags[NodeFlags["Ambient"] = 4] = "Ambient"; + NodeFlags[NodeFlags["Public"] = 8] = "Public"; + NodeFlags[NodeFlags["Private"] = 16] = "Private"; + NodeFlags[NodeFlags["Protected"] = 32] = "Protected"; + NodeFlags[NodeFlags["Static"] = 64] = "Static"; + NodeFlags[NodeFlags["Abstract"] = 128] = "Abstract"; + NodeFlags[NodeFlags["Async"] = 256] = "Async"; + NodeFlags[NodeFlags["Default"] = 512] = "Default"; + NodeFlags[NodeFlags["MultiLine"] = 1024] = "MultiLine"; + NodeFlags[NodeFlags["Synthetic"] = 2048] = "Synthetic"; + NodeFlags[NodeFlags["DeclarationFile"] = 4096] = "DeclarationFile"; + NodeFlags[NodeFlags["Let"] = 8192] = "Let"; + NodeFlags[NodeFlags["Const"] = 16384] = "Const"; + NodeFlags[NodeFlags["OctalLiteral"] = 32768] = "OctalLiteral"; + NodeFlags[NodeFlags["Namespace"] = 65536] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 131072] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 262144] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 524288] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 1048576] = "HasExplicitReturn"; + NodeFlags[NodeFlags["Modifier"] = 1022] = "Modifier"; + NodeFlags[NodeFlags["AccessibilityModifier"] = 56] = "AccessibilityModifier"; + NodeFlags[NodeFlags["BlockScoped"] = 24576] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 1572864] = "ReachabilityCheckFlags"; })(ts.NodeFlags || (ts.NodeFlags = {})); var NodeFlags = ts.NodeFlags; /* @internal */ @@ -690,6 +693,12 @@ var ts; })(ts.LanguageVariant || (ts.LanguageVariant = {})); var LanguageVariant = ts.LanguageVariant; /* @internal */ + (function (DiagnosticStyle) { + DiagnosticStyle[DiagnosticStyle["Simple"] = 0] = "Simple"; + DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; + })(ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); + var DiagnosticStyle = ts.DiagnosticStyle; + /* @internal */ (function (CharacterCodes) { CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; @@ -838,40 +847,50 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(ts.Ternary || (ts.Ternary = {})); var Ternary = ts.Ternary; - function createFileMap(getCanonicalFileName) { + function createFileMap(keyMapper) { var files = {}; return { get: get, set: set, contains: contains, remove: remove, - clear: clear, - forEachValue: forEachValueInMap + forEachValue: forEachValueInMap, + clear: clear }; - function set(fileName, value) { - files[normalizeKey(fileName)] = value; - } - function get(fileName) { - return files[normalizeKey(fileName)]; - } - function contains(fileName) { - return hasProperty(files, normalizeKey(fileName)); - } - function remove(fileName) { - var key = normalizeKey(fileName); - delete files[key]; - } function forEachValueInMap(f) { - forEachValue(files, f); + for (var key in files) { + f(key, files[key]); + } } - function normalizeKey(key) { - return getCanonicalFileName(normalizeSlashes(key)); + // path should already be well-formed so it does not need to be normalized + function get(path) { + return files[toKey(path)]; + } + function set(path, value) { + files[toKey(path)] = value; + } + function contains(path) { + return hasProperty(files, toKey(path)); + } + function remove(path) { + var key = toKey(path); + delete files[key]; } function clear() { files = {}; } + function toKey(path) { + return keyMapper ? keyMapper(path) : path; + } } ts.createFileMap = createFileMap; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; (function (Comparison) { Comparison[Comparison["LessThan"] = -1] = "LessThan"; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; @@ -897,8 +916,8 @@ var ts; ts.forEach = forEach; function contains(array, value) { if (array) { - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var v = array_1[_i]; if (v === value) { return true; } @@ -921,8 +940,8 @@ var ts; function countWhere(array, predicate) { var count = 0; if (array) { - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (predicate(v)) { count++; } @@ -935,8 +954,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var item = array[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; if (f(item)) { result.push(item); } @@ -949,8 +968,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; result.push(f(v)); } } @@ -969,8 +988,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var item = array[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; if (!contains(result, item)) { result.push(item); } @@ -981,8 +1000,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -990,8 +1009,8 @@ var ts; ts.sum = sum; function addRange(to, from) { if (to && from) { - for (var _i = 0; _i < from.length; _i++) { - var v = from[_i]; + for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { + var v = from_1[_i]; to.push(v); } } @@ -1341,8 +1360,8 @@ var ts; function getNormalizedParts(normalizedSlashedPath, rootLength) { var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); var normalized = []; - for (var _i = 0; _i < parts.length; _i++) { - var part = parts[_i]; + for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { + var part = parts_1[_i]; if (part !== ".") { if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { normalized.pop(); @@ -1521,8 +1540,8 @@ var ts; if (!fileName) { return false; } - for (var _i = 0; _i < ts.supportedExtensions.length; _i++) { - var extension = ts.supportedExtensions[_i]; + for (var _i = 0, supportedExtensions_1 = ts.supportedExtensions; _i < supportedExtensions_1.length; _i++) { + var extension = supportedExtensions_1[_i]; if (fileExtensionIs(fileName, extension)) { return true; } @@ -1532,8 +1551,8 @@ var ts; ts.isSupportedSourceFileName = isSupportedSourceFileName; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { - for (var _i = 0; _i < extensionsToRemove.length; _i++) { - var ext = extensionsToRemove[_i]; + for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { + var ext = extensionsToRemove_1[_i]; if (fileExtensionIs(path, ext)) { return path.substr(0, path.length - ext.length); } @@ -1614,8 +1633,8 @@ var ts; })(Debug = ts.Debug || (ts.Debug = {})); function copyListRemovingItem(item, list) { var copiedList = []; - for (var _i = 0; _i < list.length; _i++) { - var e = list[_i]; + for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { + var e = list_1[_i]; if (e !== item) { copiedList.push(e); } @@ -1709,16 +1728,16 @@ var ts; function visitDirectory(path) { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0; _i < files.length; _i++) { - var current = files[_i]; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; var name_1 = ts.combinePaths(path, current); if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { result.push(name_1); } } var subfolders = getNames(folder.subfolders); - for (var _a = 0; _a < subfolders.length; _a++) { - var current = subfolders[_a]; + for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { + var current = subfolders_1[_a]; var name_2 = ts.combinePaths(path, current); if (!ts.contains(exclude, getCanonicalPath(name_2))) { visitDirectory(name_2); @@ -1769,6 +1788,7 @@ var ts; var _fs = require("fs"); var _path = require("path"); var _os = require("os"); + var _tty = require("tty"); // average async stat takes about 30 microseconds // set chunk size to do 30 files in < 1 millisecond function createWatchedFileSet(interval, chunkSize) { @@ -1906,8 +1926,8 @@ var ts; function visitDirectory(path) { var files = _fs.readdirSync(path || ".").sort(); var directories = []; - for (var _i = 0; _i < files.length; _i++) { - var current = files[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var current = files_2[_i]; var name_3 = ts.combinePaths(path, current); if (!ts.contains(exclude, getCanonicalPath(name_3))) { var stat = _fs.statSync(name_3); @@ -1921,8 +1941,8 @@ var ts; } } } - for (var _a = 0; _a < directories.length; _a++) { - var current = directories[_a]; + for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { + var current = directories_1[_a]; visitDirectory(current); } } @@ -1932,15 +1952,7 @@ var ts; newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, write: function (s) { - var buffer = new Buffer(s, "utf8"); - var offset = 0; - var toWrite = buffer.length; - var written = 0; - // 1 is a standard descriptor for stdout - while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) { - offset += written; - toWrite -= written; - } + process.stdout.write(s); }, readFile: readFile, writeFile: writeFile, @@ -2223,6 +2235,7 @@ var ts; await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher_1311", message: "Async functions are only available when targeting ECMAScript 6 and higher." }, can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, + The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -2275,7 +2288,7 @@ var ts; Neither_type_0_nor_type_1_is_assignable_to_the_other: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Neither_type_0_nor_type_1_is_assignable_to_the_other_2352", message: "Neither type '{0}' nor type '{1}' is assignable to the other." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, No_best_common_type_exists_among_return_expressions: { code: 2354, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_return_expressions_2354", message: "No best common type exists among return expressions." }, - A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_th_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement." }, + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, @@ -2296,7 +2309,7 @@ var ts; Duplicate_number_index_signature: { code: 2375, category: ts.DiagnosticCategory.Error, key: "Duplicate_number_index_signature_2375", message: "Duplicate number index signature." }, A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: 2376, category: ts.DiagnosticCategory.Error, key: "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", message: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." }, Constructors_for_derived_classes_must_contain_a_super_call: { code: 2377, category: ts.DiagnosticCategory.Error, key: "Constructors_for_derived_classes_must_contain_a_super_call_2377", message: "Constructors for derived classes must contain a 'super' call." }, - A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement_2378", message: "A 'get' accessor must return a value or consist of a single 'throw' statement." }, + A_get_accessor_must_return_a_value: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_2378", message: "A 'get' accessor must return a value." }, Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2379, category: ts.DiagnosticCategory.Error, key: "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", message: "Getter and setter accessors do not agree in visibility." }, get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, @@ -2586,8 +2599,6 @@ var ts; NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "NEWLINE" }, Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: ts.DiagnosticCategory.Error, key: "Argument_for_newLine_option_must_be_CRLF_or_LF_6062", message: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, Argument_for_moduleResolution_option_must_be_node_or_classic: { code: 6063, category: ts.DiagnosticCategory.Error, key: "Argument_for_moduleResolution_option_must_be_node_or_classic_6063", message: "Argument for '--moduleResolution' option must be 'node' or 'classic'." }, - Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, - Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, @@ -2595,7 +2606,14 @@ var ts; Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: ts.DiagnosticCategory.Message, key: "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", message: "Initializes a TypeScript project and creates a tsconfig.json file." }, Successfully_created_a_tsconfig_json_file: { code: 6071, category: ts.DiagnosticCategory.Message, key: "Successfully_created_a_tsconfig_json_file_6071", message: "Successfully created a tsconfig.json file." }, Suppress_excess_property_checks_for_object_literals: { code: 6072, category: ts.DiagnosticCategory.Message, key: "Suppress_excess_property_checks_for_object_literals_6072", message: "Suppress excess property checks for object literals." }, - Disallow_inconsistently_cased_references_to_the_same_file: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6073", message: "Disallow inconsistently-cased references to the same file." }, + Stylize_errors_and_messages_using_color_and_context_experimental: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Stylize_errors_and_messages_using_color_and_context_experimental_6073", message: "Stylize errors and messages using color and context. (experimental)" }, + Do_not_report_errors_on_unused_labels: { code: 6074, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unused_labels_6074", message: "Do not report errors on unused labels." }, + Report_error_when_not_all_code_paths_in_function_return_a_value: { code: 6075, category: ts.DiagnosticCategory.Message, key: "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", message: "Report error when not all code paths in function return a value." }, + Report_errors_for_fallthrough_cases_in_switch_statement: { code: 6076, category: ts.DiagnosticCategory.Message, key: "Report_errors_for_fallthrough_cases_in_switch_statement_6076", message: "Report errors for fallthrough cases in switch statement." }, + Do_not_report_errors_on_unreachable_code: { code: 6077, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unreachable_code_6077", message: "Do not report errors on unreachable code." }, + Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, + Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, + Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2613,6 +2631,10 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", message: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: ts.DiagnosticCategory.Error, key: "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", message: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." }, JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", message: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists" }, + Unreachable_code_detected: { code: 7027, category: ts.DiagnosticCategory.Error, key: "Unreachable_code_detected_7027", message: "Unreachable code detected." }, + Unused_label: { code: 7028, category: ts.DiagnosticCategory.Error, key: "Unused_label_7028", message: "Unused label." }, + Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, + Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -4166,6 +4188,20 @@ var ts; ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); var ModuleInstanceState = ts.ModuleInstanceState; + var Reachability; + (function (Reachability) { + Reachability[Reachability["Unintialized"] = 1] = "Unintialized"; + Reachability[Reachability["Reachable"] = 2] = "Reachable"; + Reachability[Reachability["Unreachable"] = 4] = "Unreachable"; + Reachability[Reachability["ReportedUnreachable"] = 8] = "ReportedUnreachable"; + })(Reachability || (Reachability = {})); + function or(state1, state2) { + return (state1 | state2) & 2 /* Reachable */ + ? 2 /* Reachable */ + : (state1 & state2) & 8 /* ReportedUnreachable */ + ? 8 /* ReportedUnreachable */ + : 4 /* Unreachable */; + } function getModuleInstanceState(node) { // A module is uninstantiated if it contains only // 1. interface declarations, type alias declarations @@ -4175,7 +4211,7 @@ var ts; else if (ts.isConstEnumDeclaration(node)) { return 2 /* ConstEnumOnly */; } - else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && !(node.flags & 1 /* Export */)) { + else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && !(node.flags & 2 /* Export */)) { return 0 /* NonInstantiated */; } else if (node.kind === 219 /* ModuleBlock */) { @@ -4226,31 +4262,56 @@ var ts; // Functions, Methods, Modules, Source-files. ContainerFlags[ContainerFlags["IsContainerWithLocals"] = 5] = "IsContainerWithLocals"; })(ContainerFlags || (ContainerFlags = {})); - function bindSourceFile(file) { + var binder = createBinder(); + function bindSourceFile(file, options) { var start = new Date().getTime(); - bindSourceFileWorker(file); + binder(file, options); ts.bindTime += new Date().getTime() - start; } ts.bindSourceFile = bindSourceFile; - function bindSourceFileWorker(file) { + function createBinder() { + var file; + var options; var parent; var container; var blockScopeContainer; var lastContainer; var seenThisKeyword; + // state used by reachability checks + var hasExplicitReturn; + var currentReachabilityState; + var labelStack; + var labelIndexMap; + var implicitLabels; // If this file is an external module, then it is automatically in strict-mode according to // ES6. If it is not an external module, then we'll determine if it is in strict mode or // not depending on if we see "use strict" in certain places (or if we hit a class/namespace). - var inStrictMode = !!file.externalModuleIndicator; + var inStrictMode; var symbolCount = 0; - var Symbol = ts.objectAllocator.getSymbolConstructor(); - var classifiableNames = {}; - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; + var Symbol; + var classifiableNames; + function bindSourceFile(f, opts) { + file = f; + options = opts; + inStrictMode = !!file.externalModuleIndicator; + classifiableNames = {}; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + hasExplicitReturn = false; + labelStack = undefined; + labelIndexMap = undefined; + implicitLabels = undefined; } - return; + return bindSourceFile; function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -4303,7 +4364,7 @@ var ts; return node.isExportEquals ? "export=" : "default"; case 213 /* FunctionDeclaration */: case 214 /* ClassDeclaration */: - return node.flags & 1024 /* Default */ ? "default" : undefined; + return node.flags & 512 /* Default */ ? "default" : undefined; } } function getDisplayName(node) { @@ -4319,7 +4380,7 @@ var ts; */ function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = node.flags & 1024 /* Default */; + var isDefaultExport = node.flags & 512 /* Default */; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; @@ -4358,7 +4419,7 @@ var ts; ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 1024 /* Default */) { + if (declaration.flags & 512 /* Default */) { message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } }); @@ -4377,7 +4438,7 @@ var ts; return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedNodeFlags(node) & 1 /* Export */; + var hasExportModifier = ts.getCombinedNodeFlags(node) & 2 /* Export */; if (symbolFlags & 8388608 /* Alias */) { if (node.kind === 230 /* ExportSpecifier */ || (node.kind === 221 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -4398,7 +4459,7 @@ var ts; // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. - if (hasExportModifier || container.flags & 262144 /* ExportContext */) { + if (hasExportModifier || container.flags & 131072 /* ExportContext */) { var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | (symbolFlags & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) | (symbolFlags & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); @@ -4453,18 +4514,229 @@ var ts; blockScopeContainer = node; blockScopeContainer.locals = undefined; } - if (node.kind === 215 /* InterfaceDeclaration */) { + var savedReachabilityState; + var savedLabelStack; + var savedLabels; + var savedImplicitLabels; + var savedHasExplicitReturn; + var kind = node.kind; + var flags = node.flags; + // reset all reachability check related flags on node (for incremental scenarios) + flags &= ~1572864 /* ReachabilityCheckFlags */; + if (kind === 215 /* InterfaceDeclaration */) { seenThisKeyword = false; - ts.forEachChild(node, bind); - node.flags = seenThisKeyword ? node.flags | 524288 /* ContainsThis */ : node.flags & ~524288 /* ContainsThis */; } - else { - ts.forEachChild(node, bind); + var saveState = kind === 248 /* SourceFile */ || kind === 219 /* ModuleBlock */ || ts.isFunctionLikeKind(kind); + if (saveState) { + savedReachabilityState = currentReachabilityState; + savedLabelStack = labelStack; + savedLabels = labelIndexMap; + savedImplicitLabels = implicitLabels; + savedHasExplicitReturn = hasExplicitReturn; + currentReachabilityState = 2 /* Reachable */; + hasExplicitReturn = false; + labelStack = labelIndexMap = implicitLabels = undefined; + } + bindReachableStatement(node); + if (currentReachabilityState === 2 /* Reachable */ && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) { + flags |= 524288 /* HasImplicitReturn */; + if (hasExplicitReturn) { + flags |= 1048576 /* HasExplicitReturn */; + } + } + if (kind === 215 /* InterfaceDeclaration */) { + flags = seenThisKeyword ? flags | 262144 /* ContainsThis */ : flags & ~262144 /* ContainsThis */; + } + node.flags = flags; + if (saveState) { + hasExplicitReturn = savedHasExplicitReturn; + currentReachabilityState = savedReachabilityState; + labelStack = savedLabelStack; + labelIndexMap = savedLabels; + implicitLabels = savedImplicitLabels; } container = saveContainer; parent = saveParent; blockScopeContainer = savedBlockScopeContainer; } + /** + * Returns true if node and its subnodes were successfully traversed. + * Returning false means that node was not examined and caller needs to dive into the node himself. + */ + function bindReachableStatement(node) { + if (checkUnreachable(node)) { + ts.forEachChild(node, bind); + return; + } + switch (node.kind) { + case 198 /* WhileStatement */: + bindWhileStatement(node); + break; + case 197 /* DoStatement */: + bindDoStatement(node); + break; + case 199 /* ForStatement */: + bindForStatement(node); + break; + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 196 /* IfStatement */: + bindIfStatement(node); + break; + case 204 /* ReturnStatement */: + case 208 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 203 /* BreakStatement */: + case 202 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 209 /* TryStatement */: + bindTryStatement(node); + break; + case 206 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 220 /* CaseBlock */: + bindCaseBlock(node); + break; + case 207 /* LabeledStatement */: + bindLabeledStatement(node); + break; + default: + ts.forEachChild(node, bind); + break; + } + } + function bindWhileStatement(n) { + var preWhileState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + var postWhileState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + // bind expressions (don't affect reachability) + bind(n.expression); + currentReachabilityState = preWhileState; + var postWhileLabel = pushImplicitLabel(); + bind(n.statement); + popImplicitLabel(postWhileLabel, postWhileState); + } + function bindDoStatement(n) { + var preDoState = currentReachabilityState; + var postDoLabel = pushImplicitLabel(); + bind(n.statement); + var postDoState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : preDoState; + popImplicitLabel(postDoLabel, postDoState); + // bind expressions (don't affect reachability) + bind(n.expression); + } + function bindForStatement(n) { + var preForState = currentReachabilityState; + var postForLabel = pushImplicitLabel(); + // bind expressions (don't affect reachability) + bind(n.initializer); + bind(n.condition); + bind(n.incrementor); + bind(n.statement); + // for statement is considered infinite when it condition is either omitted or is true keyword + // - for(..;;..) + // - for(..;true;..) + var isInfiniteLoop = (!n.condition || n.condition.kind === 99 /* TrueKeyword */); + var postForState = isInfiniteLoop ? 4 /* Unreachable */ : preForState; + popImplicitLabel(postForLabel, postForState); + } + function bindForInOrForOfStatement(n) { + var preStatementState = currentReachabilityState; + var postStatementLabel = pushImplicitLabel(); + // bind expressions (don't affect reachability) + bind(n.initializer); + bind(n.expression); + bind(n.statement); + popImplicitLabel(postStatementLabel, preStatementState); + } + function bindIfStatement(n) { + // denotes reachability state when entering 'thenStatement' part of the if statement: + // i.e. if condition is false then thenStatement is unreachable + var ifTrueState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + // denotes reachability state when entering 'elseStatement': + // i.e. if condition is true then elseStatement is unreachable + var ifFalseState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + currentReachabilityState = ifTrueState; + // bind expression (don't affect reachability) + bind(n.expression); + bind(n.thenStatement); + if (n.elseStatement) { + var preElseState = currentReachabilityState; + currentReachabilityState = ifFalseState; + bind(n.elseStatement); + currentReachabilityState = or(currentReachabilityState, preElseState); + } + else { + currentReachabilityState = or(currentReachabilityState, ifFalseState); + } + } + function bindReturnOrThrow(n) { + // bind expression (don't affect reachability) + bind(n.expression); + if (n.kind === 204 /* ReturnStatement */) { + hasExplicitReturn = true; + } + currentReachabilityState = 4 /* Unreachable */; + } + function bindBreakOrContinueStatement(n) { + // call bind on label (don't affect reachability) + bind(n.label); + // for continue case touch label so it will be marked a used + var isValidJump = jumpToLabel(n.label, n.kind === 203 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */); + if (isValidJump) { + currentReachabilityState = 4 /* Unreachable */; + } + } + function bindTryStatement(n) { + // catch\finally blocks has the same reachability as try block + var preTryState = currentReachabilityState; + bind(n.tryBlock); + var postTryState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.catchClause); + var postCatchState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.finallyBlock); + // post catch/finally state is reachable if + // - post try state is reachable - control flow can fall out of try block + // - post catch state is reachable - control flow can fall out of catch block + currentReachabilityState = or(postTryState, postCatchState); + } + function bindSwitchStatement(n) { + var preSwitchState = currentReachabilityState; + var postSwitchLabel = pushImplicitLabel(); + // bind expression (don't affect reachability) + bind(n.expression); + bind(n.caseBlock); + var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242 /* DefaultClause */; }); + // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case + var postSwitchState = hasDefault && currentReachabilityState !== 2 /* Reachable */ ? 4 /* Unreachable */ : preSwitchState; + popImplicitLabel(postSwitchLabel, postSwitchState); + } + function bindCaseBlock(n) { + var startState = currentReachabilityState; + for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + currentReachabilityState = startState; + bind(clause); + if (clause.statements.length && currentReachabilityState === 2 /* Reachable */ && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + } + function bindLabeledStatement(n) { + // call bind on label (don't affect reachability) + bind(n.label); + var ok = pushNamedLabel(n.label); + bind(n.statement); + if (ok) { + popNamedLabel(n.label, currentReachabilityState); + } + } function getContainerFlags(node) { switch (node.kind) { case 186 /* ClassExpression */: @@ -4576,7 +4848,7 @@ var ts; } } function declareClassMember(node, symbolFlags, symbolExcludes) { - return node.flags & 128 /* Static */ + return node.flags & 64 /* Static */ ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } @@ -4585,15 +4857,6 @@ var ts; ? declareModuleMember(node, symbolFlags, symbolExcludes) : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } - function isAmbientContext(node) { - while (node) { - if (node.flags & 2 /* Ambient */) { - return true; - } - node = node.parent; - } - return false; - } function hasExportDeclarations(node) { var body = node.kind === 248 /* SourceFile */ ? node : node.body; if (body.kind === 248 /* SourceFile */ || body.kind === 219 /* ModuleBlock */) { @@ -4609,11 +4872,11 @@ var ts; function setExportContextFlag(node) { // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular // declarations with export modifiers) is an export context in which declarations are implicitly exported. - if (isAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 262144 /* ExportContext */; + if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 131072 /* ExportContext */; } else { - node.flags &= ~262144 /* ExportContext */; + node.flags &= ~131072 /* ExportContext */; } } function bindModuleDeclaration(node) { @@ -4805,7 +5068,7 @@ var ts; } } function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.flags & 65536 /* OctalLiteral */) { + if (inStrictMode && node.flags & 32768 /* OctalLiteral */) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } @@ -4829,10 +5092,10 @@ var ts; function checkStrictModeWithStatement(node) { // Grammar checking for withStatement if (inStrictMode) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); } } - function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + function errorOnFirstToken(node, message, arg0, arg1, arg2) { var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } @@ -4840,6 +5103,9 @@ var ts; return "__" + ts.indexOf(node.parent.parameters, node); } function bind(node) { + if (!node) { + return; + } node.parent = parent; var savedInStrictMode = inStrictMode; if (!savedInStrictMode) { @@ -4882,8 +5148,8 @@ var ts; } } function updateStrictModeStatementList(statements) { - for (var _i = 0; _i < statements.length; _i++) { - var statement = statements[_i]; + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; if (!ts.isPrologueDirective(statement)) { return; } @@ -5105,7 +5371,7 @@ var ts; } // If this is a property-parameter, then also declare the property symbol into the // containing class. - if (node.flags & 112 /* AccessibilityModifier */ && + if (node.flags & 56 /* AccessibilityModifier */ && node.parent.kind === 144 /* Constructor */ && ts.isClassLike(node.parent.parent)) { var classDeclaration = node.parent.parent; @@ -5117,6 +5383,112 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } + // reachability checks + function pushNamedLabel(name) { + initializeReachabilityStateIfNecessary(); + if (ts.hasProperty(labelIndexMap, name.text)) { + return false; + } + labelIndexMap[name.text] = labelStack.push(1 /* Unintialized */) - 1; + return true; + } + function pushImplicitLabel() { + initializeReachabilityStateIfNecessary(); + var index = labelStack.push(1 /* Unintialized */) - 1; + implicitLabels.push(index); + return index; + } + function popNamedLabel(label, outerState) { + var index = labelIndexMap[label.text]; + ts.Debug.assert(index !== undefined); + ts.Debug.assert(labelStack.length == index + 1); + labelIndexMap[label.text] = undefined; + setCurrentStateAtLabel(labelStack.pop(), outerState, label); + } + function popImplicitLabel(implicitLabelIndex, outerState) { + if (labelStack.length !== implicitLabelIndex + 1) { + ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex); + } + var i = implicitLabels.pop(); + if (implicitLabelIndex !== i) { + ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex); + } + setCurrentStateAtLabel(labelStack.pop(), outerState, /*name*/ undefined); + } + function setCurrentStateAtLabel(innerMergedState, outerState, label) { + if (innerMergedState === 1 /* Unintialized */) { + if (label && !options.allowUnusedLabels) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label)); + } + currentReachabilityState = outerState; + } + else { + currentReachabilityState = or(innerMergedState, outerState); + } + } + function jumpToLabel(label, outerState) { + initializeReachabilityStateIfNecessary(); + var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels); + if (index === undefined) { + // reference to unknown label or + // break/continue used outside of loops + return false; + } + var stateAtLabel = labelStack[index]; + labelStack[index] = stateAtLabel === 1 /* Unintialized */ ? outerState : or(stateAtLabel, outerState); + return true; + } + function checkUnreachable(node) { + switch (currentReachabilityState) { + case 4 /* Unreachable */: + var reportError = + // report error on all statements + ts.isStatement(node) || + // report error on class declarations + node.kind === 214 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 218 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + // report error on regular enums and const enums if preserveConstEnums is set + (node.kind === 217 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + if (reportError) { + currentReachabilityState = 8 /* ReportedUnreachable */; + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var reportUnreachableCode = !options.allowUnreachableCode && + !ts.isInAmbientContext(node) && + (node.kind !== 193 /* VariableStatement */ || + ts.getCombinedNodeFlags(node.declarationList) & 24576 /* BlockScoped */ || + ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); + if (reportUnreachableCode) { + errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + } + } + case 8 /* ReportedUnreachable */: + return true; + default: + return false; + } + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); + } + } + function initializeReachabilityStateIfNecessary() { + if (labelIndexMap) { + return; + } + currentReachabilityState = 2 /* Reachable */; + labelIndexMap = {}; + labelStack = []; + implicitLabels = []; + } } })(ts || (ts = {})); /// @@ -5127,8 +5499,8 @@ var ts; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; if (declaration.kind === kind) { return declaration; } @@ -5328,7 +5700,7 @@ var ts; } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 49152 /* BlockScoped */) !== 0 || + return (getCombinedNodeFlags(declaration) & 24576 /* BlockScoped */) !== 0 || isCatchClauseVariableDeclaration(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; @@ -5441,7 +5813,7 @@ var ts; } ts.isExternalModule = isExternalModule; function isDeclarationFile(file) { - return (file.flags & 8192 /* DeclarationFile */) !== 0; + return (file.flags & 4096 /* DeclarationFile */) !== 0; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { @@ -5478,11 +5850,11 @@ var ts; } ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(getCombinedNodeFlags(node) & 32768 /* Const */); + return !!(getCombinedNodeFlags(node) & 16384 /* Const */); } ts.isConst = isConst; function isLet(node) { - return !!(getCombinedNodeFlags(node) & 16384 /* Let */); + return !!(getCombinedNodeFlags(node) & 8192 /* Let */); } ts.isLet = isLet; function isPrologueDirective(node) { @@ -5683,27 +6055,28 @@ var ts; } ts.isClassLike = isClassLike; function isFunctionLike(node) { - if (node) { - switch (node.kind) { - case 144 /* Constructor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - return true; - } - } - return false; + return node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; + function isFunctionLikeKind(kind) { + switch (kind) { + case 144 /* Constructor */: + case 173 /* FunctionExpression */: + case 213 /* FunctionDeclaration */: + case 174 /* ArrowFunction */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + case 149 /* IndexSignature */: + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + return true; + } + } + ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 143 /* MethodDeclaration */: @@ -6206,9 +6579,18 @@ var ts; return !!node && (node.kind === 162 /* ArrayBindingPattern */ || node.kind === 161 /* ObjectBindingPattern */); } ts.isBindingPattern = isBindingPattern; + function isNodeDescendentOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + ts.isNodeDescendentOf = isNodeDescendentOf; function isInAmbientContext(node) { while (node) { - if (node.flags & (2 /* Ambient */ | 8192 /* DeclarationFile */)) { + if (node.flags & (4 /* Ambient */ | 4096 /* DeclarationFile */)) { return true; } node = node.parent; @@ -6266,7 +6648,7 @@ var ts; case 207 /* LabeledStatement */: case 204 /* ReturnStatement */: case 206 /* SwitchStatement */: - case 98 /* ThrowKeyword */: + case 208 /* ThrowStatement */: case 209 /* TryStatement */: case 193 /* VariableStatement */: case 198 /* WhileStatement */: @@ -6379,8 +6761,8 @@ var ts; ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; function getHeritageClause(clauses, kind) { if (clauses) { - for (var _i = 0; _i < clauses.length; _i++) { - var clause = clauses[_i]; + for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { + var clause = clauses_1[_i]; if (clause.token === kind) { return clause; } @@ -6392,7 +6774,6 @@ var ts; function tryResolveScriptReference(host, sourceFile, reference) { if (!host.getCompilerOptions().noResolve) { var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); - referenceFileName = ts.getNormalizedAbsolutePath(referenceFileName, host.getCurrentDirectory()); return host.getSourceFile(referenceFileName); } } @@ -6450,7 +6831,7 @@ var ts; } ts.isTrivia = isTrivia; function isAsyncFunctionLike(node) { - return isFunctionLike(node) && (node.flags & 512 /* Async */) !== 0 && !isAccessor(node); + return isFunctionLike(node) && (node.flags & 256 /* Async */) !== 0 && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; /** @@ -6837,7 +7218,7 @@ var ts; else { ts.forEach(declarations, function (member) { if ((member.kind === 145 /* GetAccessor */ || member.kind === 146 /* SetAccessor */) - && (member.flags & 128 /* Static */) === (accessor.flags & 128 /* Static */)) { + && (member.flags & 64 /* Static */) === (accessor.flags & 64 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -6894,6 +7275,66 @@ var ts; }); } ts.emitComments = emitComments; + /** + * Detached comment is a comment at the top of file or function body that is separated from + * the next statement by space. + */ + function emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, removeComments) { + var leadingComments; + var currentDetachedCommentInfo; + if (removeComments) { + // removeComments is true, only reserve pinned comment at the top of file + // For example: + // /*! Pinned Comment */ + // + // var x = 10; + if (node.pos === 0) { + leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment); + } + } + else { + // removeComments is false, just get detached as normal and bypass the process to filter comment + leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment; + for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { + var comment = leadingComments_1[_i]; + if (lastComment) { + var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); + var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); + if (commentLine >= lastCommentLine + 2) { + // There was a blank line between the last comment and this comment. This + // comment is not part of the copyright comments. Return what we have so + // far. + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + // All comments look like they could have been part of the copyright header. Make + // sure there is at least one blank line between it and the node. If not, it's not + // a copyright header. + var lastCommentLine = getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); + var nodeLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + // Valid detachedComments + emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedComment(comment) { + return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + } + } + ts.emitDetachedComments = emitDetachedComments; function writeCommentRange(currentSourceFile, writer, comment, newLine) { if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { var firstCommentLineAndCharacter = ts.getLineAndCharacterOfPosition(currentSourceFile, comment.pos); @@ -6983,16 +7424,16 @@ var ts; ts.writeCommentRange = writeCommentRange; function modifierToFlag(token) { switch (token) { - case 113 /* StaticKeyword */: return 128 /* Static */; - case 112 /* PublicKeyword */: return 16 /* Public */; - case 111 /* ProtectedKeyword */: return 64 /* Protected */; - case 110 /* PrivateKeyword */: return 32 /* Private */; - case 115 /* AbstractKeyword */: return 256 /* Abstract */; - case 82 /* ExportKeyword */: return 1 /* Export */; - case 122 /* DeclareKeyword */: return 2 /* Ambient */; - case 74 /* ConstKeyword */: return 32768 /* Const */; - case 77 /* DefaultKeyword */: return 1024 /* Default */; - case 118 /* AsyncKeyword */: return 512 /* Async */; + case 113 /* StaticKeyword */: return 64 /* Static */; + case 112 /* PublicKeyword */: return 8 /* Public */; + case 111 /* ProtectedKeyword */: return 32 /* Protected */; + case 110 /* PrivateKeyword */: return 16 /* Private */; + case 115 /* AbstractKeyword */: return 128 /* Abstract */; + case 82 /* ExportKeyword */: return 2 /* Export */; + case 122 /* DeclareKeyword */: return 4 /* Ambient */; + case 74 /* ConstKeyword */: return 16384 /* Const */; + case 77 /* DefaultKeyword */: return 512 /* Default */; + case 118 /* AsyncKeyword */: return 256 /* Async */; } return 0; } @@ -7073,7 +7514,7 @@ var ts; } ts.isEmptyObjectLiteralOrArrayLiteral = isEmptyObjectLiteralOrArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 1024 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; + return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function isJavaScript(fileName) { @@ -7150,6 +7591,12 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !ts.isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false); + } + ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -7414,8 +7861,8 @@ var ts; } function visitEachNode(cbNode, nodes) { if (nodes) { - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; var result = cbNode(node); if (result) { return result; @@ -7982,8 +8429,8 @@ var ts; function addJSDocComment(node) { var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); if (comments) { - for (var _i = 0; _i < comments.length; _i++) { - var comment = comments[_i]; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); if (jsDocComment) { node.jsDocComment = jsDocComment; @@ -8021,7 +8468,7 @@ var ts; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); - sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 8192 /* DeclarationFile */ : 0; + sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 /* DeclarationFile */ : 0; sourceFile.languageVariant = ts.isTsx(sourceFile.fileName) ? 1 /* JSX */ : 0 /* Standard */; return sourceFile; } @@ -9079,7 +9526,7 @@ var ts; if (node.kind === 8 /* NumericLiteral */ && sourceText.charCodeAt(tokenPos) === 48 /* _0 */ && ts.isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { - node.flags |= 65536 /* OctalLiteral */; + node.flags |= 32768 /* OctalLiteral */; } return node; } @@ -9832,7 +10279,7 @@ var ts; // Didn't appear to actually be a parenthesized arrow function. Just bail out. return undefined; } - var isAsync = !!(arrowFunction.flags & 512 /* Async */); + var isAsync = !!(arrowFunction.flags & 256 /* Async */); // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. var lastToken = token; @@ -9959,7 +10406,7 @@ var ts; function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(174 /* ArrowFunction */); setModifiers(node, parseModifiersForArrowFunction()); - var isAsync = !!(node.flags & 512 /* Async */); + var isAsync = !!(node.flags & 256 /* Async */); // Arrow functions are never generators. // // If we're speculatively parsing a signature for a parenthesized arrow function, then @@ -10802,7 +11249,7 @@ var ts; var node = createNode(164 /* ArrayLiteralExpression */); parseExpected(19 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) - node.flags |= 2048 /* MultiLine */; + node.flags |= 1024 /* MultiLine */; node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); parseExpected(20 /* CloseBracketToken */); return finishNode(node); @@ -10863,7 +11310,7 @@ var ts; var node = createNode(165 /* ObjectLiteralExpression */); parseExpected(15 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { - node.flags |= 2048 /* MultiLine */; + node.flags |= 1024 /* MultiLine */; } node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimeter*/ true); parseExpected(16 /* CloseBraceToken */); @@ -10884,7 +11331,7 @@ var ts; parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 512 /* Async */); + var isAsync = !!(node.flags & 256 /* Async */); node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -11476,10 +11923,10 @@ var ts; case 102 /* VarKeyword */: break; case 108 /* LetKeyword */: - node.flags |= 16384 /* Let */; + node.flags |= 8192 /* Let */; break; case 74 /* ConstKeyword */: - node.flags |= 32768 /* Const */; + node.flags |= 16384 /* Const */; break; default: ts.Debug.fail(); @@ -11522,9 +11969,9 @@ var ts; setModifiers(node, modifiers); parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); - node.name = node.flags & 1024 /* Default */ ? parseOptionalIdentifier() : parseIdentifier(); + node.name = node.flags & 512 /* Default */ ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 512 /* Async */); + var isAsync = !!(node.flags & 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return finishNode(node); @@ -11546,7 +11993,7 @@ var ts; method.name = name; method.questionToken = questionToken; var isGenerator = !!asteriskToken; - var isAsync = !!(method.flags & 512 /* Async */); + var isAsync = !!(method.flags & 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return finishNode(method); @@ -11567,7 +12014,7 @@ var ts; // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initialiser_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. - property.initializer = modifiers && modifiers.flags & 128 /* Static */ + property.initializer = modifiers && modifiers.flags & 64 /* Static */ ? allowInAnd(parseNonParameterInitializer) : doOutsideOfContext(2 /* Yield */ | 1 /* DisallowIn */, parseNonParameterInitializer); parseSemicolon(); @@ -11900,13 +12347,13 @@ var ts; var node = createNode(218 /* ModuleDeclaration */, fullStart); // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. - var namespaceFlag = flags & 131072 /* Namespace */; + var namespaceFlag = flags & 65536 /* Namespace */; node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(21 /* DotToken */) - ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 1 /* Export */ | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 2 /* Export */ | namespaceFlag) : parseModuleBlock(); return finishNode(node); } @@ -11921,7 +12368,7 @@ var ts; function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; if (parseOptional(126 /* NamespaceKeyword */)) { - flags |= 131072 /* Namespace */; + flags |= 65536 /* Namespace */; } else { parseExpected(125 /* ModuleKeyword */); @@ -12179,7 +12626,7 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return node.flags & 1 /* Export */ + return node.flags & 2 /* Export */ || node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 232 /* ExternalModuleReference */ || node.kind === 222 /* ImportDeclaration */ || node.kind === 227 /* ExportAssignment */ @@ -12868,8 +13315,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0; _i < array.length; _i++) { - var node = array[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var node = array_7[_i]; visitNode(node); } } @@ -13006,8 +13453,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0; _i < array.length; _i++) { - var node = array[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } return; @@ -13374,6 +13821,7 @@ var ts; var getInstantiatedGlobalPromiseLikeType; var getGlobalPromiseConstructorLikeType; var getGlobalThenableType; + var jsxElementClassType; var tupleTypes = {}; var unionTypes = {}; var intersectionTypes = {}; @@ -13643,7 +14091,7 @@ var ts; } var initializerOfNonStaticProperty = current.parent && current.parent.kind === 141 /* PropertyDeclaration */ && - (current.parent.flags & 128 /* Static */) === 0 && + (current.parent.flags & 64 /* Static */) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -13725,7 +14173,7 @@ var ts; // local variables of the constructor. This effectively means that entities from outer scopes // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. - if (ts.isClassLike(location.parent) && !(location.flags & 128 /* Static */)) { + if (ts.isClassLike(location.parent) && !(location.flags & 64 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { @@ -13739,7 +14187,7 @@ var ts; case 186 /* ClassExpression */: case 215 /* InterfaceDeclaration */: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { - if (lastLocation && lastLocation.flags & 128 /* Static */) { + if (lastLocation && lastLocation.flags & 64 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 // The scope of a type parameter extends over the entire declaration with which the type // parameter list is associated, with the exception of static member declarations in classes. @@ -14267,8 +14715,8 @@ var ts; } function findConstructorDeclaration(node) { var members = node.members; - for (var _i = 0; _i < members.length; _i++) { - var member = members[_i]; + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var member = members_1[_i]; if (member.kind === 144 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } @@ -14515,7 +14963,7 @@ var ts; // because these kind of aliases can be used to name types in declaration file var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 1 /* Export */) && + !(anyImportSyntax.flags & 2 /* Export */) && isDeclarationVisible(anyImportSyntax.parent)) { getNodeLinks(declaration).isVisible = true; if (aliasesToMakeVisible) { @@ -14669,8 +15117,8 @@ var ts; walkSymbol(getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol), getQualifiedLeftMeaning(meaning)); } if (accessibleSymbolChain) { - for (var _i = 0; _i < accessibleSymbolChain.length; _i++) { - var accessibleSymbol = accessibleSymbolChain[_i]; + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } @@ -14860,7 +15308,7 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 128 /* Static */; })); + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 64 /* Static */; })); var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { @@ -14971,8 +15419,8 @@ var ts; var t = getTypeOfSymbol(p); if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { var signatures = getSignaturesOfType(t, 0 /* Call */); - for (var _f = 0; _f < signatures.length; _f++) { - var signature = signatures[_f]; + for (var _f = 0, signatures_1 = signatures; _f < signatures_1.length; _f++) { + var signature = signatures_1[_f]; buildSymbolDisplay(p, writer); if (p.flags & 536870912 /* Optional */) { writePunctuation(writer, 53 /* QuestionToken */); @@ -15186,7 +15634,7 @@ var ts; case 221 /* ImportEqualsDeclaration */: var parent_4 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) - if (!(ts.getCombinedNodeFlags(node) & 1 /* Export */) && + if (!(ts.getCombinedNodeFlags(node) & 2 /* Export */) && !(node.kind !== 221 /* ImportEqualsDeclaration */ && parent_4.kind !== 248 /* SourceFile */ && ts.isInAmbientContext(parent_4))) { return isGlobalSourceFile(parent_4); } @@ -15198,7 +15646,7 @@ var ts; case 146 /* SetAccessor */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - if (node.flags & (32 /* Private */ | 64 /* Protected */)) { + if (node.flags & (16 /* Private */ | 32 /* Protected */)) { // Private/protected properties/methods are not visible return false; } @@ -15728,8 +16176,8 @@ var ts; // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set // in-place and returns the same array. function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); if (!typeParameters) { typeParameters = [tp]; @@ -15934,13 +16382,13 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 215 /* InterfaceDeclaration */) { - if (declaration.flags & 524288 /* ContainsThis */) { + if (declaration.flags & 262144 /* ContainsThis */) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { - for (var _b = 0; _b < baseTypeNodes.length; _b++) { - var node = baseTypeNodes[_b]; + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; if (ts.isSupportedExpressionWithTypeArguments(node)) { var baseSymbol = resolveEntityName(node.expression, 793056 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { @@ -16130,8 +16578,8 @@ var ts; } function createSymbolTable(symbols) { var result = {}; - for (var _i = 0; _i < symbols.length; _i++) { - var symbol = symbols[_i]; + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; result[symbol.name] = symbol; } return result; @@ -16140,15 +16588,15 @@ var ts; // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { var result = {}; - for (var _i = 0; _i < symbols.length; _i++) { - var symbol = symbols[_i]; + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); } return result; } function addInheritedMembers(symbols, baseSymbols) { - for (var _i = 0; _i < baseSymbols.length; _i++) { - var s = baseSymbols[_i]; + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; if (!ts.hasProperty(symbols, s.name)) { symbols[s.name] = s; } @@ -16156,8 +16604,8 @@ var ts; } function addInheritedSignatures(signatures, baseSignatures) { if (baseSignatures) { - for (var _i = 0; _i < baseSignatures.length; _i++) { - var signature = baseSignatures[_i]; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var signature = baseSignatures_1[_i]; signatures.push(signature); } } @@ -16200,8 +16648,8 @@ var ts; members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); - for (var _i = 0; _i < baseTypes.length; _i++) { - var baseType = baseTypes[_i]; + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); @@ -16247,8 +16695,8 @@ var ts; var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; - for (var _i = 0; _i < baseSignatures.length; _i++) { - var baseSig = baseSignatures[_i]; + for (var _i = 0, baseSignatures_2 = baseSignatures; _i < baseSignatures_2.length; _i++) { + var baseSig = baseSignatures_2[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); @@ -16277,8 +16725,8 @@ var ts; setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); } function findMatchingSignature(signatureList, signature, partialMatch, ignoreReturnTypes) { - for (var _i = 0; _i < signatureList.length; _i++) { - var s = signatureList[_i]; + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { return s; } @@ -16342,8 +16790,8 @@ var ts; } function getUnionIndexType(types, kind) { var indexTypes = []; - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexType = getIndexTypeOfType(type, kind); if (!indexType) { return undefined; @@ -16522,12 +16970,12 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (32 /* Private */ | 64 /* Protected */))) { + if (prop && !(getDeclarationFlagsFromSymbol(prop) & (16 /* Private */ | 32 /* Protected */))) { if (!props) { props = [prop]; } @@ -16549,8 +16997,8 @@ var ts; } var propTypes = []; var declarations = []; - for (var _a = 0; _a < props.length; _a++) { - var prop = props[_a]; + for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { + var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } @@ -16908,8 +17356,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types) { var result = 0; - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type = types_3[_i]; result |= type.flags; } return result & 14680064 /* PropagatingFlags */; @@ -17059,8 +17507,8 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; switch (declaration.kind) { case 214 /* ClassDeclaration */: case 215 /* InterfaceDeclaration */: @@ -17170,8 +17618,8 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToSet(typeSet, types, typeSetKind) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; addTypeToSet(typeSet, type, typeSetKind); } } @@ -17193,8 +17641,8 @@ var ts; } } function containsTypeAny(types) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (isTypeAny(type)) { return true; } @@ -17310,7 +17758,8 @@ var ts; var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 215 /* InterfaceDeclaration */)) { - if (!(container.flags & 128 /* Static */)) { + if (!(container.flags & 64 /* Static */) && + (container.kind !== 144 /* Constructor */ || ts.isNodeDescendentOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -17377,8 +17826,8 @@ var ts; function instantiateList(items, mapper, instantiator) { if (items && items.length) { var result = []; - for (var _i = 0; _i < items.length; _i++) { - var v = items[_i]; + for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { + var v = items_1[_i]; result.push(instantiator(v, mapper)); } return result; @@ -17417,8 +17866,8 @@ var ts; case 2: return createBinaryTypeEraser(sources[0], sources[1]); } return function (t) { - for (var _i = 0; _i < sources.length; _i++) { - var source = sources[_i]; + for (var _i = 0, sources_1 = sources; _i < sources_1.length; _i++) { + var source = sources_1[_i]; if (t === source) { return anyType; } @@ -17836,8 +18285,8 @@ var ts; function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; - for (var _i = 0; _i < sourceTypes.length; _i++) { - var sourceType = sourceTypes[_i]; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; var related = typeRelatedToSomeType(sourceType, target, false); if (!related) { return 0 /* False */; @@ -17859,8 +18308,8 @@ var ts; function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; var targetTypes = target.types; - for (var _i = 0; _i < targetTypes.length; _i++) { - var targetType = targetTypes[_i]; + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var targetType = targetTypes_1[_i]; var related = isRelatedTo(source, targetType, reportErrors); if (!related) { return 0 /* False */; @@ -17882,8 +18331,8 @@ var ts; function eachTypeRelatedToType(source, target, reportErrors) { var result = -1 /* True */; var sourceTypes = source.types; - for (var _i = 0; _i < sourceTypes.length; _i++) { - var sourceType = sourceTypes[_i]; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; var related = isRelatedTo(sourceType, target, reportErrors); if (!related) { return 0 /* False */; @@ -18008,8 +18457,8 @@ var ts; var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288 /* ObjectLiteral */); - for (var _i = 0; _i < properties.length; _i++) { - var targetProp = properties[_i]; + for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { + var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -18023,20 +18472,20 @@ var ts; else if (!(targetProp.flags & 134217728 /* Prototype */)) { var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); - if (sourcePropFlags & 32 /* Private */ || targetPropFlags & 32 /* Private */) { + if (sourcePropFlags & 16 /* Private */ || targetPropFlags & 16 /* Private */) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { - if (sourcePropFlags & 32 /* Private */ && targetPropFlags & 32 /* Private */) { + if (sourcePropFlags & 16 /* Private */ && targetPropFlags & 16 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); } else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 32 /* Private */ ? source : target), typeToString(sourcePropFlags & 32 /* Private */ ? target : source)); + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 16 /* Private */ ? source : target), typeToString(sourcePropFlags & 16 /* Private */ ? target : source)); } } return 0 /* False */; } } - else if (targetPropFlags & 64 /* Protected */) { + else if (targetPropFlags & 32 /* Protected */) { var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32 /* Class */; var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; var targetClass = getDeclaredTypeOfSymbol(targetProp.parent); @@ -18047,7 +18496,7 @@ var ts; return 0 /* False */; } } - else if (sourcePropFlags & 64 /* Protected */) { + else if (sourcePropFlags & 32 /* Protected */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -18089,8 +18538,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var _i = 0; _i < sourceProperties.length; _i++) { - var sourceProp = sourceProperties[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return 0 /* False */; @@ -18130,13 +18579,13 @@ var ts; return result; } } - outer: for (var _i = 0; _i < targetSignatures.length; _i++) { - var t = targetSignatures[_i]; + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; if (!t.hasStringLiterals || target.flags & 262144 /* FromSignature */) { var localErrors = reportErrors; var checkedAbstractAssignability = false; - for (var _a = 0; _a < sourceSignatures.length; _a++) { - var s = sourceSignatures[_a]; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; if (!s.hasStringLiterals || source.flags & 262144 /* FromSignature */) { var related = signatureRelatedTo(s, t, localErrors); if (related) { @@ -18167,8 +18616,8 @@ var ts; var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 256 /* Abstract */; - var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 256 /* Abstract */; + var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 128 /* Abstract */; + var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 128 /* Abstract */; if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { // if target isn't a class-declaration type, then it can be new'd, so we forbid the assignment. if (reportErrors) { @@ -18284,7 +18733,7 @@ var ts; var targetType = getIndexTypeOfType(target, 0 /* String */); if (targetType) { if ((targetType.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */)) { - // non-primitive assignment to any is always allowed, eg + // non-primitive assignment to any is always allowed, eg // `var x: { [index: string]: any } = { property: 12 };` return -1 /* True */; } @@ -18313,7 +18762,7 @@ var ts; var targetType = getIndexTypeOfType(target, 1 /* Number */); if (targetType) { if ((targetType.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */)) { - // non-primitive assignment to any is always allowed, eg + // non-primitive assignment to any is always allowed, eg // `var x: { [index: number]: any } = { property: 12 };` return -1 /* True */; } @@ -18386,8 +18835,8 @@ var ts; if (sourceProp === targetProp) { return -1 /* True */; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (32 /* Private */ | 64 /* Protected */); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (32 /* Private */ | 64 /* Protected */); + var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (16 /* Private */ | 32 /* Protected */); + var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (16 /* Private */ | 32 /* Protected */); if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -18455,8 +18904,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; if (candidate !== type && !isTypeSubtypeOf(type, candidate)) return false; } @@ -18692,8 +19141,8 @@ var ts; } function createInferenceContext(typeParameters, inferUnionTypes) { var inferences = []; - for (var _i = 0; _i < typeParameters.length; _i++) { - var unused = typeParameters[_i]; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var unused = typeParameters_1[_i]; inferences.push({ primary: undefined, secondary: undefined, isFixed: false }); @@ -18774,8 +19223,8 @@ var ts; var typeParameterCount = 0; var typeParameter; // First infer to each type in union or intersection that isn't a type parameter - for (var _i = 0; _i < targetTypes.length; _i++) { - var t = targetTypes[_i]; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var t = targetTypes_2[_i]; if (t.flags & 512 /* TypeParameter */ && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; @@ -18797,8 +19246,8 @@ var ts; else if (source.flags & 49152 /* UnionOrIntersection */) { // Source is a union or intersection type, infer from each consituent type var sourceTypes = source.types; - for (var _a = 0; _a < sourceTypes.length; _a++) { - var sourceType = sourceTypes[_a]; + for (var _a = 0, sourceTypes_3 = sourceTypes; _a < sourceTypes_3.length; _a++) { + var sourceType = sourceTypes_3[_a]; inferFromTypes(sourceType, target); } } @@ -18832,8 +19281,8 @@ var ts; } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0; _i < properties.length; _i++) { - var targetProp = properties[_i]; + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var targetProp = properties_2[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -19324,9 +19773,9 @@ var ts; symbol.valueDeclaration.parent.kind === 244 /* CatchClause */) { return; } - // 1. walk from the use site up to the declaration and check + // 1. walk from the use site up to the declaration and check // if there is anything function like between declaration and use-site (is binding/class is captured in function). - // 2. walk from the declaration up to the boundary of lexical environment and check + // 2. walk from the declaration up to the boundary of lexical environment and check // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) var container; if (symbol.flags & 32 /* Class */) { @@ -19398,7 +19847,7 @@ var ts; break; case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - if (container.flags & 128 /* Static */) { + if (container.flags & 64 /* Static */) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; @@ -19411,7 +19860,7 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - return container.flags & 128 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return container.flags & 64 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; } return anyType; } @@ -19441,7 +19890,7 @@ var ts; var nodeCheckFlag = 0; // always set NodeCheckFlags for 'super' expression node if (canUseSuperExpression) { - if ((container.flags & 128 /* Static */) || isCallExpression) { + if ((container.flags & 64 /* Static */) || isCallExpression) { nodeCheckFlag = 512 /* SuperStatic */; } else { @@ -19497,7 +19946,7 @@ var ts; // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration if (container && ts.isClassLike(container.parent)) { - if (container.flags & 128 /* Static */) { + if (container.flags & 64 /* Static */) { return container.kind === 143 /* MethodDeclaration */ || container.kind === 142 /* MethodSignature */ || container.kind === 145 /* GetAccessor */ || @@ -19654,8 +20103,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var current = types_7[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -19845,8 +20294,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -19926,8 +20375,8 @@ var ts; var hasSpreadElement = false; var elementTypes = []; var inDestructuringPattern = isAssignmentTarget(node); - for (var _i = 0; _i < elements.length; _i++) { - var e = elements[_i]; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var e = elements_1[_i]; if (inDestructuringPattern && e.kind === 185 /* SpreadElementExpression */) { // Given the following situation: // var c: {}; @@ -20259,8 +20708,8 @@ var ts; function checkJsxSpreadAttribute(node, elementAttributesType, nameTable) { var type = checkExpression(node.expression); var props = getPropertiesOfType(type); - for (var _i = 0; _i < props.length; _i++) { - var prop = props[_i]; + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; // Is there a corresponding property in the element attributes type? Skip checking of properties // that have already been assigned to, as these are not actually pushed into the resulting type if (!nameTable[prop.name]) { @@ -20479,7 +20928,6 @@ var ts; var prop = getPropertyOfType(attributesType, attrib.name.text); return prop || unknownSymbol; } - var jsxElementClassType = undefined; function getJsxGlobalElementClassType() { if (!jsxElementClassType) { jsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); @@ -20558,7 +21006,7 @@ var ts; return s.valueDeclaration ? s.valueDeclaration.kind : 141 /* PropertyDeclaration */; } function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 16 /* Public */ | 128 /* Static */ : 0; + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 8 /* Public */ | 64 /* Static */ : 0; } /** * Check whether the requested property access is valid. @@ -20588,7 +21036,7 @@ var ts; error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } - if (flags & 256 /* Abstract */) { + if (flags & 128 /* Abstract */) { // A method cannot be accessed in a super property access if the method is abstract. // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an @@ -20598,7 +21046,7 @@ var ts; } } // Public properties are otherwise accessible. - if (!(flags & (32 /* Private */ | 64 /* Protected */))) { + if (!(flags & (16 /* Private */ | 32 /* Protected */))) { return true; } // Property is known to be private or protected at this point @@ -20606,7 +21054,7 @@ var ts; var enclosingClassDeclaration = ts.getContainingClass(node); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; // Private property is accessible if declaring and enclosing class are the same - if (flags & 32 /* Private */) { + if (flags & 16 /* Private */) { if (declaringClass !== enclosingClass) { error(node, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); return false; @@ -20624,7 +21072,7 @@ var ts; return false; } // No further restrictions for static properties - if (flags & 128 /* Static */) { + if (flags & 64 /* Static */) { return true; } // An instance property must be accessed through an instance of the enclosing class @@ -20851,8 +21299,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0; _i < signatures.length; _i++) { - var signature = signatures[_i]; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent_5 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -21494,8 +21942,8 @@ var ts; // declare function f(a: { xa: number; xb: number; }); // f({ | if (!produceDiagnostics) { - for (var _i = 0; _i < candidates.length; _i++) { - var candidate = candidates[_i]; + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -21514,8 +21962,8 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); } function chooseOverload(candidates, relation) { - for (var _i = 0; _i < candidates.length; _i++) { - var originalCandidate = candidates[_i]; + for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { + var originalCandidate = candidates_2[_i]; if (!hasCorrectArity(node, args, originalCandidate)) { continue; } @@ -21652,7 +22100,7 @@ var ts; // In the case of a merged class-module or class-interface declaration, // only the class declaration node will have the Abstract flag set. var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && valueDecl.flags & 256 /* Abstract */) { + if (valueDecl && valueDecl.flags & 128 /* Abstract */) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); return resolveErrorCall(node); } @@ -22017,19 +22465,11 @@ var ts; }); return aggregatedTypes; } - function bodyContainsAReturnStatement(funcBody) { - return ts.forEachReturnStatement(funcBody, function (returnStatement) { - return true; - }); - } - function bodyContainsSingleThrowStatement(body) { - return (body.statements.length === 1) && (body.statements[0].kind === 208 /* ThrowStatement */); - } // TypeScript Specification 1.0 (6.3) - July 2014 // An explicitly typed function whose return type isn't the Void or the Any type // must have at least one return statement somewhere in its body. // An exception to this rule is if the function implementation consists of a single 'throw' statement. - function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func, returnType) { + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { if (!produceDiagnostics) { return; } @@ -22038,22 +22478,19 @@ var ts; return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 /* Block */) { + // also if HasImplicitReturnValue flags is not set this means that all codepaths in function body end with return of throw + if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 /* Block */ || !(func.flags & 524288 /* HasImplicitReturn */)) { return; } - var bodyBlock = func.body; - // Ensure the body has at least one return expression. - if (bodyContainsAReturnStatement(bodyBlock)) { - return; + if (func.flags & 1048576 /* HasExplicitReturn */) { + if (compilerOptions.noImplicitReturns) { + error(func.type, ts.Diagnostics.Not_all_code_paths_return_a_value); + } } - // If there are no return expressions, then we need to check if - // the function body consists solely of a throw statement; - // this is to make an exception for unimplemented functions. - if (bodyContainsSingleThrowStatement(bodyBlock)) { - return; + else { + // This function does not conform to the specification. + error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } - // This function does not conform to the specification. - error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement); } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); @@ -22120,7 +22557,7 @@ var ts; promisedType = checkAsyncFunctionReturnType(node); } if (returnType && !node.asteriskToken) { - checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); } if (node.body) { if (!node.type) { @@ -22205,7 +22642,7 @@ var ts; case 69 /* Identifier */: case 166 /* PropertyAccessExpression */: { var symbol = findSymbol(n); - return symbol && (symbol.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 32768 /* Const */) !== 0; + return symbol && (symbol.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 16384 /* Const */) !== 0; } case 167 /* ElementAccessExpression */: { var index = n.argumentExpression; @@ -22213,7 +22650,7 @@ var ts; if (symbol && index && index.kind === 9 /* StringLiteral */) { var name_12 = index.text; var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_12); - return prop && (prop.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 32768 /* Const */) !== 0; + return prop && (prop.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 16384 /* Const */) !== 0; } return false; } @@ -22298,8 +22735,8 @@ var ts; } if (type.flags & 49152 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; if (current.flags & kind) { return true; } @@ -22315,8 +22752,8 @@ var ts; } if (type.flags & 49152 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var current = types_10[_i]; if (!(current.flags & kind)) { return false; } @@ -22361,8 +22798,8 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { var properties = node.properties; - for (var _i = 0; _i < properties.length; _i++) { - var p = properties[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var p = properties_3[_i]; if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { // TODO(andersh): Computed property support var name_13 = p.name; @@ -22896,7 +23333,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 112 /* AccessibilityModifier */) { + if (node.flags & 56 /* AccessibilityModifier */) { func = ts.getContainingFunction(node); if (!(func.kind === 144 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -23096,7 +23533,7 @@ var ts; checkFunctionLikeDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (node.flags & 256 /* Abstract */ && node.body) { + if (node.flags & 128 /* Abstract */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -23147,7 +23584,7 @@ var ts; } function isInstancePropertyWithInitializer(n) { return n.kind === 141 /* PropertyDeclaration */ && - !(n.flags & 128 /* Static */) && + !(n.flags & 64 /* Static */) && !!n.initializer; } // TS 1.0 spec (April 2014): 8.3.2 @@ -23168,14 +23605,14 @@ var ts; // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return p.flags & (16 /* Public */ | 32 /* Private */ | 64 /* Protected */); }); + ts.forEach(node.parameters, function (p) { return p.flags & (8 /* Public */ | 16 /* Private */ | 32 /* Protected */); }); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement; - for (var _i = 0; _i < statements.length; _i++) { - var statement = statements[_i]; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; if (statement.kind === 195 /* ExpressionStatement */ && isSuperCallExpression(statement.expression)) { superCallStatement = statement; break; @@ -23203,8 +23640,15 @@ var ts; // Grammar checking accessors checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); if (node.kind === 145 /* GetAccessor */) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { - error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 524288 /* HasImplicitReturn */)) { + if (node.flags & 1048576 /* HasExplicitReturn */) { + if (compilerOptions.noImplicitReturns) { + error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + else { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } } } if (!ts.hasDynamicName(node)) { @@ -23213,7 +23657,7 @@ var ts; var otherKind = node.kind === 145 /* GetAccessor */ ? 146 /* SetAccessor */ : 145 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 112 /* AccessibilityModifier */) !== (otherAccessor.flags & 112 /* AccessibilityModifier */))) { + if (((node.flags & 56 /* AccessibilityModifier */) !== (otherAccessor.flags & 56 /* AccessibilityModifier */))) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } var currentAccessorType = getAnnotatedAccessorType(node); @@ -23284,7 +23728,7 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 32 /* Private */) && ts.isInAmbientContext(node); + return (node.flags & 16 /* Private */) && ts.isInAmbientContext(node); } function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { if (!produceDiagnostics) { @@ -23316,8 +23760,8 @@ var ts; else { signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); } - for (var _i = 0; _i < signaturesToCheck.length; _i++) { - var otherSignature = signaturesToCheck[_i]; + for (var _i = 0, signaturesToCheck_1 = signaturesToCheck; _i < signaturesToCheck_1.length; _i++) { + var otherSignature = signaturesToCheck_1[_i]; if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { return; } @@ -23332,11 +23776,11 @@ var ts; n.parent.kind !== 214 /* ClassDeclaration */ && n.parent.kind !== 186 /* ClassExpression */ && ts.isInAmbientContext(n)) { - if (!(flags & 2 /* Ambient */)) { + if (!(flags & 4 /* Ambient */)) { // It is nested in an ambient context, which means it is automatically exported - flags |= 1 /* Export */; + flags |= 2 /* Export */; } - flags |= 2 /* Ambient */; + flags |= 4 /* Ambient */; } return flags & flagsToCheck; } @@ -23361,16 +23805,16 @@ var ts; var canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; - if (deviation & 1 /* Export */) { + if (deviation & 2 /* Export */) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); } - else if (deviation & 2 /* Ambient */) { + else if (deviation & 4 /* Ambient */) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } - else if (deviation & (32 /* Private */ | 64 /* Protected */)) { + else if (deviation & (16 /* Private */ | 32 /* Protected */)) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } - else if (deviation & 256 /* Abstract */) { + else if (deviation & 128 /* Abstract */) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_not_abstract); } }); @@ -23387,7 +23831,7 @@ var ts; }); } } - var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 32 /* Private */ | 64 /* Protected */ | 256 /* Abstract */; + var flagsToCheck = 2 /* Export */ | 4 /* Ambient */ | 16 /* Private */ | 32 /* Protected */ | 128 /* Abstract */; var someNodeFlags = 0; var allNodeFlags = flagsToCheck; var someHaveQuestionToken = false; @@ -23418,8 +23862,8 @@ var ts; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { // the only situation when this is possible (same kind\same name but different symbol) - mixed static and instance class members ts.Debug.assert(node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */); - ts.Debug.assert((node.flags & 128 /* Static */) !== (subsequentNode.flags & 128 /* Static */)); - var diagnostic = node.flags & 128 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + ts.Debug.assert((node.flags & 64 /* Static */) !== (subsequentNode.flags & 64 /* Static */)); + var diagnostic = node.flags & 64 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); return; } @@ -23436,7 +23880,7 @@ var ts; else { // Report different errors regarding non-consecutive blocks of declarations depending on whether // the node in question is abstract. - if (node.flags & 256 /* Abstract */) { + if (node.flags & 128 /* Abstract */) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -23449,8 +23893,8 @@ var ts; var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536 /* Module */; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; - for (var _i = 0; _i < declarations.length; _i++) { - var current = declarations[_i]; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); var inAmbientContextOrInterface = node.parent.kind === 215 /* InterfaceDeclaration */ || node.parent.kind === 155 /* TypeLiteral */ || inAmbientContext; @@ -23507,7 +23951,7 @@ var ts; } // Abstract methods can't have an implementation -- in particular, they don't need one. if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(lastSeenNonAmbientDeclaration.flags & 256 /* Abstract */)) { + !(lastSeenNonAmbientDeclaration.flags & 128 /* Abstract */)) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -23533,8 +23977,8 @@ var ts; // function g(x: string, y: string) { } // // The implementation is completely unrelated to the specialized signature, yet we do not check this. - for (var _a = 0; _a < signatures.length; _a++) { - var signature = signatures[_a]; + for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { + var signature = signatures_3[_a]; if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -23571,9 +24015,9 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var d = _a[_i]; var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 1024 /* Default */); - if (effectiveDeclarationFlags & 1 /* Export */) { - if (effectiveDeclarationFlags & 1024 /* Default */) { + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 2 /* Export */ | 512 /* Default */); + if (effectiveDeclarationFlags & 2 /* Export */) { + if (effectiveDeclarationFlags & 512 /* Default */) { defaultExportedDeclarationSpaces |= declarationSpaces; } else { @@ -23826,9 +24270,12 @@ var ts; // type as a value. As such, we will just return unknownType; return unknownType; } - var promiseConstructor = getMergedSymbol(promiseType.symbol); + var promiseConstructor = getNodeLinks(node.type).resolvedSymbol; if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { - error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeToString(promiseType)); + var typeName = promiseConstructor + ? symbolToString(promiseConstructor) + : typeToString(promiseType); + error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } // Validate the promise constructor type. @@ -24020,7 +24467,7 @@ var ts; if (isAsync) { promisedType = checkAsyncFunctionReturnType(node); } - checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); } if (produceDiagnostics && !node.type) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method @@ -24162,7 +24609,7 @@ var ts; // let x = 0; // symbol for this declaration will be 'symbol' // } // skip block-scoped variables and parameters - if ((ts.getCombinedNodeFlags(node) & 49152 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + if ((ts.getCombinedNodeFlags(node) & 24576 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { return; } // skip variable declarations that don't have initializers @@ -24177,7 +24624,7 @@ var ts; if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 49152 /* BlockScoped */) { + if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 24576 /* BlockScoped */) { var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 212 /* VariableDeclarationList */); var container = varDeclList.parent.kind === 193 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent @@ -24330,6 +24777,9 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 194 /* EmptyStatement */) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } checkSourceElement(node.elseStatement); } function checkDoStatement(node) { @@ -24688,7 +25138,7 @@ var ts; error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } else if (func.kind === 144 /* Constructor */) { - if (!isTypeAssignableTo(exprType, returnType)) { + if (!checkTypeAssignableTo(exprType, returnType, node.expression)) { error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } @@ -24835,7 +25285,7 @@ var ts; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!(member.flags & 128 /* Static */) && ts.hasDynamicName(member)) { + if (!(member.flags & 64 /* Static */) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); @@ -24921,7 +25371,7 @@ var ts; return getTypeOfSymbol(getSymbolOfNode(node)); } function checkClassDeclaration(node) { - if (!node.name && !(node.flags & 1024 /* Default */)) { + if (!node.name && !(node.flags & 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -24975,8 +25425,8 @@ var ts; } var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); if (implementedTypeNodes) { - for (var _b = 0; _b < implementedTypeNodes.length; _b++) { - var typeRefNode = implementedTypeNodes[_b]; + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } @@ -25024,8 +25474,8 @@ var ts; // derived class instance member variables and accessors, but not by other kinds of members. // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfObjectType(baseType); - for (var _i = 0; _i < baseProperties.length; _i++) { - var baseProperty = baseProperties[_i]; + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; var base = getTargetSymbol(baseProperty); if (base.flags & 134217728 /* Prototype */) { continue; @@ -25043,7 +25493,7 @@ var ts; // It is an error to inherit an abstract member without implementing it or being declared abstract. // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. - if (baseDeclarationFlags & 256 /* Abstract */ && (!derivedClassDecl || !(derivedClassDecl.flags & 256 /* Abstract */))) { + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(derivedClassDecl.flags & 128 /* Abstract */))) { if (derivedClassDecl.kind === 186 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -25055,11 +25505,11 @@ var ts; else { // derived overrides base. var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); - if ((baseDeclarationFlags & 32 /* Private */) || (derivedDeclarationFlags & 32 /* Private */)) { + if ((baseDeclarationFlags & 16 /* Private */) || (derivedDeclarationFlags & 16 /* Private */)) { // either base or derived property is private - not override, skip it continue; } - if ((baseDeclarationFlags & 128 /* Static */) !== (derivedDeclarationFlags & 128 /* Static */)) { + if ((baseDeclarationFlags & 64 /* Static */) !== (derivedDeclarationFlags & 64 /* Static */)) { // value of 'static' is not the same for properties - not override, skip it continue; } @@ -25130,11 +25580,11 @@ var ts; var seen = {}; ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; - for (var _i = 0; _i < baseTypes.length; _i++) { - var base = baseTypes[_i]; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0; _a < properties.length; _a++) { - var prop = properties[_a]; + for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { + var prop = properties_4[_a]; if (!ts.hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } @@ -25431,8 +25881,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; if ((declaration.kind === 214 /* ClassDeclaration */ || (declaration.kind === 213 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { @@ -25571,7 +26021,7 @@ var ts; // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -25599,7 +26049,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -25630,7 +26080,7 @@ var ts; // If we hit an export in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -25674,7 +26124,7 @@ var ts; return; } // Grammar checking - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69 /* Identifier */) { @@ -26087,7 +26537,7 @@ var ts; // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. - if (!(memberFlags & 128 /* Static */)) { + if (!(memberFlags & 64 /* Static */)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); } break; @@ -26388,7 +26838,7 @@ var ts; */ function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 128 /* Static */ + return node.flags & 64 /* Static */ ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -26709,7 +27159,7 @@ var ts; function initializeTypeChecker() { // Bind all source files and propagate errors ts.forEach(host.getSourceFiles(), function (file) { - ts.bindSourceFile(file); + ts.bindSourceFile(file, compilerOptions); }); // Initialize global symbol table ts.forEach(host.getSourceFiles(), function (file) { @@ -26863,19 +27313,19 @@ var ts; text = "private"; lastPrivate = modifier; } - if (flags & 112 /* AccessibilityModifier */) { + if (flags & 56 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (flags & 128 /* Static */) { + else if (flags & 64 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); } - else if (flags & 256 /* Abstract */) { + else if (flags & 128 /* Abstract */) { if (modifier.kind === 110 /* PrivateKeyword */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } @@ -26886,10 +27336,10 @@ var ts; flags |= ts.modifierToFlag(modifier.kind); break; case 113 /* StaticKeyword */: - if (flags & 128 /* Static */) { + if (flags & 64 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { @@ -26898,23 +27348,23 @@ var ts; else if (node.kind === 138 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } - else if (flags & 256 /* Abstract */) { + else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - flags |= 128 /* Static */; + flags |= 64 /* Static */; lastStatic = modifier; break; case 82 /* ExportKeyword */: - if (flags & 1 /* Export */) { + if (flags & 2 /* Export */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } - else if (flags & 2 /* Ambient */) { + else if (flags & 4 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } - else if (flags & 256 /* Abstract */) { + else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } else if (node.parent.kind === 214 /* ClassDeclaration */) { @@ -26923,13 +27373,13 @@ var ts; else if (node.kind === 138 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } - flags |= 1 /* Export */; + flags |= 2 /* Export */; break; case 122 /* DeclareKeyword */: - if (flags & 2 /* Ambient */) { + if (flags & 4 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } else if (node.parent.kind === 214 /* ClassDeclaration */) { @@ -26941,69 +27391,69 @@ var ts; else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 219 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - flags |= 2 /* Ambient */; + flags |= 4 /* Ambient */; lastDeclare = modifier; break; case 115 /* AbstractKeyword */: - if (flags & 256 /* Abstract */) { + if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } if (node.kind !== 214 /* ClassDeclaration */) { if (node.kind !== 143 /* MethodDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); } - if (!(node.parent.kind === 214 /* ClassDeclaration */ && node.parent.flags & 256 /* Abstract */)) { + if (!(node.parent.kind === 214 /* ClassDeclaration */ && node.parent.flags & 128 /* Abstract */)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } - if (flags & 128 /* Static */) { + if (flags & 64 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - if (flags & 32 /* Private */) { + if (flags & 16 /* Private */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); } } - flags |= 256 /* Abstract */; + flags |= 128 /* Abstract */; break; case 118 /* AsyncKeyword */: - if (flags & 512 /* Async */) { + if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { + else if (flags & 4 /* Ambient */ || ts.isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } else if (node.kind === 138 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } - flags |= 512 /* Async */; + flags |= 256 /* Async */; lastAsync = modifier; break; } } if (node.kind === 144 /* Constructor */) { - if (flags & 128 /* Static */) { + if (flags & 64 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } - if (flags & 256 /* Abstract */) { + if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } - else if (flags & 64 /* Protected */) { + else if (flags & 32 /* Protected */) { return grammarErrorOnNode(lastProtected, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "protected"); } - else if (flags & 32 /* Private */) { + else if (flags & 16 /* Private */) { return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } return; } - else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && flags & 4 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 138 /* Parameter */ && (flags & 112 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 138 /* Parameter */ && (flags & 56 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); } - if (flags & 512 /* Async */) { + if (flags & 256 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); } } @@ -27104,7 +27554,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 2035 /* Modifier */) { + if (parameter.flags & 1022 /* Modifier */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -27124,7 +27574,7 @@ var ts; } } function checkGrammarForIndexSignatureModifier(node) { - if (node.flags & 2035 /* Modifier */) { + if (node.flags & 1022 /* Modifier */) { grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_not_permitted_on_index_signature_members); } } @@ -27147,8 +27597,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0; _i < args.length; _i++) { - var arg = args[_i]; + for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { + var arg = args_1[_i]; if (arg.kind === 187 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -27403,7 +27853,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); } - else if (parameter.flags & 2035 /* Modifier */) { + else if (parameter.flags & 1022 /* Modifier */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } else if (parameter.questionToken) { @@ -27554,8 +28004,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0; _i < elements.length; _i++) { - var element = elements[_i]; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; if (element.kind !== 187 /* OmittedExpression */) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -27691,8 +28141,8 @@ var ts; node.kind === 221 /* ImportEqualsDeclaration */ || node.kind === 228 /* ExportDeclaration */ || node.kind === 227 /* ExportAssignment */ || - (node.flags & 2 /* Ambient */) || - (node.flags & (1 /* Export */ | 1024 /* Default */))) { + (node.flags & 4 /* Ambient */) || + (node.flags & (2 /* Export */ | 512 /* Default */))) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -27739,7 +28189,7 @@ var ts; } function checkGrammarNumericLiteral(node) { // Grammar checking - if (node.flags & 65536 /* OctalLiteral */ && languageVersion >= 1 /* ES5 */) { + if (node.flags & 32768 /* OctalLiteral */ && languageVersion >= 1 /* ES5 */) { return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } @@ -27793,7 +28243,7 @@ var ts; ts.forEach(root.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); // All the references that are not going to be part of same file - if (referencedFile && ((referencedFile.flags & 8192 /* DeclarationFile */) || + if (referencedFile && ((referencedFile.flags & 4096 /* DeclarationFile */) || ts.shouldEmitToOwnFile(referencedFile, compilerOptions) || !addedGlobalFileReference)) { writeReferencePath(referencedFile); @@ -27988,15 +28438,15 @@ var ts; } } function emitLines(nodes) { - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; emit(node); } } function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { var currentWriterPos = writer.getTextPos(); - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; if (!canEmitFn || canEmitFn(node)) { if (currentWriterPos !== writer.getTextPos()) { write(separator); @@ -28142,6 +28592,7 @@ var ts; function emitSourceFile(node) { currentSourceFile = node; enclosingDeclaration = node; + ts.emitDetachedComments(currentSourceFile, writer, ts.writeCommentRange, node, newLine, true /* remove comments */); emitLines(node.statements); } // Return a temp variable name to be used in `export default` statements. @@ -28258,10 +28709,10 @@ var ts; // If the node is parented in the current source file we need to emit export declare or just export if (node.parent === currentSourceFile) { // If the node is exported - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { write("export "); } - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { write("default "); } else if (node.kind !== 215 /* InterfaceDeclaration */) { @@ -28270,16 +28721,16 @@ var ts; } } function emitClassMemberDeclarationFlags(node) { - if (node.flags & 32 /* Private */) { + if (node.flags & 16 /* Private */) { write("private "); } - else if (node.flags & 64 /* Protected */) { + else if (node.flags & 32 /* Protected */) { write("protected "); } - if (node.flags & 128 /* Static */) { + if (node.flags & 64 /* Static */) { write("static "); } - if (node.flags & 256 /* Abstract */) { + if (node.flags & 128 /* Abstract */) { write("abstract "); } } @@ -28287,7 +28738,7 @@ var ts; // note usage of writer. methods instead of aliases created, just to make sure we are using // correct writer especially to handle asynchronous alias writing emitJsDocComments(node); - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { write("export "); } write("import "); @@ -28322,12 +28773,12 @@ var ts; } } function writeImportDeclaration(node) { - if (!node.importClause && !(node.flags & 1 /* Export */)) { + if (!node.importClause && !(node.flags & 2 /* Export */)) { // do not write non-exported import declarations that don't have import clauses return; } emitJsDocComments(node); - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { write("export "); } write("import "); @@ -28392,7 +28843,7 @@ var ts; function writeModuleDeclaration(node) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 131072 /* Namespace */) { + if (node.flags & 65536 /* Namespace */) { write("namespace "); } else { @@ -28464,7 +28915,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 143 /* MethodDeclaration */ && (node.parent.flags & 32 /* Private */); + return node.parent.kind === 143 /* MethodDeclaration */ && (node.parent.flags & 16 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -28508,7 +28959,7 @@ var ts; break; case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - if (node.parent.flags & 128 /* Static */) { + if (node.parent.flags & 64 /* Static */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } else if (node.parent.parent.kind === 214 /* ClassDeclaration */) { @@ -28574,7 +29025,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 112 /* AccessibilityModifier */) { + if (param.flags & 56 /* AccessibilityModifier */) { emitPropertyDeclaration(param); } }); @@ -28582,7 +29033,7 @@ var ts; } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 256 /* Abstract */) { + if (node.flags & 128 /* Abstract */) { write("abstract "); } write("class "); @@ -28652,7 +29103,7 @@ var ts; if ((node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) && node.parent.kind === 155 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 32 /* Private */)) { + else if (!(node.flags & 16 /* Private */)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } @@ -28667,7 +29118,7 @@ var ts; } else if (node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) { // TODO(jfreeman): Deal with computed properties in error reporting. - if (node.flags & 128 /* Static */) { + if (node.flags & 64 /* Static */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -28771,7 +29222,7 @@ var ts; emitJsDocComments(accessors.setAccessor); emitClassMemberDeclarationFlags(node); writeTextOfNode(currentSourceFile, node.name); - if (!(node.flags & 32 /* Private */)) { + if (!(node.flags & 16 /* Private */)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { @@ -28800,7 +29251,7 @@ var ts; var diagnosticMessage; if (accessorWithTypeAnnotation.kind === 146 /* SetAccessor */) { // Setters have to have type named and cannot infer it so, the type should always be named - if (accessorWithTypeAnnotation.parent.flags & 128 /* Static */) { + if (accessorWithTypeAnnotation.parent.flags & 64 /* Static */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; @@ -28818,7 +29269,7 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 128 /* Static */) { + if (accessorWithTypeAnnotation.flags & 64 /* Static */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -28905,7 +29356,7 @@ var ts; emitType(node.type); } } - else if (node.kind !== 144 /* Constructor */ && !(node.flags & 32 /* Private */)) { + else if (node.kind !== 144 /* Constructor */ && !(node.flags & 16 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -28936,7 +29387,7 @@ var ts; break; case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - if (node.flags & 128 /* Static */) { + if (node.flags & 64 /* Static */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -28997,7 +29448,7 @@ var ts; node.parent.parent.kind === 155 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 32 /* Private */)) { + else if (!(node.parent.flags & 16 /* Private */)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { @@ -29028,7 +29479,7 @@ var ts; ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - if (node.parent.flags & 128 /* Static */) { + if (node.parent.flags & 64 /* Static */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -29170,7 +29621,7 @@ var ts; } } function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 8192 /* DeclarationFile */ + var declFileName = referencedFile.flags & 4096 /* DeclarationFile */ ? referencedFile.fileName // Declaration file, use declaration file name : ts.shouldEmitToOwnFile(referencedFile, compilerOptions) ? ts.getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file @@ -29216,6 +29667,12 @@ var ts; return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); } ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); var entities = { "quot": 0x0022, "amp": 0x0026, @@ -29525,16 +29982,8 @@ var ts; diagnostics: diagnostics, sourceMaps: sourceMapDataList }; - function isNodeDescendentOf(node, ancestor) { - while (node) { - if (node === ancestor) - return true; - node = node.parent; - } - return false; - } function isUniqueLocalName(name, container) { - for (var node = container; isNodeDescendentOf(node, container); node = node.nextContainer) { + for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { if (node.locals && ts.hasProperty(node.locals, name)) { // We conservatively include alias symbols to cover cases where they're emitted as locals if (node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) { @@ -29544,12 +29993,6 @@ var ts; } return true; } - var Jump; - (function (Jump) { - Jump[Jump["Break"] = 2] = "Break"; - Jump[Jump["Continue"] = 4] = "Continue"; - Jump[Jump["Return"] = 8] = "Return"; - })(Jump || (Jump = {})); function setLabeledJump(state, isBreak, labelText, labelMarker) { if (isBreak) { if (!state.labeledNonLocalBreaks) { @@ -31026,7 +31469,7 @@ var ts; write("]"); } else { - emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ (node.flags & 2048 /* MultiLine */) !== 0, + emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ (node.flags & 1024 /* MultiLine */) !== 0, /*trailingComma*/ elements.hasTrailingComma, /*useConcat*/ true); } } @@ -31045,7 +31488,7 @@ var ts; emitLinePreservingList(node, properties, /* allowTrailingComma */ languageVersion >= 1 /* ES5 */, /* spacesBetweenBraces */ true); } else { - var multiLine = (node.flags & 2048 /* MultiLine */) !== 0; + var multiLine = (node.flags & 1024 /* MultiLine */) !== 0; if (!multiLine) { write(" "); } @@ -31064,7 +31507,7 @@ var ts; write("}"); } function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = (node.flags & 2048 /* MultiLine */) !== 0; + var multiLine = (node.flags & 1024 /* MultiLine */) !== 0; var properties = node.properties; write("("); if (multiLine) { @@ -31693,7 +32136,7 @@ var ts; var current = node; while (current) { if (current.kind === 248 /* SourceFile */) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 1 /* Export */) !== 0); + return !isExported || ((ts.getCombinedNodeFlags(node) & 2 /* Export */) !== 0); } else if (ts.isFunctionLike(current) || current.kind === 219 /* ModuleBlock */) { return false; @@ -31934,7 +32377,7 @@ var ts; // variables in variable declaration list were already hoisted return false; } - if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 49152 /* BlockScoped */) === 0) { + if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 24576 /* BlockScoped */) === 0) { // we are inside a converted loop - this can only happen in downlevel scenarios // record names for all variable declarations for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { @@ -32019,7 +32462,7 @@ var ts; break; } var loopParameters; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 49152 /* BlockScoped */)) { + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 24576 /* BlockScoped */)) { // if loop initializer contains block scoped variables - they should be passed to converted loop body as parameters loopParameters = []; for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { @@ -32334,10 +32777,12 @@ var ts; // // for (let v of arr) { } // - // we don't want to emit a temporary variable for the RHS, just use it directly. - var rhsIsIdentifier = node.expression.kind === 69 /* Identifier */; + // we can't reuse 'arr' because it might be modified within the body of the loop. var counter = createTempVariable(268435456 /* _i */); - var rhsReference = rhsIsIdentifier ? node.expression : createTempVariable(0 /* Auto */); + var rhsReference = ts.createSynthesizedNode(69 /* Identifier */); + rhsReference.text = node.expression.kind === 69 /* Identifier */ ? + makeUniqueName(node.expression.text) : + makeTempVariableName(0 /* Auto */); // This is the let keyword for the counter and rhsReference. The let keyword for // the LHS will be emitted inside the body. emitStart(node.expression); @@ -32346,15 +32791,13 @@ var ts; emitNodeWithoutSourceMap(counter); write(" = 0"); emitEnd(node.expression); - if (!rhsIsIdentifier) { - // , _a = expr - write(", "); - emitStart(node.expression); - emitNodeWithoutSourceMap(rhsReference); - write(" = "); - emitNodeWithoutSourceMap(node.expression); - emitEnd(node.expression); - } + // , _a = expr + write(", "); + emitStart(node.expression); + emitNodeWithoutSourceMap(rhsReference); + write(" = "); + emitNodeWithoutSourceMap(node.expression); + emitEnd(node.expression); write("; "); // _i < _a.length; emitStart(node.initializer); @@ -32609,7 +33052,7 @@ var ts; } function emitModuleMemberName(node) { emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 1 /* Export */) { + if (ts.getCombinedNodeFlags(node) & 2 /* Export */) { var container = getContainingModule(node); if (container) { write(getGeneratedNameForNode(container)); @@ -32631,7 +33074,7 @@ var ts; } function emitEs6ExportDefaultCompat(node) { if (node.parent.kind === 248 /* SourceFile */) { - ts.Debug.assert(!!(node.flags & 1024 /* Default */) || node.kind === 227 /* ExportAssignment */); + ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 227 /* ExportAssignment */); // only allow export default at a source file level if (modulekind === 1 /* CommonJS */ || modulekind === 2 /* AMD */ || modulekind === 3 /* UMD */) { if (!currentSourceFile.symbol.exports["___esModule"]) { @@ -32649,7 +33092,7 @@ var ts; } } function emitExportMemberAssignment(node) { - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { writeLine(); emitStart(node); // emit call to exporter only for top level nodes @@ -32657,7 +33100,7 @@ var ts; // emit export default as // export("default", ) write(exportFunctionForFile + "(\""); - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { write("default"); } else { @@ -32668,7 +33111,7 @@ var ts; write(")"); } else { - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { emitEs6ExportDefaultCompat(node); if (languageVersion === 0 /* ES3 */) { write("exports[\"default\"]"); @@ -32772,7 +33215,7 @@ var ts; // because actual variable declarations are hoisted var canDefineTempVariablesInPlace = false; if (root.kind === 211 /* VariableDeclaration */) { - var isExported = ts.getCombinedNodeFlags(root) & 1 /* Export */; + var isExported = ts.getCombinedNodeFlags(root) & 2 /* Export */; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } @@ -32854,8 +33297,8 @@ var ts; // to ensure value is evaluated exactly once. value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); } - for (var _a = 0; _a < properties.length; _a++) { - var p = properties[_a]; + for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { + var p = properties_5[_a]; if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { var propName = p.name; var target_1 = p.kind === 246 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; @@ -32990,7 +33433,7 @@ var ts; // this is necessary to preserve ES6 semantic in scenarios like // for (...) { let x; console.log(x); x = 1 } // assignment on one iteration should not affect other iterations var isLetDefinedInLoop = (resolver.getNodeCheckFlags(node) & 16384 /* BlockScopedBindingInLoop */) && - (getCombinedFlagsForIdentifier(node.name) & 16384 /* Let */); + (getCombinedFlagsForIdentifier(node.name) & 8192 /* Let */); // NOTE: default initialization should not be added to let bindings in for-in\for-of statements if (isLetDefinedInLoop && node.parent.parent.kind !== 200 /* ForInStatement */ && @@ -33030,13 +33473,13 @@ var ts; return ts.getCombinedNodeFlags(node.parent); } function isES6ExportedDeclaration(node) { - return !!(node.flags & 1 /* Export */) && + return !!(node.flags & 2 /* Export */) && modulekind === 5 /* ES6 */ && node.parent.kind === 248 /* SourceFile */; } function emitVariableStatement(node) { var startIsEmitted = false; - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { if (isES6ExportedDeclaration(node)) { // Exported ES6 module member write("export "); @@ -33063,7 +33506,7 @@ var ts; function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { // If we're not exporting the variables, there's nothing special here. // Always emit comments for these nodes. - if (!(node.flags & 1 /* Export */)) { + if (!(node.flags & 2 /* Export */)) { return true; } // If we are exporting, but it's a top-level ES6 module exports, @@ -33246,7 +33689,7 @@ var ts; if (!shouldEmitAsArrowFunction(node)) { if (isES6ExportedDeclaration(node)) { write("export "); - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { write("default "); } } @@ -33466,7 +33909,7 @@ var ts; emitRestParameter(node); } function emitExpressionFunctionBody(node, body) { - if (languageVersion < 2 /* ES6 */ || node.flags & 512 /* Async */) { + if (languageVersion < 2 /* ES6 */ || node.flags & 256 /* Async */) { emitDownLevelExpressionFunctionBody(node, body); return; } @@ -33487,7 +33930,7 @@ var ts; scopeEmitStart(node); increaseIndent(); var outPos = writer.getTextPos(); - emitDetachedComments(node.body); + emitDetachedCommentsAndUpdateCommentsInfo(node.body); emitFunctionBodyPreamble(node); var preambleEmitted = writer.getTextPos() !== outPos; decreaseIndent(); @@ -33525,7 +33968,7 @@ var ts; scopeEmitStart(node); var initialTextPos = writer.getTextPos(); increaseIndent(); - emitDetachedComments(body.statements); + emitDetachedCommentsAndUpdateCommentsInfo(body.statements); // Emit all the directive prologues (like "use strict"). These have to come before // any other preamble code we write (like parameter initializers). var startIndex = emitDirectivePrologues(body.statements, /*startWithNewLine*/ true); @@ -33569,7 +34012,7 @@ var ts; } function emitParameterPropertyAssignments(node) { ts.forEach(node.parameters, function (param) { - if (param.flags & 112 /* AccessibilityModifier */) { + if (param.flags & 56 /* AccessibilityModifier */) { writeLine(); emitStart(param); emitStart(param.name); @@ -33604,15 +34047,15 @@ var ts; var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 141 /* PropertyDeclaration */ && isStatic === ((member.flags & 128 /* Static */) !== 0) && member.initializer) { + if (member.kind === 141 /* PropertyDeclaration */ && isStatic === ((member.flags & 64 /* Static */) !== 0) && member.initializer) { properties.push(member); } } return properties; } function emitPropertyDeclarations(node, properties) { - for (var _a = 0; _a < properties.length; _a++) { - var property = properties[_a]; + for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { + var property = properties_6[_a]; emitPropertyDeclaration(node, property); } } @@ -33625,7 +34068,7 @@ var ts; emit(receiver); } else { - if (property.flags & 128 /* Static */) { + if (property.flags & 64 /* Static */) { emitDeclarationName(node); } else { @@ -33724,7 +34167,7 @@ var ts; writeLine(); emitLeadingComments(member); emitStart(member); - if (member.flags & 128 /* Static */) { + if (member.flags & 64 /* Static */) { write("static "); } if (member.kind === 145 /* GetAccessor */) { @@ -33774,7 +34217,7 @@ var ts; emitCommentsOnNotEmittedNode(member); } // Check if there is any non-static property assignment - if (member.kind === 141 /* PropertyDeclaration */ && member.initializer && (member.flags & 128 /* Static */) === 0) { + if (member.kind === 141 /* PropertyDeclaration */ && member.initializer && (member.flags & 64 /* Static */) === 0) { hasInstancePropertyWithInitializer = true; } }); @@ -33821,7 +34264,7 @@ var ts; // Emit all the directive prologues (like "use strict"). These have to come before // any other preamble code we write (like parameter initializers). startIndex = emitDirectivePrologues(ctor.body.statements, /*startWithNewLine*/ true); - emitDetachedComments(ctor.body.statements); + emitDetachedCommentsAndUpdateCommentsInfo(ctor.body.statements); } emitCaptureThisForNodeIfNecessary(node); var superCall; @@ -33941,7 +34384,7 @@ var ts; // _default = __decorate([dec], _default); // export default _default; // - if (isES6ExportedDeclaration(node) && !(node.flags & 1024 /* Default */)) { + if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */)) { write("export "); } write("let "); @@ -33950,7 +34393,7 @@ var ts; } else if (isES6ExportedDeclaration(node)) { write("export "); - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { write("default "); } } @@ -33980,7 +34423,7 @@ var ts; // emit name if // - node has a name // - this is default export with static initializers - if ((node.name || (node.flags & 1024 /* Default */ && staticProperties.length > 0)) && !thisNodeIsDecorated) { + if ((node.name || (node.flags & 512 /* Default */ && staticProperties.length > 0)) && !thisNodeIsDecorated) { write(" "); emitDeclarationName(node); } @@ -34016,8 +34459,8 @@ var ts; // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. if (isClassExpressionWithStaticProperties) { - for (var _a = 0; _a < staticProperties.length; _a++) { - var property = staticProperties[_a]; + for (var _a = 0, staticProperties_1 = staticProperties; _a < staticProperties_1.length; _a++) { + var property = staticProperties_1[_a]; write(","); writeLine(); emitPropertyDeclaration(node, property, /*receiver:*/ tempVariable, /*isExpression:*/ true); @@ -34035,7 +34478,7 @@ var ts; } // If this is an exported class, but not on the top level (i.e. on an internal // module), export it - if (!isES6ExportedDeclaration(node) && (node.flags & 1 /* Export */)) { + if (!isES6ExportedDeclaration(node) && (node.flags & 2 /* Export */)) { writeLine(); emitStart(node); emitModuleMemberName(node); @@ -34044,7 +34487,7 @@ var ts; emitEnd(node); write(";"); } - else if (isES6ExportedDeclaration(node) && (node.flags & 1024 /* Default */) && thisNodeIsDecorated) { + else if (isES6ExportedDeclaration(node) && (node.flags & 512 /* Default */) && thisNodeIsDecorated) { // if this is a top level default export of decorated class, write the export after the declaration. writeLine(); write("export default "); @@ -34126,13 +34569,13 @@ var ts; } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); - if (!(member.flags & 128 /* Static */)) { + if (!(member.flags & 64 /* Static */)) { write(".prototype"); } } function emitDecoratorsOfClass(node) { emitDecoratorsOfMembers(node, /*staticFlag*/ 0); - emitDecoratorsOfMembers(node, 128 /* Static */); + emitDecoratorsOfMembers(node, 64 /* Static */); emitDecoratorsOfConstructor(node); } function emitDecoratorsOfConstructor(node) { @@ -34179,7 +34622,7 @@ var ts; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; // only emit members in the correct group - if ((member.flags & 128 /* Static */) !== staticFlag) { + if ((member.flags & 64 /* Static */) !== staticFlag) { continue; } // skip members that cannot be decorated (such as the constructor) @@ -34580,7 +35023,7 @@ var ts; } if (!shouldHoistDeclarationInSystemJsModule(node)) { // do not emit var if variable was already hoisted - if (!(node.flags & 1 /* Export */) || isES6ExportedDeclaration(node)) { + if (!(node.flags & 2 /* Export */) || isES6ExportedDeclaration(node)) { emitStart(node); if (isES6ExportedDeclaration(node)) { write("export "); @@ -34611,7 +35054,7 @@ var ts; emitModuleMemberName(node); write(" = {}));"); emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 1 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) { + if (!isES6ExportedDeclaration(node) && node.flags & 2 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) { // do not emit var if variable was already hoisted writeLine(); emitStart(node); @@ -34623,7 +35066,7 @@ var ts; write(";"); } if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile) { - if (modulekind === 4 /* System */ && (node.flags & 1 /* Export */)) { + if (modulekind === 4 /* System */ && (node.flags & 2 /* Export */)) { // write the call to exporter for enum writeLine(); write(exportFunctionForFile + "(\""); @@ -34728,7 +35171,7 @@ var ts; } write(")("); // write moduleDecl = containingModule.m only if it is not exported es6 module member - if ((node.flags & 1 /* Export */) && !isES6ExportedDeclaration(node)) { + if ((node.flags & 2 /* Export */) && !isES6ExportedDeclaration(node)) { emit(node.name); write(" = "); } @@ -34738,7 +35181,7 @@ var ts; write(" = {}));"); emitEnd(node); if (!isES6ExportedDeclaration(node) && node.name.kind === 69 /* Identifier */ && node.parent === currentSourceFile) { - if (modulekind === 4 /* System */ && (node.flags & 1 /* Export */)) { + if (modulekind === 4 /* System */ && (node.flags & 2 /* Export */)) { writeLine(); write(exportFunctionForFile + "(\""); emitDeclarationName(node); @@ -34841,7 +35284,7 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 221 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0; + var isExportedImport = node.kind === 221 /* ImportEqualsDeclaration */ && (node.flags & 2 /* Export */) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); if (modulekind !== 2 /* AMD */) { emitLeadingComments(node); @@ -34923,7 +35366,7 @@ var ts; write("export "); write("var "); } - else if (!(node.flags & 1 /* Export */)) { + else if (!(node.flags & 2 /* Export */)) { write("var "); } } @@ -35014,8 +35457,8 @@ var ts; function emitExportOrImportSpecifierList(specifiers, shouldEmit) { ts.Debug.assert(modulekind === 5 /* ES6 */); var needsComma = false; - for (var _a = 0; _a < specifiers.length; _a++) { - var specifier = specifiers[_a]; + for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { + var specifier = specifiers_1[_a]; if (shouldEmit(specifier)) { if (needsComma) { write(", "); @@ -35158,8 +35601,8 @@ var ts; } writeLine(); var started = false; - for (var _a = 0; _a < externalImports.length; _a++) { - var importNode = externalImports[_a]; + for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { + var importNode = externalImports_1[_a]; // do not create variable declaration for exports and imports that lack import clause var skipNode = importNode.kind === 228 /* ExportDeclaration */ || (importNode.kind === 222 /* ImportDeclaration */ && !importNode.importClause); @@ -35193,8 +35636,8 @@ var ts; // no exported declarations (export var ...) or export specifiers (export {x}) // check if we have any non star export declarations. var hasExportDeclarationWithExportClause = false; - for (var _a = 0; _a < externalImports.length; _a++) { - var externalImport = externalImports[_a]; + for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { + var externalImport = externalImports_2[_a]; if (externalImport.kind === 228 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; @@ -35225,8 +35668,8 @@ var ts; } } } - for (var _d = 0; _d < externalImports.length; _d++) { - var externalImport = externalImports[_d]; + for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { + var externalImport = externalImports_3[_d]; if (externalImport.kind !== 228 /* ExportDeclaration */) { continue; } @@ -35275,7 +35718,7 @@ var ts; function writeExportedName(node) { // do not record default exports // they are local to module and never overwritten (explicitly skipped) by star export - if (node.kind !== 69 /* Identifier */ && node.flags & 1024 /* Default */) { + if (node.kind !== 69 /* Identifier */ && node.flags & 512 /* Default */) { return; } if (started) { @@ -35338,7 +35781,7 @@ var ts; emit(local); } var flags = ts.getCombinedNodeFlags(local.kind === 69 /* Identifier */ ? local.parent : local); - if (flags & 1 /* Export */) { + if (flags & 2 /* Export */) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -35348,11 +35791,11 @@ var ts; write(";"); } if (hoistedFunctionDeclarations) { - for (var _a = 0; _a < hoistedFunctionDeclarations.length; _a++) { - var f = hoistedFunctionDeclarations[_a]; + for (var _a = 0, hoistedFunctionDeclarations_1 = hoistedFunctionDeclarations; _a < hoistedFunctionDeclarations_1.length; _a++) { + var f = hoistedFunctionDeclarations_1[_a]; writeLine(); emit(f); - if (f.flags & 1 /* Export */) { + if (f.flags & 2 /* Export */) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -35362,7 +35805,7 @@ var ts; } return exportedDeclarations; function visit(node) { - if (node.flags & 2 /* Ambient */) { + if (node.flags & 4 /* Ambient */) { return; } if (node.kind === 213 /* FunctionDeclaration */) { @@ -35437,7 +35880,7 @@ var ts; // - it is top level block scoped // if block scoped variables are nested in some another block then // no other functions can use them except ones that are defined at least in the same block - return (ts.getCombinedNodeFlags(node) & 49152 /* BlockScoped */) === 0 || + return (ts.getCombinedNodeFlags(node) & 24576 /* BlockScoped */) === 0 || ts.getEnclosingBlockScopeContainer(node).kind === 248 /* SourceFile */; } function isCurrentFileSystemExternalModule() { @@ -35509,8 +35952,8 @@ var ts; var parameterName = makeUniqueName(ts.forEach(group, getLocalNameForExternalImport) || ""); write("function (" + parameterName + ") {"); increaseIndent(); - for (var _a = 0; _a < group.length; _a++) { - var entry = group[_a]; + for (var _a = 0, group_1 = group; _a < group_1.length; _a++) { + var entry = group_1[_a]; var importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { case 222 /* ImportDeclaration */: @@ -35679,8 +36122,8 @@ var ts; unaliasedModuleNames.push("\"" + amdDependency.path + "\""); } } - for (var _c = 0; _c < externalImports.length; _c++) { - var importNode = externalImports[_c]; + for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { + var importNode = externalImports_4[_c]; // Find the name of the external module var externalModuleName = getExternalModuleNameText(importNode); // Find the name of the module alias, if there is one @@ -35959,7 +36402,7 @@ var ts; // Start new file on new line writeLine(); emitShebang(); - emitDetachedComments(node); + emitDetachedCommentsAndUpdateCommentsInfo(node); if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */]; emitModule(node); @@ -35983,7 +36426,7 @@ var ts; } function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { if (node) { - if (node.flags & 2 /* Ambient */) { + if (node.flags & 4 /* Ambient */) { return emitCommentsOnNotEmittedNode(node); } if (isSpecializedCommentHandling(node)) { @@ -36232,10 +36675,6 @@ var ts; } return leadingComments; } - function isPinnedComments(comment) { - return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && - currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; - } /** * Determine if the given comment is a triple-slash * @@ -36350,57 +36789,14 @@ var ts; // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); } - function emitDetachedComments(node) { - var leadingComments; - if (compilerOptions.removeComments) { - // removeComments is true, only reserve pinned comment at the top of file - // For example: - // /*! Pinned Comment */ - // - // var x = 10; - if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComments); + function emitDetachedCommentsAndUpdateCommentsInfo(node) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); } - } - else { - // removeComments is false, just get detached as normal and bypass the process to filter comment - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); - } - if (leadingComments) { - var detachedComments = []; - var lastComment; - ts.forEach(leadingComments, function (comment) { - if (lastComment) { - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, lastComment.end); - var commentLine = ts.getLineOfLocalPosition(currentSourceFile, comment.pos); - if (commentLine >= lastCommentLine + 2) { - // There was a blank line between the last comment and this comment. This - // comment is not part of the copyright comments. Return what we have so - // far. - return detachedComments; - } - } - detachedComments.push(comment); - lastComment = comment; - }); - if (detachedComments.length) { - // All comments look like they could have been part of the copyright header. Make - // sure there is at least one blank line between it and the node. If not, it's not - // a copyright header. - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); - var nodeLine = ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); - if (nodeLine >= lastCommentLine + 2) { - // Valid detachedComments - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - ts.emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); - var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; } } } @@ -36716,7 +37112,7 @@ var ts; var resolveModuleNamesWorker = host.resolveModuleNames ? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }) : (function (moduleNames, containingFile) { return ts.map(moduleNames, function (moduleName) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }); }); - var filesByName = ts.createFileMap(getCanonicalFileName); + var filesByName = ts.createFileMap(); // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; @@ -36774,8 +37170,8 @@ var ts; // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = {}; - for (var _i = 0; _i < files.length; _i++) { - var sourceFile = files[_i]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var sourceFile = files_3[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -36793,7 +37189,7 @@ var ts; } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; - var normalizedAbsoluteFileNames = []; + var filePaths = []; var modifiedSourceFiles = []; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; @@ -36801,8 +37197,8 @@ var ts; if (!newSourceFile) { return false; } - var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); - normalizedAbsoluteFileNames.push(normalizedAbsolutePath); + newSourceFile.path = oldSourceFile.path; + filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed @@ -36822,7 +37218,7 @@ var ts; } if (resolveModuleNamesWorker) { var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); - var resolutions = resolveModuleNamesWorker(moduleNames, normalizedAbsolutePath); + var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); // ensure that module resolution results are still correct for (var i = 0; i < moduleNames.length; ++i) { var newResolution = resolutions[i]; @@ -36850,12 +37246,12 @@ var ts; } // update fileName -> file mapping for (var i = 0, len = newSourceFiles.length; i < len; ++i) { - filesByName.set(normalizedAbsoluteFileNames[i], newSourceFiles[i]); + filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _b = 0; _b < modifiedSourceFiles.length; _b++) { - var modifiedFile = modifiedSourceFiles[_b]; + for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { + var modifiedFile = modifiedSourceFiles_1[_b]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); } oldProgram.structureIsReused = true; @@ -36905,7 +37301,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - return filesByName.get(ts.getNormalizedAbsolutePath(fileName, currentDirectory)); + return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); } function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { if (sourceFile) { @@ -37024,7 +37420,7 @@ var ts; } break; case 218 /* ModuleDeclaration */: - if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { + if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 4 /* Ambient */ || ts.isDeclarationFile(file))) { // TypeScript 1.0 spec (April 2014): 12.1.6 // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. @@ -37049,7 +37445,7 @@ var ts; diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"]; } - else if (!findSourceFile(fileName, ts.getNormalizedAbsolutePath(fileName, currentDirectory), isDefaultLib, refFile, refPos, refEnd)) { + else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } @@ -37059,13 +37455,13 @@ var ts; } } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.getNormalizedAbsolutePath(fileName, currentDirectory), isDefaultLib, refFile, refPos, refEnd); + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.getNormalizedAbsolutePath(fileName + extension, currentDirectory), isDefaultLib, refFile, refPos, refEnd); })) { + else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -37111,6 +37507,7 @@ var ts; }); filesByName.set(normalizedAbsolutePath, file); if (file) { + file.path = normalizedAbsolutePath; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath); @@ -37157,13 +37554,7 @@ var ts; var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); if (resolution && !options.noResolve) { - var absoluteImportPath = ts.isRootedDiskPath(resolution.resolvedFileName) - ? resolution.resolvedFileName - : ts.getNormalizedAbsolutePath(resolution.resolvedFileName, currentDirectory); - // convert an absolute import path to path that is relative to current directory - // this was host still can locate it but files names in user output will be shorter (and thus look nicer). - var relativePath = ts.getRelativePathToDirectoryOrUrl(currentDirectory, absoluteImportPath, currentDirectory, getCanonicalFileName, false); - var importedFile = findSourceFile(relativePath, absoluteImportPath, /* isDefaultLib */ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /* isDefaultLib */ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { if (!ts.isExternalModule(importedFile)) { var start_2 = ts.getTokenPosOfNode(file.imports[i], file); @@ -37219,8 +37610,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0; _i < sourceFiles.length; _i++) { - var sourceFile = sourceFiles[_i]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -37344,6 +37735,7 @@ var ts; /// /// /// +/// /// var ts; (function (ts) { @@ -37493,6 +37885,12 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code }, + { + name: "pretty", + paramType: ts.Diagnostics.KIND, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental, + type: "boolean" + }, { name: "project", shortName: "p", @@ -37591,11 +37989,31 @@ var ts; description: ts.Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, error: ts.Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic }, + { + name: "allowUnusedLabels", + type: "boolean", + description: ts.Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "noImplicitReturns", + type: "boolean", + description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + { + name: "allowUnreachableCode", + type: "boolean", + description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code + }, { name: "forceConsistentCasingInFileNames", type: "boolean", description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file - }, + } ]; var optionNameMapCache; /* @internal */ @@ -37734,13 +38152,38 @@ var ts; */ function parseConfigFileTextToJson(fileName, jsonText) { try { - return { config: /\S/.test(jsonText) ? JSON.parse(jsonText) : {} }; + var jsonTextWithoutComments = removeComments(jsonText); + return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Remove the comments from a json like text. + * Comments can be single line comments (starting with # or //) or multiline comments using / * * / + * + * This method replace comment content by whitespace rather than completely remove them to keep positions in json parsing error reporting accurate. + */ + function removeComments(jsonText) { + var output = ""; + var scanner = ts.createScanner(1 /* ES5 */, /* skipTrivia */ false, 0 /* Standard */, jsonText); + var token; + while ((token = scanner.scan()) !== 1 /* EndOfFileToken */) { + switch (token) { + case 2 /* SingleLineCommentTrivia */: + case 3 /* MultiLineCommentTrivia */: + // replace comments with whitespace to preserve original character positions + output += scanner.getTokenText().replace(/\S/g, " "); + break; + default: + output += scanner.getTokenText(); + break; + } + } + return output; + } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -37871,8 +38314,8 @@ var ts; var lastSingleLineCommentEnd = -1; var isFirstSingleLineComment = true; var singleLineCommentCount = 0; - for (var _i = 0; _i < comments.length; _i++) { - var currentComment = comments[_i]; + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var currentComment = comments_2[_i]; // For single line comments, combine consecutive ones (2 or more) into // a single span from the start of the first till the end of the last if (currentComment.kind === 2 /* SingleLineCommentTrivia */) { @@ -38004,6 +38447,8 @@ var ts; function getNavigateToItems(program, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; + // This means "compare in a case insensitive manner." + var baseSensitivity = { sensitivity: "base" }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); @@ -38017,8 +38462,8 @@ var ts; if (!matches) { continue; } - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. if (patternMatcher.patternContainsDots) { @@ -38047,8 +38492,8 @@ var ts; function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0; _i < matches.length; _i++) { - var match = matches[_i]; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; if (!match.isCaseSensitive) { return false; } @@ -38123,8 +38568,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0; _i < matches.length; _i++) { - var match = matches[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -38132,8 +38577,6 @@ var ts; } return bestMatchKind; } - // This means "compare in a case insensitive manner." - var baseSensitivity = { sensitivity: "base" }; function compareNavigateToItems(i1, i2) { // TODO(cyrusn): get the gamut of comparisons that VS already uses here. // Right now we just sort by kind first, and then by name of the item. @@ -38296,8 +38739,8 @@ var ts; } function addTopLevelNodes(nodes, topLevelNodes) { nodes = sortNodes(nodes); - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; switch (node.kind) { case 214 /* ClassDeclaration */: case 217 /* EnumDeclaration */: @@ -38340,8 +38783,8 @@ var ts; function getItemsWorker(nodes, createItem) { var items = []; var keyToItem = {}; - for (var _i = 0; _i < nodes.length; _i++) { - var child = nodes[_i]; + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var child = nodes_5[_i]; var item = createItem(child); if (item !== undefined) { if (item.text.length > 0) { @@ -38389,7 +38832,7 @@ var ts; if (ts.isBindingPattern(node.name)) { break; } - if ((node.flags & 2035 /* Modifier */) === 0) { + if ((node.flags & 1022 /* Modifier */) === 0) { return undefined; } return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); @@ -38693,8 +39136,8 @@ var ts; // word part. That way we don't match something like 'Class' when the user types 'a'. // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). var wordSpans = getWordSpans(candidate); - for (var _i = 0; _i < wordSpans.length; _i++) { - var span = wordSpans[_i]; + for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { + var span = wordSpans_1[_i]; if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); @@ -38800,8 +39243,8 @@ var ts; // Only if all words have some sort of match is the pattern considered matched. var subWordTextChunks = segment.subWordTextChunks; var matches = undefined; - for (var _i = 0; _i < subWordTextChunks.length; _i++) { - var subWordTextChunk = subWordTextChunks[_i]; + for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { + var subWordTextChunk = subWordTextChunks_1[_i]; // Try to match the candidate with this word var result = matchTextChunk(candidate, subWordTextChunk, /*punctuationStripped:*/ true); if (!result) { @@ -39386,8 +39829,8 @@ var ts; var nameToDeclarations = sourceFile_1.getNamedDeclarations(); var declarations = ts.getProperty(nameToDeclarations, name.text); if (declarations) { - for (var _b = 0; _b < declarations.length; _b++) { - var declaration = declarations[_b]; + for (var _b = 0, declarations_7 = declarations; _b < declarations_7.length; _b++) { + var declaration = declarations_7[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -39503,8 +39946,8 @@ var ts; // arg index. var argumentIndex = 0; var listChildren = argumentsList.getChildren(); - for (var _i = 0; _i < listChildren.length; _i++) { - var child = listChildren[_i]; + for (var _i = 0, listChildren_1 = listChildren; _i < listChildren_1.length; _i++) { + var child = listChildren_1[_i]; if (child === node) { break; } @@ -40049,8 +40492,8 @@ var ts; return n; } var children = n.getChildren(); - for (var _i = 0; _i < children.length; _i++) { - var child = children[_i]; + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; var shouldDiveInChildNode = // previous token is enclosed somewhere in the child (child.pos <= previousToken.pos && child.end > previousToken.end) || @@ -40212,17 +40655,17 @@ var ts; function getNodeModifiers(node) { var flags = ts.getCombinedNodeFlags(node); var result = []; - if (flags & 32 /* Private */) + if (flags & 16 /* Private */) result.push(ts.ScriptElementKindModifier.privateMemberModifier); - if (flags & 64 /* Protected */) + if (flags & 32 /* Protected */) result.push(ts.ScriptElementKindModifier.protectedMemberModifier); - if (flags & 16 /* Public */) + if (flags & 8 /* Public */) result.push(ts.ScriptElementKindModifier.publicMemberModifier); - if (flags & 128 /* Static */) + if (flags & 64 /* Static */) result.push(ts.ScriptElementKindModifier.staticModifier); - if (flags & 256 /* Abstract */) + if (flags & 128 /* Abstract */) result.push(ts.ScriptElementKindModifier.abstractModifier); - if (flags & 1 /* Export */) + if (flags & 2 /* Export */) result.push(ts.ScriptElementKindModifier.exportedModifier); if (ts.isInAmbientContext(node)) result.push(ts.ScriptElementKindModifier.ambientModifier); @@ -42366,8 +42809,8 @@ var ts; } } var inheritedIndentation = -1 /* Unknown */; - for (var _i = 0; _i < nodes.length; _i++) { - var child = nodes[_i]; + for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { + var child = nodes_6[_i]; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true); } if (listEndToken !== 0 /* Unknown */) { @@ -42458,8 +42901,8 @@ var ts; } } function processTrivia(trivia, parent, contextNode, dynamicIndentation) { - for (var _i = 0; _i < trivia.length; _i++) { - var triviaItem = trivia[_i]; + for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { + var triviaItem = trivia_1[_i]; if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); @@ -43056,7 +43499,6 @@ var ts; return node; } } - return node; } } function deriveActualIndentationFromList(list, index, sourceFile, options) { @@ -43307,17 +43749,17 @@ var ts; while (pos < end) { var token = scanner.scan(); var textPos = scanner.getTextPos(); - nodes.push(createNode(token, pos, textPos, 4096 /* Synthetic */, this)); + nodes.push(createNode(token, pos, textPos, 2048 /* Synthetic */, this)); pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(271 /* SyntaxList */, nodes.pos, nodes.end, 4096 /* Synthetic */, this); + var list = createNode(271 /* SyntaxList */, nodes.pos, nodes.end, 2048 /* Synthetic */, this); list._children = []; var pos = nodes.pos; - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -43872,7 +44314,7 @@ var ts; break; case 138 /* Parameter */: // Only consider properties defined as constructor parameters - if (!(node.flags & 112 /* AccessibilityModifier */)) { + if (!(node.flags & 56 /* AccessibilityModifier */)) { break; } // fall through @@ -44148,13 +44590,15 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; + this.getCanonicalFileName = getCanonicalFileName; // script id => script index - this.fileNameToEntry = ts.createFileMap(getCanonicalFileName); + this.currentDirectory = host.getCurrentDirectory(); + this.fileNameToEntry = ts.createFileMap(); // Initialize the list with the root file names var rootFileNames = host.getScriptFileNames(); - for (var _i = 0; _i < rootFileNames.length; _i++) { - var fileName = rootFileNames[_i]; - this.createEntry(fileName); + for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { + var fileName = rootFileNames_1[_i]; + this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); } // store the compilation settings this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); @@ -44162,7 +44606,7 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; - HostCache.prototype.createEntry = function (fileName) { + HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); if (scriptSnapshot) { @@ -44172,36 +44616,37 @@ var ts; scriptSnapshot: scriptSnapshot }; } - this.fileNameToEntry.set(fileName, entry); + this.fileNameToEntry.set(path, entry); return entry; }; - HostCache.prototype.getEntry = function (fileName) { - return this.fileNameToEntry.get(fileName); + HostCache.prototype.getEntry = function (path) { + return this.fileNameToEntry.get(path); }; - HostCache.prototype.contains = function (fileName) { - return this.fileNameToEntry.contains(fileName); + HostCache.prototype.contains = function (path) { + return this.fileNameToEntry.contains(path); }; HostCache.prototype.getOrCreateEntry = function (fileName) { - if (this.contains(fileName)) { - return this.getEntry(fileName); + var path = ts.toPath(fileName, this.currentDirectory, this.getCanonicalFileName); + if (this.contains(path)) { + return this.getEntry(path); } - return this.createEntry(fileName); + return this.createEntry(fileName, path); }; HostCache.prototype.getRootFileNames = function () { var fileNames = []; - this.fileNameToEntry.forEachValue(function (value) { + this.fileNameToEntry.forEachValue(function (path, value) { if (value) { fileNames.push(value.hostFileName); } }); return fileNames; }; - HostCache.prototype.getVersion = function (fileName) { - var file = this.getEntry(fileName); + HostCache.prototype.getVersion = function (path) { + var file = this.getEntry(path); return file && file.version; }; - HostCache.prototype.getScriptSnapshot = function (fileName) { - var file = this.getEntry(fileName); + HostCache.prototype.getScriptSnapshot = function (path) { + var file = this.getEntry(path); return file && file.scriptSnapshot; }; return HostCache; @@ -44383,7 +44828,8 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; - function createDocumentRegistry(useCaseSensitiveFileNames) { + function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. var buckets = {}; @@ -44395,7 +44841,7 @@ var ts; var key = getKeyFromCompilationSettings(settings); var bucket = ts.lookUp(buckets, key); if (!bucket && createIfMissing) { - buckets[key] = bucket = ts.createFileMap(getCanonicalFileName); + buckets[key] = bucket = ts.createFileMap(); } return bucket; } @@ -44403,14 +44849,13 @@ var ts; var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === '_'; }).map(function (name) { var entries = ts.lookUp(buckets, name); var sourceFiles = []; - for (var i in entries) { - var entry = entries.get(i); + entries.forEachValue(function (key, entry) { sourceFiles.push({ - name: i, + name: key, refCount: entry.languageServiceRefCount, references: entry.owners.slice(0) }); - } + }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); return { bucket: name, @@ -44427,7 +44872,8 @@ var ts; } function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true); - var entry = bucket.get(fileName); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = bucket.get(path); if (!entry) { ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); // Have never seen this file with these settings. Create a new source file for it. @@ -44437,7 +44883,7 @@ var ts; languageServiceRefCount: 0, owners: [] }; - bucket.set(fileName, entry); + bucket.set(path, entry); } else { // We have an entry for this file. However, it may be for a different version of @@ -44460,11 +44906,12 @@ var ts; function releaseDocument(fileName, compilationSettings) { var bucket = getBucketForCompilationSettings(compilationSettings, false); ts.Debug.assert(bucket !== undefined); - var entry = bucket.get(fileName); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = bucket.get(path); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.remove(fileName); + bucket.remove(path); } } return { @@ -44871,7 +45318,7 @@ var ts; case 144 /* Constructor */: return ScriptElementKind.constructorImplementationElement; case 137 /* TypeParameter */: return ScriptElementKind.typeParameterElement; case 247 /* EnumMember */: return ScriptElementKind.variableElement; - case 138 /* Parameter */: return (node.flags & 112 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; + case 138 /* Parameter */: return (node.flags & 56 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; case 221 /* ImportEqualsDeclaration */: case 226 /* ImportSpecifier */: case 223 /* ImportClause */: @@ -44897,13 +45344,14 @@ var ts; return CancellationTokenObject; })(); function createLanguageService(host, documentRegistry) { - if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(); } + if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); var ruleProvider; var program; var lastProjectVersion; var useCaseSensitivefileNames = false; var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); + var currentDirectory = host.getCurrentDirectory(); // Check if the localized messages json is set, otherwise query the host for it if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); @@ -44915,8 +45363,7 @@ var ts; } var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName) { - fileName = ts.normalizeSlashes(fileName); - var sourceFile = program.getSourceFile(getCanonicalFileName(fileName)); + var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { throw new Error("Could not find file: '" + fileName + "'."); } @@ -44968,7 +45415,7 @@ var ts; getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: function (fileName, data, writeByteOrderMark) { }, - getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { // stub missing host functionality ts.Debug.assert(!host.resolveModuleNames); @@ -44988,11 +45435,10 @@ var ts; // not part of the new program. if (program) { var oldSourceFiles = program.getSourceFiles(); - for (var _i = 0; _i < oldSourceFiles.length; _i++) { - var oldSourceFile = oldSourceFiles[_i]; - var fileName = oldSourceFile.fileName; - if (!newProgram.getSourceFile(fileName) || changesInCompilationSettingsAffectSyntax) { - documentRegistry.releaseDocument(fileName, oldSettings); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; + if (!newProgram.getSourceFile(oldSourceFile.fileName) || changesInCompilationSettingsAffectSyntax) { + documentRegistry.releaseDocument(oldSourceFile.fileName, oldSettings); } } } @@ -45048,7 +45494,8 @@ var ts; return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); } function sourceFileUpToDate(sourceFile) { - return sourceFile && sourceFile.version === hostCache.getVersion(sourceFile.fileName); + var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); + return sourceFile && sourceFile.version === hostCache.getVersion(path); } function programUpToDate() { // If we haven't create a program yet, then it is not up-to-date @@ -45061,8 +45508,8 @@ var ts; return false; } // If any file is not up-to-date, then the whole program is not up-to-date - for (var _i = 0; _i < rootFileNames.length; _i++) { - var fileName = rootFileNames[_i]; + for (var _i = 0, rootFileNames_2 = rootFileNames; _i < rootFileNames_2.length; _i++) { + var fileName = rootFileNames_2[_i]; if (!sourceFileUpToDate(program.getSourceFile(fileName))) { return false; } @@ -45237,8 +45684,8 @@ var ts; } function checkModifiers(modifiers) { if (modifiers) { - for (var _i = 0; _i < modifiers.length; _i++) { - var modifier = modifiers[_i]; + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; switch (modifier.kind) { case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: @@ -45940,8 +46387,8 @@ var ts; */ function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { var exisingImportsOrExports = {}; - for (var _i = 0; _i < namedImportsOrExports.length; _i++) { - var element = namedImportsOrExports[_i]; + for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { + var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out if (element.getStart() <= position && position <= element.getEnd()) { continue; @@ -45965,8 +46412,8 @@ var ts; return contextualMemberSymbols; } var existingMemberNames = {}; - for (var _i = 0; _i < existingMembers.length; _i++) { - var m = existingMembers[_i]; + for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { + var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members if (m.kind !== 245 /* PropertyAssignment */ && m.kind !== 246 /* ShorthandPropertyAssignment */ && @@ -45999,8 +46446,8 @@ var ts; */ function filterJsxAttributes(symbols, attributes) { var seenNames = {}; - for (var _i = 0; _i < attributes.length; _i++) { - var attr = attributes[_i]; + for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { + var attr = attributes_1[_i]; // If this is the current item we are editing right now, do not filter it out if (attr.getStart() <= position && position <= attr.getEnd()) { continue; @@ -46101,8 +46548,8 @@ var ts; var entries = []; if (symbols) { var nameToSymbol = {}; - for (var _i = 0; _i < symbols.length; _i++) { - var symbol = symbols[_i]; + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var symbol = symbols_3[_i]; var entry = createCompletionEntry(symbol, location); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -46844,8 +47291,8 @@ var ts; } var fileNameToDocumentHighlights = {}; var result = []; - for (var _i = 0; _i < referencedSymbols.length; _i++) { - var referencedSymbol = referencedSymbols[_i]; + for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { + var referencedSymbol = referencedSymbols_1[_i]; for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { var referenceEntry = _b[_a]; var fileName_1 = referenceEntry.fileName; @@ -46989,7 +47436,6 @@ var ts; ts.forEachChild(node, aggregate); } } - ; } /** * For lack of a better name, this function takes a throw statement and returns the @@ -47027,7 +47473,6 @@ var ts; ts.forEachChild(node, aggregate); } } - ; } function ownsBreakOrContinueStatement(owner, statement) { var actualOwner = getBreakOrContinueOwner(statement); @@ -47096,7 +47541,7 @@ var ts; case 219 /* ModuleBlock */: case 248 /* SourceFile */: // Container is either a class declaration or the declaration is a classDeclaration - if (modifierFlag & 256 /* Abstract */) { + if (modifierFlag & 128 /* Abstract */) { nodes = declaration.members.concat(declaration); } else { @@ -47111,7 +47556,7 @@ var ts; nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. - if (modifierFlag & 112 /* AccessibilityModifier */) { + if (modifierFlag & 56 /* AccessibilityModifier */) { var constructor = ts.forEach(container.members, function (member) { return member.kind === 144 /* Constructor */ && member; }); @@ -47119,7 +47564,7 @@ var ts; nodes = nodes.concat(constructor.parameters); } } - else if (modifierFlag & 256 /* Abstract */) { + else if (modifierFlag & 128 /* Abstract */) { nodes = nodes.concat(container); } break; @@ -47135,19 +47580,19 @@ var ts; function getFlagFromModifier(modifier) { switch (modifier) { case 112 /* PublicKeyword */: - return 16 /* Public */; + return 8 /* Public */; case 110 /* PrivateKeyword */: - return 32 /* Private */; + return 16 /* Private */; case 111 /* ProtectedKeyword */: - return 64 /* Protected */; + return 32 /* Protected */; case 113 /* StaticKeyword */: - return 128 /* Static */; + return 64 /* Static */; case 82 /* ExportKeyword */: - return 1 /* Export */; + return 2 /* Export */; case 122 /* DeclareKeyword */: - return 2 /* Ambient */; + return 4 /* Ambient */; case 115 /* AbstractKeyword */: - return 256 /* Abstract */; + return 128 /* Abstract */; default: ts.Debug.fail(); } @@ -47346,8 +47791,8 @@ var ts; return undefined; } var result = []; - for (var _i = 0; _i < documentHighlights.length; _i++) { - var entry = documentHighlights[_i]; + for (var _i = 0, documentHighlights_1 = documentHighlights; _i < documentHighlights_1.length; _i++) { + var entry = documentHighlights_1[_i]; for (var _a = 0, _b = entry.highlightSpans; _a < _b.length; _a++) { var highlightSpan = _b[_a]; result.push({ @@ -47365,8 +47810,8 @@ var ts; return undefined; } var referenceEntries = []; - for (var _i = 0; _i < referenceSymbols.length; _i++) { - var referenceSymbol = referenceSymbols[_i]; + for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) { + var referenceSymbol = referenceSymbols_1[_i]; ts.addRange(referenceEntries, referenceSymbol.references); } return referenceEntries; @@ -47451,8 +47896,8 @@ var ts; } else { var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0; _i < sourceFiles.length; _i++) { - var sourceFile = sourceFiles[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); if (ts.lookUp(nameTable, internedName)) { @@ -47512,7 +47957,7 @@ var ts; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { - var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 32 /* Private */) ? d : undefined; }); + var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 16 /* Private */) ? d : undefined; }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 214 /* ClassDeclaration */); } @@ -47530,8 +47975,8 @@ var ts; var scope = undefined; var declarations = symbol.getDeclarations(); if (declarations) { - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; @@ -47711,7 +48156,7 @@ var ts; return undefined; } // Whether 'super' occurs in a static context within a class. - var staticFlag = 128 /* Static */; + var staticFlag = 64 /* Static */; switch (searchSpaceNode.kind) { case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: @@ -47739,7 +48184,7 @@ var ts; // If we have a 'super' container, we must have an enclosing class. // Now make sure the owning class is the same as the search-space // and has the same static qualifier as the original 'super's owner. - if (container && (128 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { + if (container && (64 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { references.push(getReferenceEntryFromNode(node)); } }); @@ -47749,7 +48194,7 @@ var ts; function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. - var staticFlag = 128 /* Static */; + var staticFlag = 64 /* Static */; switch (searchSpaceNode.kind) { case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: @@ -47827,7 +48272,7 @@ var ts; case 214 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. - if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 128 /* Static */) === staticFlag) { + if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 64 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; @@ -47998,8 +48443,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; var declarationMeaning = getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -48115,7 +48560,6 @@ var ts; return 4 /* Namespace */ | 1 /* Value */; } return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; - ts.Debug.fail("Unknown declaration type"); } function isTypeReference(node) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { @@ -48694,8 +49138,8 @@ var ts; if (matchKind) { var parentElement = token.parent; var childNodes = parentElement.getChildren(sourceFile); - for (var _i = 0; _i < childNodes.length; _i++) { - var current = childNodes[_i]; + for (var _i = 0, childNodes_1 = childNodes; _i < childNodes_1.length; _i++) { + var current = childNodes_1[_i]; if (current.kind === matchKind) { var range1 = ts.createTextSpan(token.getStart(sourceFile), token.getWidth(sourceFile)); var range2 = ts.createTextSpan(current.getStart(sourceFile), current.getWidth(sourceFile)); @@ -49025,8 +49469,8 @@ var ts; // Disallow rename for elements that are defined in the standard TypeScript library. var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); if (defaultLibFileName) { - for (var _i = 0; _i < declarations.length; _i++) { - var current = declarations[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var current = declarations_10[_i]; var sourceFile_2 = current.getSourceFile(); var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); if (sourceFile_2 && getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)) === getCanonicalFileName(ts.normalizePath(defaultLibFileName))) { @@ -49609,7 +50053,7 @@ var ts; */ function spanInSourceFileAtLocation(sourceFile, position) { // Cannot set breakpoint in dts file - if (sourceFile.flags & 8192 /* DeclarationFile */) { + if (sourceFile.flags & 4096 /* DeclarationFile */) { return undefined; } var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); @@ -49827,7 +50271,7 @@ var ts; ? variableDeclaration.parent.parent.initializer.declarations : undefined; // Breakpoint is possible in variableDeclaration only if there is initialization - if (variableDeclaration.initializer || (variableDeclaration.flags & 1 /* Export */)) { + if (variableDeclaration.initializer || (variableDeclaration.flags & 2 /* Export */)) { if (declarations && declarations[0] === variableDeclaration) { if (isParentVariableStatement) { // First declaration - include let keyword @@ -49853,7 +50297,7 @@ var ts; function canHaveSpanInParameterDeclaration(parameter) { // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier return !!parameter.initializer || parameter.dotDotDotToken !== undefined || - !!(parameter.flags & 16 /* Public */) || !!(parameter.flags & 32 /* Private */); + !!(parameter.flags & 8 /* Public */) || !!(parameter.flags & 16 /* Private */); } function spanInParameterDeclaration(parameter) { if (canHaveSpanInParameterDeclaration(parameter)) { @@ -49873,7 +50317,7 @@ var ts; } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return !!(functionDeclaration.flags & 1 /* Export */) || + return !!(functionDeclaration.flags & 2 /* Export */) || (functionDeclaration.parent.kind === 214 /* ClassDeclaration */ && functionDeclaration.kind !== 144 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { @@ -49967,7 +50411,6 @@ var ts; // fall through. case 244 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - ; case 220 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; @@ -50008,8 +50451,6 @@ var ts; default: return spanInNode(node.parent); } - // Default to parent node - return spanInNode(node.parent); } function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration @@ -50138,7 +50579,6 @@ var ts; // TODO: should this be '==='? if (settingsJson == null || settingsJson == "") { throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); - return null; } return JSON.parse(settingsJson); }; diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index badaff1c3e2..d2758e6d5e9 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -17,19 +17,22 @@ declare namespace ts { interface Map { [index: string]: T; } + type Path = string & { + __pathBrand: any; + }; interface FileMap { - get(fileName: string): T; - set(fileName: string, value: T): void; - contains(fileName: string): boolean; - remove(fileName: string): void; - forEachValue(f: (v: T) => void): void; + get(fileName: Path): T; + set(fileName: Path, value: T): void; + contains(fileName: Path): boolean; + remove(fileName: Path): void; + forEachValue(f: (key: Path, v: T) => void): void; clear(): void; } interface TextRange { pos: number; end: number; } - const enum SyntaxKind { + enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, SingleLineCommentTrivia = 2, @@ -327,31 +330,34 @@ declare namespace ts { LastBinaryOperator = 68, FirstNode = 135, } - const enum NodeFlags { + enum NodeFlags { None = 0, - Export = 1, - Ambient = 2, - Public = 16, - Private = 32, - Protected = 64, - Static = 128, - Abstract = 256, - Async = 512, - Default = 1024, - MultiLine = 2048, - Synthetic = 4096, - DeclarationFile = 8192, - Let = 16384, - Const = 32768, - OctalLiteral = 65536, - Namespace = 131072, - ExportContext = 262144, - ContainsThis = 524288, - Modifier = 2035, - AccessibilityModifier = 112, - BlockScoped = 49152, + Export = 2, + Ambient = 4, + Public = 8, + Private = 16, + Protected = 32, + Static = 64, + Abstract = 128, + Async = 256, + Default = 512, + MultiLine = 1024, + Synthetic = 2048, + DeclarationFile = 4096, + Let = 8192, + Const = 16384, + OctalLiteral = 32768, + Namespace = 65536, + ExportContext = 131072, + ContainsThis = 262144, + HasImplicitReturn = 524288, + HasExplicitReturn = 1048576, + Modifier = 1022, + AccessibilityModifier = 56, + BlockScoped = 24576, + ReachabilityCheckFlags = 1572864, } - const enum JsxFlags { + enum JsxFlags { None = 0, IntrinsicNamedElement = 1, IntrinsicIndexedElement = 2, @@ -931,6 +937,7 @@ declare namespace ts { statements: NodeArray; endOfFileToken: Node; fileName: string; + path: Path; text: string; amdDependencies: { path: string; @@ -1093,7 +1100,7 @@ declare namespace ts { trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; reportInaccessibleThisError(): void; } - const enum TypeFormatFlags { + enum TypeFormatFlags { None = 0, WriteArrayAsGenericType = 1, UseTypeOfFunction = 2, @@ -1104,7 +1111,7 @@ declare namespace ts { InElementType = 64, UseFullyQualifiedType = 128, } - const enum SymbolFormatFlags { + enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, @@ -1114,7 +1121,7 @@ declare namespace ts { parameterIndex: number; type: Type; } - const enum SymbolFlags { + enum SymbolFlags { None = 0, FunctionScopedVariable = 1, BlockScopedVariable = 2, @@ -1191,7 +1198,7 @@ declare namespace ts { interface SymbolTable { [index: string]: Symbol; } - const enum TypeFlags { + enum TypeFlags { Any = 1, String = 2, Number = 4, @@ -1262,7 +1269,7 @@ declare namespace ts { interface TypeParameter extends Type { constraint: Type; } - const enum SignatureKind { + enum SignatureKind { Call = 0, Construct = 1, } @@ -1272,7 +1279,7 @@ declare namespace ts { parameters: Symbol[]; typePredicate?: TypePredicate; } - const enum IndexKind { + enum IndexKind { String = 0, Number = 1, } @@ -1307,7 +1314,7 @@ declare namespace ts { Error = 1, Message = 2, } - const enum ModuleResolutionKind { + enum ModuleResolutionKind { Classic = 1, NodeJs = 2, } @@ -1352,10 +1359,14 @@ declare namespace ts { experimentalDecorators?: boolean; emitDecoratorMetadata?: boolean; moduleResolution?: ModuleResolutionKind; + allowUnusedLabels?: boolean; + allowUnreachableCode?: boolean; + noImplicitReturns?: boolean; + noFallthroughCasesInSwitch?: boolean; forceConsistentCasingInFileNames?: boolean; [option: string]: string | number | boolean; } - const enum ModuleKind { + enum ModuleKind { None = 0, CommonJS = 1, AMD = 2, @@ -1364,12 +1375,12 @@ declare namespace ts { ES6 = 5, ES2015 = 5, } - const enum JsxEmit { + enum JsxEmit { None = 0, Preserve = 1, React = 2, } - const enum NewLineKind { + enum NewLineKind { CarriageReturnLineFeed = 0, LineFeed = 1, } @@ -1377,14 +1388,14 @@ declare namespace ts { line: number; character: number; } - const enum ScriptTarget { + enum ScriptTarget { ES3 = 0, ES5 = 1, ES6 = 2, ES2015 = 2, Latest = 2, } - const enum LanguageVariant { + enum LanguageVariant { Standard = 0, JSX = 1, } @@ -1938,7 +1949,7 @@ declare namespace ts { outputFiles: OutputFile[]; emitSkipped: boolean; } - const enum OutputFileType { + enum OutputFileType { JavaScript = 0, SourceMap = 1, Declaration = 2, @@ -1948,7 +1959,7 @@ declare namespace ts { writeByteOrderMark: boolean; text: string; } - const enum EndOfLineState { + enum EndOfLineState { None = 0, InMultiLineCommentTrivia = 1, InSingleQuoteStringLiteral = 2, @@ -2116,7 +2127,7 @@ declare namespace ts { static parameterName: string; static docCommentTagName: string; } - const enum ClassificationType { + enum ClassificationType { comment = 1, identifier = 2, keyword = 3, @@ -2159,7 +2170,7 @@ declare namespace ts { let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; function createGetCanonicalFileName(useCaseSensitivefileNames: boolean): (fileName: string) => string; - function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry; + function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo; function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; function createClassifier(): Classifier; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 1e0c0edad05..8b0ef04f96e 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -350,27 +350,30 @@ var ts; var SyntaxKind = ts.SyntaxKind; (function (NodeFlags) { NodeFlags[NodeFlags["None"] = 0] = "None"; - NodeFlags[NodeFlags["Export"] = 1] = "Export"; - NodeFlags[NodeFlags["Ambient"] = 2] = "Ambient"; - NodeFlags[NodeFlags["Public"] = 16] = "Public"; - NodeFlags[NodeFlags["Private"] = 32] = "Private"; - NodeFlags[NodeFlags["Protected"] = 64] = "Protected"; - NodeFlags[NodeFlags["Static"] = 128] = "Static"; - NodeFlags[NodeFlags["Abstract"] = 256] = "Abstract"; - NodeFlags[NodeFlags["Async"] = 512] = "Async"; - NodeFlags[NodeFlags["Default"] = 1024] = "Default"; - NodeFlags[NodeFlags["MultiLine"] = 2048] = "MultiLine"; - NodeFlags[NodeFlags["Synthetic"] = 4096] = "Synthetic"; - NodeFlags[NodeFlags["DeclarationFile"] = 8192] = "DeclarationFile"; - NodeFlags[NodeFlags["Let"] = 16384] = "Let"; - NodeFlags[NodeFlags["Const"] = 32768] = "Const"; - NodeFlags[NodeFlags["OctalLiteral"] = 65536] = "OctalLiteral"; - NodeFlags[NodeFlags["Namespace"] = 131072] = "Namespace"; - NodeFlags[NodeFlags["ExportContext"] = 262144] = "ExportContext"; - NodeFlags[NodeFlags["ContainsThis"] = 524288] = "ContainsThis"; - NodeFlags[NodeFlags["Modifier"] = 2035] = "Modifier"; - NodeFlags[NodeFlags["AccessibilityModifier"] = 112] = "AccessibilityModifier"; - NodeFlags[NodeFlags["BlockScoped"] = 49152] = "BlockScoped"; + NodeFlags[NodeFlags["Export"] = 2] = "Export"; + NodeFlags[NodeFlags["Ambient"] = 4] = "Ambient"; + NodeFlags[NodeFlags["Public"] = 8] = "Public"; + NodeFlags[NodeFlags["Private"] = 16] = "Private"; + NodeFlags[NodeFlags["Protected"] = 32] = "Protected"; + NodeFlags[NodeFlags["Static"] = 64] = "Static"; + NodeFlags[NodeFlags["Abstract"] = 128] = "Abstract"; + NodeFlags[NodeFlags["Async"] = 256] = "Async"; + NodeFlags[NodeFlags["Default"] = 512] = "Default"; + NodeFlags[NodeFlags["MultiLine"] = 1024] = "MultiLine"; + NodeFlags[NodeFlags["Synthetic"] = 2048] = "Synthetic"; + NodeFlags[NodeFlags["DeclarationFile"] = 4096] = "DeclarationFile"; + NodeFlags[NodeFlags["Let"] = 8192] = "Let"; + NodeFlags[NodeFlags["Const"] = 16384] = "Const"; + NodeFlags[NodeFlags["OctalLiteral"] = 32768] = "OctalLiteral"; + NodeFlags[NodeFlags["Namespace"] = 65536] = "Namespace"; + NodeFlags[NodeFlags["ExportContext"] = 131072] = "ExportContext"; + NodeFlags[NodeFlags["ContainsThis"] = 262144] = "ContainsThis"; + NodeFlags[NodeFlags["HasImplicitReturn"] = 524288] = "HasImplicitReturn"; + NodeFlags[NodeFlags["HasExplicitReturn"] = 1048576] = "HasExplicitReturn"; + NodeFlags[NodeFlags["Modifier"] = 1022] = "Modifier"; + NodeFlags[NodeFlags["AccessibilityModifier"] = 56] = "AccessibilityModifier"; + NodeFlags[NodeFlags["BlockScoped"] = 24576] = "BlockScoped"; + NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 1572864] = "ReachabilityCheckFlags"; })(ts.NodeFlags || (ts.NodeFlags = {})); var NodeFlags = ts.NodeFlags; /* @internal */ @@ -690,6 +693,12 @@ var ts; })(ts.LanguageVariant || (ts.LanguageVariant = {})); var LanguageVariant = ts.LanguageVariant; /* @internal */ + (function (DiagnosticStyle) { + DiagnosticStyle[DiagnosticStyle["Simple"] = 0] = "Simple"; + DiagnosticStyle[DiagnosticStyle["Pretty"] = 1] = "Pretty"; + })(ts.DiagnosticStyle || (ts.DiagnosticStyle = {})); + var DiagnosticStyle = ts.DiagnosticStyle; + /* @internal */ (function (CharacterCodes) { CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter"; CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter"; @@ -838,40 +847,50 @@ var ts; Ternary[Ternary["True"] = -1] = "True"; })(ts.Ternary || (ts.Ternary = {})); var Ternary = ts.Ternary; - function createFileMap(getCanonicalFileName) { + function createFileMap(keyMapper) { var files = {}; return { get: get, set: set, contains: contains, remove: remove, - clear: clear, - forEachValue: forEachValueInMap + forEachValue: forEachValueInMap, + clear: clear }; - function set(fileName, value) { - files[normalizeKey(fileName)] = value; - } - function get(fileName) { - return files[normalizeKey(fileName)]; - } - function contains(fileName) { - return hasProperty(files, normalizeKey(fileName)); - } - function remove(fileName) { - var key = normalizeKey(fileName); - delete files[key]; - } function forEachValueInMap(f) { - forEachValue(files, f); + for (var key in files) { + f(key, files[key]); + } } - function normalizeKey(key) { - return getCanonicalFileName(normalizeSlashes(key)); + // path should already be well-formed so it does not need to be normalized + function get(path) { + return files[toKey(path)]; + } + function set(path, value) { + files[toKey(path)] = value; + } + function contains(path) { + return hasProperty(files, toKey(path)); + } + function remove(path) { + var key = toKey(path); + delete files[key]; } function clear() { files = {}; } + function toKey(path) { + return keyMapper ? keyMapper(path) : path; + } } ts.createFileMap = createFileMap; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; (function (Comparison) { Comparison[Comparison["LessThan"] = -1] = "LessThan"; Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; @@ -897,8 +916,8 @@ var ts; ts.forEach = forEach; function contains(array, value) { if (array) { - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { + var v = array_1[_i]; if (v === value) { return true; } @@ -921,8 +940,8 @@ var ts; function countWhere(array, predicate) { var count = 0; if (array) { - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_2 = array; _i < array_2.length; _i++) { + var v = array_2[_i]; if (predicate(v)) { count++; } @@ -935,8 +954,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var item = array[_i]; + for (var _i = 0, array_3 = array; _i < array_3.length; _i++) { + var item = array_3[_i]; if (f(item)) { result.push(item); } @@ -949,8 +968,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_4 = array; _i < array_4.length; _i++) { + var v = array_4[_i]; result.push(f(v)); } } @@ -969,8 +988,8 @@ var ts; var result; if (array) { result = []; - for (var _i = 0; _i < array.length; _i++) { - var item = array[_i]; + for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { + var item = array_5[_i]; if (!contains(result, item)) { result.push(item); } @@ -981,8 +1000,8 @@ var ts; ts.deduplicate = deduplicate; function sum(array, prop) { var result = 0; - for (var _i = 0; _i < array.length; _i++) { - var v = array[_i]; + for (var _i = 0, array_6 = array; _i < array_6.length; _i++) { + var v = array_6[_i]; result += v[prop]; } return result; @@ -990,8 +1009,8 @@ var ts; ts.sum = sum; function addRange(to, from) { if (to && from) { - for (var _i = 0; _i < from.length; _i++) { - var v = from[_i]; + for (var _i = 0, from_1 = from; _i < from_1.length; _i++) { + var v = from_1[_i]; to.push(v); } } @@ -1341,8 +1360,8 @@ var ts; function getNormalizedParts(normalizedSlashedPath, rootLength) { var parts = normalizedSlashedPath.substr(rootLength).split(ts.directorySeparator); var normalized = []; - for (var _i = 0; _i < parts.length; _i++) { - var part = parts[_i]; + for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) { + var part = parts_1[_i]; if (part !== ".") { if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { normalized.pop(); @@ -1521,8 +1540,8 @@ var ts; if (!fileName) { return false; } - for (var _i = 0; _i < ts.supportedExtensions.length; _i++) { - var extension = ts.supportedExtensions[_i]; + for (var _i = 0, supportedExtensions_1 = ts.supportedExtensions; _i < supportedExtensions_1.length; _i++) { + var extension = supportedExtensions_1[_i]; if (fileExtensionIs(fileName, extension)) { return true; } @@ -1532,8 +1551,8 @@ var ts; ts.isSupportedSourceFileName = isSupportedSourceFileName; var extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; function removeFileExtension(path) { - for (var _i = 0; _i < extensionsToRemove.length; _i++) { - var ext = extensionsToRemove[_i]; + for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) { + var ext = extensionsToRemove_1[_i]; if (fileExtensionIs(path, ext)) { return path.substr(0, path.length - ext.length); } @@ -1614,8 +1633,8 @@ var ts; })(Debug = ts.Debug || (ts.Debug = {})); function copyListRemovingItem(item, list) { var copiedList = []; - for (var _i = 0; _i < list.length; _i++) { - var e = list[_i]; + for (var _i = 0, list_1 = list; _i < list_1.length; _i++) { + var e = list_1[_i]; if (e !== item) { copiedList.push(e); } @@ -1709,16 +1728,16 @@ var ts; function visitDirectory(path) { var folder = fso.GetFolder(path || "."); var files = getNames(folder.files); - for (var _i = 0; _i < files.length; _i++) { - var current = files[_i]; + for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { + var current = files_1[_i]; var name_1 = ts.combinePaths(path, current); if ((!extension || ts.fileExtensionIs(name_1, extension)) && !ts.contains(exclude, getCanonicalPath(name_1))) { result.push(name_1); } } var subfolders = getNames(folder.subfolders); - for (var _a = 0; _a < subfolders.length; _a++) { - var current = subfolders[_a]; + for (var _a = 0, subfolders_1 = subfolders; _a < subfolders_1.length; _a++) { + var current = subfolders_1[_a]; var name_2 = ts.combinePaths(path, current); if (!ts.contains(exclude, getCanonicalPath(name_2))) { visitDirectory(name_2); @@ -1769,6 +1788,7 @@ var ts; var _fs = require("fs"); var _path = require("path"); var _os = require("os"); + var _tty = require("tty"); // average async stat takes about 30 microseconds // set chunk size to do 30 files in < 1 millisecond function createWatchedFileSet(interval, chunkSize) { @@ -1906,8 +1926,8 @@ var ts; function visitDirectory(path) { var files = _fs.readdirSync(path || ".").sort(); var directories = []; - for (var _i = 0; _i < files.length; _i++) { - var current = files[_i]; + for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { + var current = files_2[_i]; var name_3 = ts.combinePaths(path, current); if (!ts.contains(exclude, getCanonicalPath(name_3))) { var stat = _fs.statSync(name_3); @@ -1921,8 +1941,8 @@ var ts; } } } - for (var _a = 0; _a < directories.length; _a++) { - var current = directories[_a]; + for (var _a = 0, directories_1 = directories; _a < directories_1.length; _a++) { + var current = directories_1[_a]; visitDirectory(current); } } @@ -1932,15 +1952,7 @@ var ts; newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, write: function (s) { - var buffer = new Buffer(s, "utf8"); - var offset = 0; - var toWrite = buffer.length; - var written = 0; - // 1 is a standard descriptor for stdout - while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) { - offset += written; - toWrite -= written; - } + process.stdout.write(s); }, readFile: readFile, writeFile: writeFile, @@ -2223,6 +2235,7 @@ var ts; await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: ts.DiagnosticCategory.Error, key: "await_expression_is_only_allowed_within_an_async_function_1308", message: "'await' expression is only allowed within an async function." }, Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: ts.DiagnosticCategory.Error, key: "Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher_1311", message: "Async functions are only available when targeting ECMAScript 6 and higher." }, can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment: { code: 1312, category: ts.DiagnosticCategory.Error, key: "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312", message: "'=' can only be used in an object literal property inside a destructuring assignment." }, + The_body_of_an_if_statement_cannot_be_the_empty_statement: { code: 1313, category: ts.DiagnosticCategory.Error, key: "The_body_of_an_if_statement_cannot_be_the_empty_statement_1313", message: "The body of an 'if' statement cannot be the empty statement." }, Duplicate_identifier_0: { code: 2300, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_0_2300", message: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: ts.DiagnosticCategory.Error, key: "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", message: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: ts.DiagnosticCategory.Error, key: "Static_members_cannot_reference_class_type_parameters_2302", message: "Static members cannot reference class type parameters." }, @@ -2275,7 +2288,7 @@ var ts; Neither_type_0_nor_type_1_is_assignable_to_the_other: { code: 2352, category: ts.DiagnosticCategory.Error, key: "Neither_type_0_nor_type_1_is_assignable_to_the_other_2352", message: "Neither type '{0}' nor type '{1}' is assignable to the other." }, Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1: { code: 2353, category: ts.DiagnosticCategory.Error, key: "Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1_2353", message: "Object literal may only specify known properties, and '{0}' does not exist in type '{1}'." }, No_best_common_type_exists_among_return_expressions: { code: 2354, category: ts.DiagnosticCategory.Error, key: "No_best_common_type_exists_among_return_expressions_2354", message: "No best common type exists among return expressions." }, - A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_th_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement." }, + A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value: { code: 2355, category: ts.DiagnosticCategory.Error, key: "A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_2355", message: "A function whose declared type is neither 'void' nor 'any' must return a value." }, An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type: { code: 2356, category: ts.DiagnosticCategory.Error, key: "An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type_2356", message: "An arithmetic operand must be of type 'any', 'number' or an enum type." }, The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer: { code: 2357, category: ts.DiagnosticCategory.Error, key: "The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_property_or_indexer_2357", message: "The operand of an increment or decrement operator must be a variable, property or indexer." }, The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2358, category: ts.DiagnosticCategory.Error, key: "The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_paramete_2358", message: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter." }, @@ -2296,7 +2309,7 @@ var ts; Duplicate_number_index_signature: { code: 2375, category: ts.DiagnosticCategory.Error, key: "Duplicate_number_index_signature_2375", message: "Duplicate number index signature." }, A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties: { code: 2376, category: ts.DiagnosticCategory.Error, key: "A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_proper_2376", message: "A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties." }, Constructors_for_derived_classes_must_contain_a_super_call: { code: 2377, category: ts.DiagnosticCategory.Error, key: "Constructors_for_derived_classes_must_contain_a_super_call_2377", message: "Constructors for derived classes must contain a 'super' call." }, - A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement_2378", message: "A 'get' accessor must return a value or consist of a single 'throw' statement." }, + A_get_accessor_must_return_a_value: { code: 2378, category: ts.DiagnosticCategory.Error, key: "A_get_accessor_must_return_a_value_2378", message: "A 'get' accessor must return a value." }, Getter_and_setter_accessors_do_not_agree_in_visibility: { code: 2379, category: ts.DiagnosticCategory.Error, key: "Getter_and_setter_accessors_do_not_agree_in_visibility_2379", message: "Getter and setter accessors do not agree in visibility." }, get_and_set_accessor_must_have_the_same_type: { code: 2380, category: ts.DiagnosticCategory.Error, key: "get_and_set_accessor_must_have_the_same_type_2380", message: "'get' and 'set' accessor must have the same type." }, A_signature_with_an_implementation_cannot_use_a_string_literal_type: { code: 2381, category: ts.DiagnosticCategory.Error, key: "A_signature_with_an_implementation_cannot_use_a_string_literal_type_2381", message: "A signature with an implementation cannot use a string literal type." }, @@ -2586,8 +2599,6 @@ var ts; NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE_6061", message: "NEWLINE" }, Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: ts.DiagnosticCategory.Error, key: "Argument_for_newLine_option_must_be_CRLF_or_LF_6062", message: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, Argument_for_moduleResolution_option_must_be_node_or_classic: { code: 6063, category: ts.DiagnosticCategory.Error, key: "Argument_for_moduleResolution_option_must_be_node_or_classic_6063", message: "Argument for '--moduleResolution' option must be 'node' or 'classic'." }, - Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, - Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, Enables_experimental_support_for_ES7_decorators: { code: 6065, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_decorators_6065", message: "Enables experimental support for ES7 decorators." }, Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066", message: "Enables experimental support for emitting type metadata for decorators." }, Enables_experimental_support_for_ES7_async_functions: { code: 6068, category: ts.DiagnosticCategory.Message, key: "Enables_experimental_support_for_ES7_async_functions_6068", message: "Enables experimental support for ES7 async functions." }, @@ -2595,7 +2606,14 @@ var ts; Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file: { code: 6070, category: ts.DiagnosticCategory.Message, key: "Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file_6070", message: "Initializes a TypeScript project and creates a tsconfig.json file." }, Successfully_created_a_tsconfig_json_file: { code: 6071, category: ts.DiagnosticCategory.Message, key: "Successfully_created_a_tsconfig_json_file_6071", message: "Successfully created a tsconfig.json file." }, Suppress_excess_property_checks_for_object_literals: { code: 6072, category: ts.DiagnosticCategory.Message, key: "Suppress_excess_property_checks_for_object_literals_6072", message: "Suppress excess property checks for object literals." }, - Disallow_inconsistently_cased_references_to_the_same_file: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6073", message: "Disallow inconsistently-cased references to the same file." }, + Stylize_errors_and_messages_using_color_and_context_experimental: { code: 6073, category: ts.DiagnosticCategory.Message, key: "Stylize_errors_and_messages_using_color_and_context_experimental_6073", message: "Stylize errors and messages using color and context. (experimental)" }, + Do_not_report_errors_on_unused_labels: { code: 6074, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unused_labels_6074", message: "Do not report errors on unused labels." }, + Report_error_when_not_all_code_paths_in_function_return_a_value: { code: 6075, category: ts.DiagnosticCategory.Message, key: "Report_error_when_not_all_code_paths_in_function_return_a_value_6075", message: "Report error when not all code paths in function return a value." }, + Report_errors_for_fallthrough_cases_in_switch_statement: { code: 6076, category: ts.DiagnosticCategory.Message, key: "Report_errors_for_fallthrough_cases_in_switch_statement_6076", message: "Report errors for fallthrough cases in switch statement." }, + Do_not_report_errors_on_unreachable_code: { code: 6077, category: ts.DiagnosticCategory.Message, key: "Do_not_report_errors_on_unreachable_code_6077", message: "Do not report errors on unreachable code." }, + Disallow_inconsistently_cased_references_to_the_same_file: { code: 6078, category: ts.DiagnosticCategory.Message, key: "Disallow_inconsistently_cased_references_to_the_same_file_6078", message: "Disallow inconsistently-cased references to the same file." }, + Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: ts.DiagnosticCategory.Message, key: "Specify_JSX_code_generation_Colon_preserve_or_react_6080", message: "Specify JSX code generation: 'preserve' or 'react'" }, + Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: ts.DiagnosticCategory.Message, key: "Argument_for_jsx_must_be_preserve_or_react_6081", message: "Argument for '--jsx' must be 'preserve' or 'react'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2613,6 +2631,10 @@ var ts; Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024", message: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: ts.DiagnosticCategory.Error, key: "Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_typ_7025", message: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." }, JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026", message: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists" }, + Unreachable_code_detected: { code: 7027, category: ts.DiagnosticCategory.Error, key: "Unreachable_code_detected_7027", message: "Unreachable code detected." }, + Unused_label: { code: 7028, category: ts.DiagnosticCategory.Error, key: "Unused_label_7028", message: "Unused label." }, + Fallthrough_case_in_switch: { code: 7029, category: ts.DiagnosticCategory.Error, key: "Fallthrough_case_in_switch_7029", message: "Fallthrough case in switch." }, + Not_all_code_paths_return_a_value: { code: 7030, category: ts.DiagnosticCategory.Error, key: "Not_all_code_paths_return_a_value_7030", message: "Not all code paths return a value." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -4166,6 +4188,20 @@ var ts; ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly"; })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); var ModuleInstanceState = ts.ModuleInstanceState; + var Reachability; + (function (Reachability) { + Reachability[Reachability["Unintialized"] = 1] = "Unintialized"; + Reachability[Reachability["Reachable"] = 2] = "Reachable"; + Reachability[Reachability["Unreachable"] = 4] = "Unreachable"; + Reachability[Reachability["ReportedUnreachable"] = 8] = "ReportedUnreachable"; + })(Reachability || (Reachability = {})); + function or(state1, state2) { + return (state1 | state2) & 2 /* Reachable */ + ? 2 /* Reachable */ + : (state1 & state2) & 8 /* ReportedUnreachable */ + ? 8 /* ReportedUnreachable */ + : 4 /* Unreachable */; + } function getModuleInstanceState(node) { // A module is uninstantiated if it contains only // 1. interface declarations, type alias declarations @@ -4175,7 +4211,7 @@ var ts; else if (ts.isConstEnumDeclaration(node)) { return 2 /* ConstEnumOnly */; } - else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && !(node.flags & 1 /* Export */)) { + else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && !(node.flags & 2 /* Export */)) { return 0 /* NonInstantiated */; } else if (node.kind === 219 /* ModuleBlock */) { @@ -4226,31 +4262,56 @@ var ts; // Functions, Methods, Modules, Source-files. ContainerFlags[ContainerFlags["IsContainerWithLocals"] = 5] = "IsContainerWithLocals"; })(ContainerFlags || (ContainerFlags = {})); - function bindSourceFile(file) { + var binder = createBinder(); + function bindSourceFile(file, options) { var start = new Date().getTime(); - bindSourceFileWorker(file); + binder(file, options); ts.bindTime += new Date().getTime() - start; } ts.bindSourceFile = bindSourceFile; - function bindSourceFileWorker(file) { + function createBinder() { + var file; + var options; var parent; var container; var blockScopeContainer; var lastContainer; var seenThisKeyword; + // state used by reachability checks + var hasExplicitReturn; + var currentReachabilityState; + var labelStack; + var labelIndexMap; + var implicitLabels; // If this file is an external module, then it is automatically in strict-mode according to // ES6. If it is not an external module, then we'll determine if it is in strict mode or // not depending on if we see "use strict" in certain places (or if we hit a class/namespace). - var inStrictMode = !!file.externalModuleIndicator; + var inStrictMode; var symbolCount = 0; - var Symbol = ts.objectAllocator.getSymbolConstructor(); - var classifiableNames = {}; - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; + var Symbol; + var classifiableNames; + function bindSourceFile(f, opts) { + file = f; + options = opts; + inStrictMode = !!file.externalModuleIndicator; + classifiableNames = {}; + Symbol = ts.objectAllocator.getSymbolConstructor(); + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + hasExplicitReturn = false; + labelStack = undefined; + labelIndexMap = undefined; + implicitLabels = undefined; } - return; + return bindSourceFile; function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -4303,7 +4364,7 @@ var ts; return node.isExportEquals ? "export=" : "default"; case 213 /* FunctionDeclaration */: case 214 /* ClassDeclaration */: - return node.flags & 1024 /* Default */ ? "default" : undefined; + return node.flags & 512 /* Default */ ? "default" : undefined; } } function getDisplayName(node) { @@ -4319,7 +4380,7 @@ var ts; */ function declareSymbol(symbolTable, parent, node, includes, excludes) { ts.Debug.assert(!ts.hasDynamicName(node)); - var isDefaultExport = node.flags & 1024 /* Default */; + var isDefaultExport = node.flags & 512 /* Default */; // The exported symbol for an export default function/class node is always named "default" var name = isDefaultExport && parent ? "default" : getDeclarationName(node); var symbol; @@ -4358,7 +4419,7 @@ var ts; ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; ts.forEach(symbol.declarations, function (declaration) { - if (declaration.flags & 1024 /* Default */) { + if (declaration.flags & 512 /* Default */) { message = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } }); @@ -4377,7 +4438,7 @@ var ts; return symbol; } function declareModuleMember(node, symbolFlags, symbolExcludes) { - var hasExportModifier = ts.getCombinedNodeFlags(node) & 1 /* Export */; + var hasExportModifier = ts.getCombinedNodeFlags(node) & 2 /* Export */; if (symbolFlags & 8388608 /* Alias */) { if (node.kind === 230 /* ExportSpecifier */ || (node.kind === 221 /* ImportEqualsDeclaration */ && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -4398,7 +4459,7 @@ var ts; // 2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol, // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. - if (hasExportModifier || container.flags & 262144 /* ExportContext */) { + if (hasExportModifier || container.flags & 131072 /* ExportContext */) { var exportKind = (symbolFlags & 107455 /* Value */ ? 1048576 /* ExportValue */ : 0) | (symbolFlags & 793056 /* Type */ ? 2097152 /* ExportType */ : 0) | (symbolFlags & 1536 /* Namespace */ ? 4194304 /* ExportNamespace */ : 0); @@ -4453,18 +4514,229 @@ var ts; blockScopeContainer = node; blockScopeContainer.locals = undefined; } - if (node.kind === 215 /* InterfaceDeclaration */) { + var savedReachabilityState; + var savedLabelStack; + var savedLabels; + var savedImplicitLabels; + var savedHasExplicitReturn; + var kind = node.kind; + var flags = node.flags; + // reset all reachability check related flags on node (for incremental scenarios) + flags &= ~1572864 /* ReachabilityCheckFlags */; + if (kind === 215 /* InterfaceDeclaration */) { seenThisKeyword = false; - ts.forEachChild(node, bind); - node.flags = seenThisKeyword ? node.flags | 524288 /* ContainsThis */ : node.flags & ~524288 /* ContainsThis */; } - else { - ts.forEachChild(node, bind); + var saveState = kind === 248 /* SourceFile */ || kind === 219 /* ModuleBlock */ || ts.isFunctionLikeKind(kind); + if (saveState) { + savedReachabilityState = currentReachabilityState; + savedLabelStack = labelStack; + savedLabels = labelIndexMap; + savedImplicitLabels = implicitLabels; + savedHasExplicitReturn = hasExplicitReturn; + currentReachabilityState = 2 /* Reachable */; + hasExplicitReturn = false; + labelStack = labelIndexMap = implicitLabels = undefined; + } + bindReachableStatement(node); + if (currentReachabilityState === 2 /* Reachable */ && ts.isFunctionLikeKind(kind) && ts.nodeIsPresent(node.body)) { + flags |= 524288 /* HasImplicitReturn */; + if (hasExplicitReturn) { + flags |= 1048576 /* HasExplicitReturn */; + } + } + if (kind === 215 /* InterfaceDeclaration */) { + flags = seenThisKeyword ? flags | 262144 /* ContainsThis */ : flags & ~262144 /* ContainsThis */; + } + node.flags = flags; + if (saveState) { + hasExplicitReturn = savedHasExplicitReturn; + currentReachabilityState = savedReachabilityState; + labelStack = savedLabelStack; + labelIndexMap = savedLabels; + implicitLabels = savedImplicitLabels; } container = saveContainer; parent = saveParent; blockScopeContainer = savedBlockScopeContainer; } + /** + * Returns true if node and its subnodes were successfully traversed. + * Returning false means that node was not examined and caller needs to dive into the node himself. + */ + function bindReachableStatement(node) { + if (checkUnreachable(node)) { + ts.forEachChild(node, bind); + return; + } + switch (node.kind) { + case 198 /* WhileStatement */: + bindWhileStatement(node); + break; + case 197 /* DoStatement */: + bindDoStatement(node); + break; + case 199 /* ForStatement */: + bindForStatement(node); + break; + case 200 /* ForInStatement */: + case 201 /* ForOfStatement */: + bindForInOrForOfStatement(node); + break; + case 196 /* IfStatement */: + bindIfStatement(node); + break; + case 204 /* ReturnStatement */: + case 208 /* ThrowStatement */: + bindReturnOrThrow(node); + break; + case 203 /* BreakStatement */: + case 202 /* ContinueStatement */: + bindBreakOrContinueStatement(node); + break; + case 209 /* TryStatement */: + bindTryStatement(node); + break; + case 206 /* SwitchStatement */: + bindSwitchStatement(node); + break; + case 220 /* CaseBlock */: + bindCaseBlock(node); + break; + case 207 /* LabeledStatement */: + bindLabeledStatement(node); + break; + default: + ts.forEachChild(node, bind); + break; + } + } + function bindWhileStatement(n) { + var preWhileState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + var postWhileState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + // bind expressions (don't affect reachability) + bind(n.expression); + currentReachabilityState = preWhileState; + var postWhileLabel = pushImplicitLabel(); + bind(n.statement); + popImplicitLabel(postWhileLabel, postWhileState); + } + function bindDoStatement(n) { + var preDoState = currentReachabilityState; + var postDoLabel = pushImplicitLabel(); + bind(n.statement); + var postDoState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : preDoState; + popImplicitLabel(postDoLabel, postDoState); + // bind expressions (don't affect reachability) + bind(n.expression); + } + function bindForStatement(n) { + var preForState = currentReachabilityState; + var postForLabel = pushImplicitLabel(); + // bind expressions (don't affect reachability) + bind(n.initializer); + bind(n.condition); + bind(n.incrementor); + bind(n.statement); + // for statement is considered infinite when it condition is either omitted or is true keyword + // - for(..;;..) + // - for(..;true;..) + var isInfiniteLoop = (!n.condition || n.condition.kind === 99 /* TrueKeyword */); + var postForState = isInfiniteLoop ? 4 /* Unreachable */ : preForState; + popImplicitLabel(postForLabel, postForState); + } + function bindForInOrForOfStatement(n) { + var preStatementState = currentReachabilityState; + var postStatementLabel = pushImplicitLabel(); + // bind expressions (don't affect reachability) + bind(n.initializer); + bind(n.expression); + bind(n.statement); + popImplicitLabel(postStatementLabel, preStatementState); + } + function bindIfStatement(n) { + // denotes reachability state when entering 'thenStatement' part of the if statement: + // i.e. if condition is false then thenStatement is unreachable + var ifTrueState = n.expression.kind === 84 /* FalseKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + // denotes reachability state when entering 'elseStatement': + // i.e. if condition is true then elseStatement is unreachable + var ifFalseState = n.expression.kind === 99 /* TrueKeyword */ ? 4 /* Unreachable */ : currentReachabilityState; + currentReachabilityState = ifTrueState; + // bind expression (don't affect reachability) + bind(n.expression); + bind(n.thenStatement); + if (n.elseStatement) { + var preElseState = currentReachabilityState; + currentReachabilityState = ifFalseState; + bind(n.elseStatement); + currentReachabilityState = or(currentReachabilityState, preElseState); + } + else { + currentReachabilityState = or(currentReachabilityState, ifFalseState); + } + } + function bindReturnOrThrow(n) { + // bind expression (don't affect reachability) + bind(n.expression); + if (n.kind === 204 /* ReturnStatement */) { + hasExplicitReturn = true; + } + currentReachabilityState = 4 /* Unreachable */; + } + function bindBreakOrContinueStatement(n) { + // call bind on label (don't affect reachability) + bind(n.label); + // for continue case touch label so it will be marked a used + var isValidJump = jumpToLabel(n.label, n.kind === 203 /* BreakStatement */ ? currentReachabilityState : 4 /* Unreachable */); + if (isValidJump) { + currentReachabilityState = 4 /* Unreachable */; + } + } + function bindTryStatement(n) { + // catch\finally blocks has the same reachability as try block + var preTryState = currentReachabilityState; + bind(n.tryBlock); + var postTryState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.catchClause); + var postCatchState = currentReachabilityState; + currentReachabilityState = preTryState; + bind(n.finallyBlock); + // post catch/finally state is reachable if + // - post try state is reachable - control flow can fall out of try block + // - post catch state is reachable - control flow can fall out of catch block + currentReachabilityState = or(postTryState, postCatchState); + } + function bindSwitchStatement(n) { + var preSwitchState = currentReachabilityState; + var postSwitchLabel = pushImplicitLabel(); + // bind expression (don't affect reachability) + bind(n.expression); + bind(n.caseBlock); + var hasDefault = ts.forEach(n.caseBlock.clauses, function (c) { return c.kind === 242 /* DefaultClause */; }); + // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case + var postSwitchState = hasDefault && currentReachabilityState !== 2 /* Reachable */ ? 4 /* Unreachable */ : preSwitchState; + popImplicitLabel(postSwitchLabel, postSwitchState); + } + function bindCaseBlock(n) { + var startState = currentReachabilityState; + for (var _i = 0, _a = n.clauses; _i < _a.length; _i++) { + var clause = _a[_i]; + currentReachabilityState = startState; + bind(clause); + if (clause.statements.length && currentReachabilityState === 2 /* Reachable */ && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } + } + } + function bindLabeledStatement(n) { + // call bind on label (don't affect reachability) + bind(n.label); + var ok = pushNamedLabel(n.label); + bind(n.statement); + if (ok) { + popNamedLabel(n.label, currentReachabilityState); + } + } function getContainerFlags(node) { switch (node.kind) { case 186 /* ClassExpression */: @@ -4576,7 +4848,7 @@ var ts; } } function declareClassMember(node, symbolFlags, symbolExcludes) { - return node.flags & 128 /* Static */ + return node.flags & 64 /* Static */ ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes) : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes); } @@ -4585,15 +4857,6 @@ var ts; ? declareModuleMember(node, symbolFlags, symbolExcludes) : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } - function isAmbientContext(node) { - while (node) { - if (node.flags & 2 /* Ambient */) { - return true; - } - node = node.parent; - } - return false; - } function hasExportDeclarations(node) { var body = node.kind === 248 /* SourceFile */ ? node : node.body; if (body.kind === 248 /* SourceFile */ || body.kind === 219 /* ModuleBlock */) { @@ -4609,11 +4872,11 @@ var ts; function setExportContextFlag(node) { // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular // declarations with export modifiers) is an export context in which declarations are implicitly exported. - if (isAmbientContext(node) && !hasExportDeclarations(node)) { - node.flags |= 262144 /* ExportContext */; + if (ts.isInAmbientContext(node) && !hasExportDeclarations(node)) { + node.flags |= 131072 /* ExportContext */; } else { - node.flags &= ~262144 /* ExportContext */; + node.flags &= ~131072 /* ExportContext */; } } function bindModuleDeclaration(node) { @@ -4805,7 +5068,7 @@ var ts; } } function checkStrictModeNumericLiteral(node) { - if (inStrictMode && node.flags & 65536 /* OctalLiteral */) { + if (inStrictMode && node.flags & 32768 /* OctalLiteral */) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode)); } } @@ -4829,10 +5092,10 @@ var ts; function checkStrictModeWithStatement(node) { // Grammar checking for withStatement if (inStrictMode) { - grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); + errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode); } } - function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { + function errorOnFirstToken(node, message, arg0, arg1, arg2) { var span = ts.getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } @@ -4840,6 +5103,9 @@ var ts; return "__" + ts.indexOf(node.parent.parameters, node); } function bind(node) { + if (!node) { + return; + } node.parent = parent; var savedInStrictMode = inStrictMode; if (!savedInStrictMode) { @@ -4882,8 +5148,8 @@ var ts; } } function updateStrictModeStatementList(statements) { - for (var _i = 0; _i < statements.length; _i++) { - var statement = statements[_i]; + for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) { + var statement = statements_1[_i]; if (!ts.isPrologueDirective(statement)) { return; } @@ -5105,7 +5371,7 @@ var ts; } // If this is a property-parameter, then also declare the property symbol into the // containing class. - if (node.flags & 112 /* AccessibilityModifier */ && + if (node.flags & 56 /* AccessibilityModifier */ && node.parent.kind === 144 /* Constructor */ && ts.isClassLike(node.parent.parent)) { var classDeclaration = node.parent.parent; @@ -5117,6 +5383,112 @@ var ts; ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } + // reachability checks + function pushNamedLabel(name) { + initializeReachabilityStateIfNecessary(); + if (ts.hasProperty(labelIndexMap, name.text)) { + return false; + } + labelIndexMap[name.text] = labelStack.push(1 /* Unintialized */) - 1; + return true; + } + function pushImplicitLabel() { + initializeReachabilityStateIfNecessary(); + var index = labelStack.push(1 /* Unintialized */) - 1; + implicitLabels.push(index); + return index; + } + function popNamedLabel(label, outerState) { + var index = labelIndexMap[label.text]; + ts.Debug.assert(index !== undefined); + ts.Debug.assert(labelStack.length == index + 1); + labelIndexMap[label.text] = undefined; + setCurrentStateAtLabel(labelStack.pop(), outerState, label); + } + function popImplicitLabel(implicitLabelIndex, outerState) { + if (labelStack.length !== implicitLabelIndex + 1) { + ts.Debug.assert(false, "Label stack: " + labelStack.length + ", index:" + implicitLabelIndex); + } + var i = implicitLabels.pop(); + if (implicitLabelIndex !== i) { + ts.Debug.assert(false, "i: " + i + ", index: " + implicitLabelIndex); + } + setCurrentStateAtLabel(labelStack.pop(), outerState, /*name*/ undefined); + } + function setCurrentStateAtLabel(innerMergedState, outerState, label) { + if (innerMergedState === 1 /* Unintialized */) { + if (label && !options.allowUnusedLabels) { + file.bindDiagnostics.push(ts.createDiagnosticForNode(label, ts.Diagnostics.Unused_label)); + } + currentReachabilityState = outerState; + } + else { + currentReachabilityState = or(innerMergedState, outerState); + } + } + function jumpToLabel(label, outerState) { + initializeReachabilityStateIfNecessary(); + var index = label ? labelIndexMap[label.text] : ts.lastOrUndefined(implicitLabels); + if (index === undefined) { + // reference to unknown label or + // break/continue used outside of loops + return false; + } + var stateAtLabel = labelStack[index]; + labelStack[index] = stateAtLabel === 1 /* Unintialized */ ? outerState : or(stateAtLabel, outerState); + return true; + } + function checkUnreachable(node) { + switch (currentReachabilityState) { + case 4 /* Unreachable */: + var reportError = + // report error on all statements + ts.isStatement(node) || + // report error on class declarations + node.kind === 214 /* ClassDeclaration */ || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === 218 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node)) || + // report error on regular enums and const enums if preserveConstEnums is set + (node.kind === 217 /* EnumDeclaration */ && (!ts.isConstEnumDeclaration(node) || options.preserveConstEnums)); + if (reportError) { + currentReachabilityState = 8 /* ReportedUnreachable */; + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + var reportUnreachableCode = !options.allowUnreachableCode && + !ts.isInAmbientContext(node) && + (node.kind !== 193 /* VariableStatement */ || + ts.getCombinedNodeFlags(node.declarationList) & 24576 /* BlockScoped */ || + ts.forEach(node.declarationList.declarations, function (d) { return d.initializer; })); + if (reportUnreachableCode) { + errorOnFirstToken(node, ts.Diagnostics.Unreachable_code_detected); + } + } + case 8 /* ReportedUnreachable */: + return true; + default: + return false; + } + function shouldReportErrorOnModuleDeclaration(node) { + var instanceState = getModuleInstanceState(node); + return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && options.preserveConstEnums); + } + } + function initializeReachabilityStateIfNecessary() { + if (labelIndexMap) { + return; + } + currentReachabilityState = 2 /* Reachable */; + labelIndexMap = {}; + labelStack = []; + implicitLabels = []; + } } })(ts || (ts = {})); /// @@ -5127,8 +5499,8 @@ var ts; function getDeclarationOfKind(symbol, kind) { var declarations = symbol.declarations; if (declarations) { - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) { + var declaration = declarations_1[_i]; if (declaration.kind === kind) { return declaration; } @@ -5328,7 +5700,7 @@ var ts; } ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName; function isBlockOrCatchScoped(declaration) { - return (getCombinedNodeFlags(declaration) & 49152 /* BlockScoped */) !== 0 || + return (getCombinedNodeFlags(declaration) & 24576 /* BlockScoped */) !== 0 || isCatchClauseVariableDeclaration(declaration); } ts.isBlockOrCatchScoped = isBlockOrCatchScoped; @@ -5441,7 +5813,7 @@ var ts; } ts.isExternalModule = isExternalModule; function isDeclarationFile(file) { - return (file.flags & 8192 /* DeclarationFile */) !== 0; + return (file.flags & 4096 /* DeclarationFile */) !== 0; } ts.isDeclarationFile = isDeclarationFile; function isConstEnumDeclaration(node) { @@ -5478,11 +5850,11 @@ var ts; } ts.getCombinedNodeFlags = getCombinedNodeFlags; function isConst(node) { - return !!(getCombinedNodeFlags(node) & 32768 /* Const */); + return !!(getCombinedNodeFlags(node) & 16384 /* Const */); } ts.isConst = isConst; function isLet(node) { - return !!(getCombinedNodeFlags(node) & 16384 /* Let */); + return !!(getCombinedNodeFlags(node) & 8192 /* Let */); } ts.isLet = isLet; function isPrologueDirective(node) { @@ -5683,27 +6055,28 @@ var ts; } ts.isClassLike = isClassLike; function isFunctionLike(node) { - if (node) { - switch (node.kind) { - case 144 /* Constructor */: - case 173 /* FunctionExpression */: - case 213 /* FunctionDeclaration */: - case 174 /* ArrowFunction */: - case 143 /* MethodDeclaration */: - case 142 /* MethodSignature */: - case 145 /* GetAccessor */: - case 146 /* SetAccessor */: - case 147 /* CallSignature */: - case 148 /* ConstructSignature */: - case 149 /* IndexSignature */: - case 152 /* FunctionType */: - case 153 /* ConstructorType */: - return true; - } - } - return false; + return node && isFunctionLikeKind(node.kind); } ts.isFunctionLike = isFunctionLike; + function isFunctionLikeKind(kind) { + switch (kind) { + case 144 /* Constructor */: + case 173 /* FunctionExpression */: + case 213 /* FunctionDeclaration */: + case 174 /* ArrowFunction */: + case 143 /* MethodDeclaration */: + case 142 /* MethodSignature */: + case 145 /* GetAccessor */: + case 146 /* SetAccessor */: + case 147 /* CallSignature */: + case 148 /* ConstructSignature */: + case 149 /* IndexSignature */: + case 152 /* FunctionType */: + case 153 /* ConstructorType */: + return true; + } + } + ts.isFunctionLikeKind = isFunctionLikeKind; function introducesArgumentsExoticObject(node) { switch (node.kind) { case 143 /* MethodDeclaration */: @@ -6206,9 +6579,18 @@ var ts; return !!node && (node.kind === 162 /* ArrayBindingPattern */ || node.kind === 161 /* ObjectBindingPattern */); } ts.isBindingPattern = isBindingPattern; + function isNodeDescendentOf(node, ancestor) { + while (node) { + if (node === ancestor) + return true; + node = node.parent; + } + return false; + } + ts.isNodeDescendentOf = isNodeDescendentOf; function isInAmbientContext(node) { while (node) { - if (node.flags & (2 /* Ambient */ | 8192 /* DeclarationFile */)) { + if (node.flags & (4 /* Ambient */ | 4096 /* DeclarationFile */)) { return true; } node = node.parent; @@ -6266,7 +6648,7 @@ var ts; case 207 /* LabeledStatement */: case 204 /* ReturnStatement */: case 206 /* SwitchStatement */: - case 98 /* ThrowKeyword */: + case 208 /* ThrowStatement */: case 209 /* TryStatement */: case 193 /* VariableStatement */: case 198 /* WhileStatement */: @@ -6379,8 +6761,8 @@ var ts; ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes; function getHeritageClause(clauses, kind) { if (clauses) { - for (var _i = 0; _i < clauses.length; _i++) { - var clause = clauses[_i]; + for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) { + var clause = clauses_1[_i]; if (clause.token === kind) { return clause; } @@ -6392,7 +6774,6 @@ var ts; function tryResolveScriptReference(host, sourceFile, reference) { if (!host.getCompilerOptions().noResolve) { var referenceFileName = ts.isRootedDiskPath(reference.fileName) ? reference.fileName : ts.combinePaths(ts.getDirectoryPath(sourceFile.fileName), reference.fileName); - referenceFileName = ts.getNormalizedAbsolutePath(referenceFileName, host.getCurrentDirectory()); return host.getSourceFile(referenceFileName); } } @@ -6450,7 +6831,7 @@ var ts; } ts.isTrivia = isTrivia; function isAsyncFunctionLike(node) { - return isFunctionLike(node) && (node.flags & 512 /* Async */) !== 0 && !isAccessor(node); + return isFunctionLike(node) && (node.flags & 256 /* Async */) !== 0 && !isAccessor(node); } ts.isAsyncFunctionLike = isAsyncFunctionLike; /** @@ -6837,7 +7218,7 @@ var ts; else { ts.forEach(declarations, function (member) { if ((member.kind === 145 /* GetAccessor */ || member.kind === 146 /* SetAccessor */) - && (member.flags & 128 /* Static */) === (accessor.flags & 128 /* Static */)) { + && (member.flags & 64 /* Static */) === (accessor.flags & 64 /* Static */)) { var memberName = getPropertyNameForPropertyNameNode(member.name); var accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { @@ -6894,6 +7275,66 @@ var ts; }); } ts.emitComments = emitComments; + /** + * Detached comment is a comment at the top of file or function body that is separated from + * the next statement by space. + */ + function emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, removeComments) { + var leadingComments; + var currentDetachedCommentInfo; + if (removeComments) { + // removeComments is true, only reserve pinned comment at the top of file + // For example: + // /*! Pinned Comment */ + // + // var x = 10; + if (node.pos === 0) { + leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment); + } + } + else { + // removeComments is false, just get detached as normal and bypass the process to filter comment + leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); + } + if (leadingComments) { + var detachedComments = []; + var lastComment; + for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) { + var comment = leadingComments_1[_i]; + if (lastComment) { + var lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); + var commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); + if (commentLine >= lastCommentLine + 2) { + // There was a blank line between the last comment and this comment. This + // comment is not part of the copyright comments. Return what we have so + // far. + break; + } + } + detachedComments.push(comment); + lastComment = comment; + } + if (detachedComments.length) { + // All comments look like they could have been part of the copyright header. Make + // sure there is at least one blank line between it and the node. If not, it's not + // a copyright header. + var lastCommentLine = getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); + var nodeLine = getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + // Valid detachedComments + emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; + } + } + } + return currentDetachedCommentInfo; + function isPinnedComment(comment) { + return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && + currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; + } + } + ts.emitDetachedComments = emitDetachedComments; function writeCommentRange(currentSourceFile, writer, comment, newLine) { if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { var firstCommentLineAndCharacter = ts.getLineAndCharacterOfPosition(currentSourceFile, comment.pos); @@ -6983,16 +7424,16 @@ var ts; ts.writeCommentRange = writeCommentRange; function modifierToFlag(token) { switch (token) { - case 113 /* StaticKeyword */: return 128 /* Static */; - case 112 /* PublicKeyword */: return 16 /* Public */; - case 111 /* ProtectedKeyword */: return 64 /* Protected */; - case 110 /* PrivateKeyword */: return 32 /* Private */; - case 115 /* AbstractKeyword */: return 256 /* Abstract */; - case 82 /* ExportKeyword */: return 1 /* Export */; - case 122 /* DeclareKeyword */: return 2 /* Ambient */; - case 74 /* ConstKeyword */: return 32768 /* Const */; - case 77 /* DefaultKeyword */: return 1024 /* Default */; - case 118 /* AsyncKeyword */: return 512 /* Async */; + case 113 /* StaticKeyword */: return 64 /* Static */; + case 112 /* PublicKeyword */: return 8 /* Public */; + case 111 /* ProtectedKeyword */: return 32 /* Protected */; + case 110 /* PrivateKeyword */: return 16 /* Private */; + case 115 /* AbstractKeyword */: return 128 /* Abstract */; + case 82 /* ExportKeyword */: return 2 /* Export */; + case 122 /* DeclareKeyword */: return 4 /* Ambient */; + case 74 /* ConstKeyword */: return 16384 /* Const */; + case 77 /* DefaultKeyword */: return 512 /* Default */; + case 118 /* AsyncKeyword */: return 256 /* Async */; } return 0; } @@ -7073,7 +7514,7 @@ var ts; } ts.isEmptyObjectLiteralOrArrayLiteral = isEmptyObjectLiteralOrArrayLiteral; function getLocalSymbolForExportDefault(symbol) { - return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 1024 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; + return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; function isJavaScript(fileName) { @@ -7150,6 +7591,12 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !ts.isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false); + } + ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -7414,8 +7861,8 @@ var ts; } function visitEachNode(cbNode, nodes) { if (nodes) { - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) { + var node = nodes_1[_i]; var result = cbNode(node); if (result) { return result; @@ -7982,8 +8429,8 @@ var ts; function addJSDocComment(node) { var comments = ts.getLeadingCommentRangesOfNode(node, sourceFile); if (comments) { - for (var _i = 0; _i < comments.length; _i++) { - var comment = comments[_i]; + for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) { + var comment = comments_1[_i]; var jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); if (jsDocComment) { node.jsDocComment = jsDocComment; @@ -8021,7 +8468,7 @@ var ts; sourceFile.bindDiagnostics = []; sourceFile.languageVersion = languageVersion; sourceFile.fileName = ts.normalizePath(fileName); - sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 8192 /* DeclarationFile */ : 0; + sourceFile.flags = ts.fileExtensionIs(sourceFile.fileName, ".d.ts") ? 4096 /* DeclarationFile */ : 0; sourceFile.languageVariant = ts.isTsx(sourceFile.fileName) ? 1 /* JSX */ : 0 /* Standard */; return sourceFile; } @@ -9079,7 +9526,7 @@ var ts; if (node.kind === 8 /* NumericLiteral */ && sourceText.charCodeAt(tokenPos) === 48 /* _0 */ && ts.isOctalDigit(sourceText.charCodeAt(tokenPos + 1))) { - node.flags |= 65536 /* OctalLiteral */; + node.flags |= 32768 /* OctalLiteral */; } return node; } @@ -9832,7 +10279,7 @@ var ts; // Didn't appear to actually be a parenthesized arrow function. Just bail out. return undefined; } - var isAsync = !!(arrowFunction.flags & 512 /* Async */); + var isAsync = !!(arrowFunction.flags & 256 /* Async */); // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. var lastToken = token; @@ -9959,7 +10406,7 @@ var ts; function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity) { var node = createNode(174 /* ArrowFunction */); setModifiers(node, parseModifiersForArrowFunction()); - var isAsync = !!(node.flags & 512 /* Async */); + var isAsync = !!(node.flags & 256 /* Async */); // Arrow functions are never generators. // // If we're speculatively parsing a signature for a parenthesized arrow function, then @@ -10802,7 +11249,7 @@ var ts; var node = createNode(164 /* ArrayLiteralExpression */); parseExpected(19 /* OpenBracketToken */); if (scanner.hasPrecedingLineBreak()) - node.flags |= 2048 /* MultiLine */; + node.flags |= 1024 /* MultiLine */; node.elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement); parseExpected(20 /* CloseBracketToken */); return finishNode(node); @@ -10863,7 +11310,7 @@ var ts; var node = createNode(165 /* ObjectLiteralExpression */); parseExpected(15 /* OpenBraceToken */); if (scanner.hasPrecedingLineBreak()) { - node.flags |= 2048 /* MultiLine */; + node.flags |= 1024 /* MultiLine */; } node.properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimeter*/ true); parseExpected(16 /* CloseBraceToken */); @@ -10884,7 +11331,7 @@ var ts; parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 512 /* Async */); + var isAsync = !!(node.flags & 256 /* Async */); node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -11476,10 +11923,10 @@ var ts; case 102 /* VarKeyword */: break; case 108 /* LetKeyword */: - node.flags |= 16384 /* Let */; + node.flags |= 8192 /* Let */; break; case 74 /* ConstKeyword */: - node.flags |= 32768 /* Const */; + node.flags |= 16384 /* Const */; break; default: ts.Debug.fail(); @@ -11522,9 +11969,9 @@ var ts; setModifiers(node, modifiers); parseExpected(87 /* FunctionKeyword */); node.asteriskToken = parseOptionalToken(37 /* AsteriskToken */); - node.name = node.flags & 1024 /* Default */ ? parseOptionalIdentifier() : parseIdentifier(); + node.name = node.flags & 512 /* Default */ ? parseOptionalIdentifier() : parseIdentifier(); var isGenerator = !!node.asteriskToken; - var isAsync = !!(node.flags & 512 /* Async */); + var isAsync = !!(node.flags & 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, ts.Diagnostics.or_expected); return finishNode(node); @@ -11546,7 +11993,7 @@ var ts; method.name = name; method.questionToken = questionToken; var isGenerator = !!asteriskToken; - var isAsync = !!(method.flags & 512 /* Async */); + var isAsync = !!(method.flags & 256 /* Async */); fillSignature(54 /* ColonToken */, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return finishNode(method); @@ -11567,7 +12014,7 @@ var ts; // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initialiser_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. - property.initializer = modifiers && modifiers.flags & 128 /* Static */ + property.initializer = modifiers && modifiers.flags & 64 /* Static */ ? allowInAnd(parseNonParameterInitializer) : doOutsideOfContext(2 /* Yield */ | 1 /* DisallowIn */, parseNonParameterInitializer); parseSemicolon(); @@ -11900,13 +12347,13 @@ var ts; var node = createNode(218 /* ModuleDeclaration */, fullStart); // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. - var namespaceFlag = flags & 131072 /* Namespace */; + var namespaceFlag = flags & 65536 /* Namespace */; node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; node.name = parseIdentifier(); node.body = parseOptional(21 /* DotToken */) - ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 1 /* Export */ | namespaceFlag) + ? parseModuleOrNamespaceDeclaration(getNodePos(), /*decorators*/ undefined, /*modifiers*/ undefined, 2 /* Export */ | namespaceFlag) : parseModuleBlock(); return finishNode(node); } @@ -11921,7 +12368,7 @@ var ts; function parseModuleDeclaration(fullStart, decorators, modifiers) { var flags = modifiers ? modifiers.flags : 0; if (parseOptional(126 /* NamespaceKeyword */)) { - flags |= 131072 /* Namespace */; + flags |= 65536 /* Namespace */; } else { parseExpected(125 /* ModuleKeyword */); @@ -12179,7 +12626,7 @@ var ts; } function setExternalModuleIndicator(sourceFile) { sourceFile.externalModuleIndicator = ts.forEach(sourceFile.statements, function (node) { - return node.flags & 1 /* Export */ + return node.flags & 2 /* Export */ || node.kind === 221 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 232 /* ExternalModuleReference */ || node.kind === 222 /* ImportDeclaration */ || node.kind === 227 /* ExportAssignment */ @@ -12868,8 +13315,8 @@ var ts; array._children = undefined; array.pos += delta; array.end += delta; - for (var _i = 0; _i < array.length; _i++) { - var node = array[_i]; + for (var _i = 0, array_7 = array; _i < array_7.length; _i++) { + var node = array_7[_i]; visitNode(node); } } @@ -13006,8 +13453,8 @@ var ts; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (var _i = 0; _i < array.length; _i++) { - var node = array[_i]; + for (var _i = 0, array_8 = array; _i < array_8.length; _i++) { + var node = array_8[_i]; visitNode(node); } return; @@ -13374,6 +13821,7 @@ var ts; var getInstantiatedGlobalPromiseLikeType; var getGlobalPromiseConstructorLikeType; var getGlobalThenableType; + var jsxElementClassType; var tupleTypes = {}; var unionTypes = {}; var intersectionTypes = {}; @@ -13643,7 +14091,7 @@ var ts; } var initializerOfNonStaticProperty = current.parent && current.parent.kind === 141 /* PropertyDeclaration */ && - (current.parent.flags & 128 /* Static */) === 0 && + (current.parent.flags & 64 /* Static */) === 0 && current.parent.initializer === current; if (initializerOfNonStaticProperty) { return true; @@ -13725,7 +14173,7 @@ var ts; // local variables of the constructor. This effectively means that entities from outer scopes // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. - if (ts.isClassLike(location.parent) && !(location.flags & 128 /* Static */)) { + if (ts.isClassLike(location.parent) && !(location.flags & 64 /* Static */)) { var ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & 107455 /* Value */)) { @@ -13739,7 +14187,7 @@ var ts; case 186 /* ClassExpression */: case 215 /* InterfaceDeclaration */: if (result = getSymbol(getSymbolOfNode(location).members, name, meaning & 793056 /* Type */)) { - if (lastLocation && lastLocation.flags & 128 /* Static */) { + if (lastLocation && lastLocation.flags & 64 /* Static */) { // TypeScript 1.0 spec (April 2014): 3.4.1 // The scope of a type parameter extends over the entire declaration with which the type // parameter list is associated, with the exception of static member declarations in classes. @@ -14267,8 +14715,8 @@ var ts; } function findConstructorDeclaration(node) { var members = node.members; - for (var _i = 0; _i < members.length; _i++) { - var member = members[_i]; + for (var _i = 0, members_1 = members; _i < members_1.length; _i++) { + var member = members_1[_i]; if (member.kind === 144 /* Constructor */ && ts.nodeIsPresent(member.body)) { return member; } @@ -14515,7 +14963,7 @@ var ts; // because these kind of aliases can be used to name types in declaration file var anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && - !(anyImportSyntax.flags & 1 /* Export */) && + !(anyImportSyntax.flags & 2 /* Export */) && isDeclarationVisible(anyImportSyntax.parent)) { getNodeLinks(declaration).isVisible = true; if (aliasesToMakeVisible) { @@ -14669,8 +15117,8 @@ var ts; walkSymbol(getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol), getQualifiedLeftMeaning(meaning)); } if (accessibleSymbolChain) { - for (var _i = 0; _i < accessibleSymbolChain.length; _i++) { - var accessibleSymbol = accessibleSymbolChain[_i]; + for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { + var accessibleSymbol = accessibleSymbolChain_1[_i]; appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } @@ -14860,7 +15308,7 @@ var ts; } function shouldWriteTypeOfFunctionSymbol() { var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */ && - ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 128 /* Static */; })); + ts.forEach(symbol.declarations, function (declaration) { return declaration.flags & 64 /* Static */; })); var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && (symbol.parent || ts.forEach(symbol.declarations, function (declaration) { @@ -14971,8 +15419,8 @@ var ts; var t = getTypeOfSymbol(p); if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { var signatures = getSignaturesOfType(t, 0 /* Call */); - for (var _f = 0; _f < signatures.length; _f++) { - var signature = signatures[_f]; + for (var _f = 0, signatures_1 = signatures; _f < signatures_1.length; _f++) { + var signature = signatures_1[_f]; buildSymbolDisplay(p, writer); if (p.flags & 536870912 /* Optional */) { writePunctuation(writer, 53 /* QuestionToken */); @@ -15186,7 +15634,7 @@ var ts; case 221 /* ImportEqualsDeclaration */: var parent_4 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) - if (!(ts.getCombinedNodeFlags(node) & 1 /* Export */) && + if (!(ts.getCombinedNodeFlags(node) & 2 /* Export */) && !(node.kind !== 221 /* ImportEqualsDeclaration */ && parent_4.kind !== 248 /* SourceFile */ && ts.isInAmbientContext(parent_4))) { return isGlobalSourceFile(parent_4); } @@ -15198,7 +15646,7 @@ var ts; case 146 /* SetAccessor */: case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - if (node.flags & (32 /* Private */ | 64 /* Protected */)) { + if (node.flags & (16 /* Private */ | 32 /* Protected */)) { // Private/protected properties/methods are not visible return false; } @@ -15728,8 +16176,8 @@ var ts; // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set // in-place and returns the same array. function appendTypeParameters(typeParameters, declarations) { - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) { + var declaration = declarations_2[_i]; var tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); if (!typeParameters) { typeParameters = [tp]; @@ -15934,13 +16382,13 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; if (declaration.kind === 215 /* InterfaceDeclaration */) { - if (declaration.flags & 524288 /* ContainsThis */) { + if (declaration.flags & 262144 /* ContainsThis */) { return false; } var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { - for (var _b = 0; _b < baseTypeNodes.length; _b++) { - var node = baseTypeNodes[_b]; + for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) { + var node = baseTypeNodes_1[_b]; if (ts.isSupportedExpressionWithTypeArguments(node)) { var baseSymbol = resolveEntityName(node.expression, 793056 /* Type */, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { @@ -16130,8 +16578,8 @@ var ts; } function createSymbolTable(symbols) { var result = {}; - for (var _i = 0; _i < symbols.length; _i++) { - var symbol = symbols[_i]; + for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) { + var symbol = symbols_1[_i]; result[symbol.name] = symbol; } return result; @@ -16140,15 +16588,15 @@ var ts; // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) { var result = {}; - for (var _i = 0; _i < symbols.length; _i++) { - var symbol = symbols[_i]; + for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) { + var symbol = symbols_2[_i]; result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); } return result; } function addInheritedMembers(symbols, baseSymbols) { - for (var _i = 0; _i < baseSymbols.length; _i++) { - var s = baseSymbols[_i]; + for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) { + var s = baseSymbols_1[_i]; if (!ts.hasProperty(symbols, s.name)) { symbols[s.name] = s; } @@ -16156,8 +16604,8 @@ var ts; } function addInheritedSignatures(signatures, baseSignatures) { if (baseSignatures) { - for (var _i = 0; _i < baseSignatures.length; _i++) { - var signature = baseSignatures[_i]; + for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) { + var signature = baseSignatures_1[_i]; signatures.push(signature); } } @@ -16200,8 +16648,8 @@ var ts; members = createSymbolTable(source.declaredProperties); } var thisArgument = ts.lastOrUndefined(typeArguments); - for (var _i = 0; _i < baseTypes.length; _i++) { - var baseType = baseTypes[_i]; + for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) { + var baseType = baseTypes_1[_i]; var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */)); @@ -16247,8 +16695,8 @@ var ts; var typeArguments = ts.map(baseTypeNode.typeArguments, getTypeFromTypeNode); var typeArgCount = typeArguments ? typeArguments.length : 0; var result = []; - for (var _i = 0; _i < baseSignatures.length; _i++) { - var baseSig = baseSignatures[_i]; + for (var _i = 0, baseSignatures_2 = baseSignatures; _i < baseSignatures_2.length; _i++) { + var baseSig = baseSignatures_2[_i]; var typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { var sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); @@ -16277,8 +16725,8 @@ var ts; setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); } function findMatchingSignature(signatureList, signature, partialMatch, ignoreReturnTypes) { - for (var _i = 0; _i < signatureList.length; _i++) { - var s = signatureList[_i]; + for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) { + var s = signatureList_1[_i]; if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { return s; } @@ -16342,8 +16790,8 @@ var ts; } function getUnionIndexType(types, kind) { var indexTypes = []; - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_1 = types; _i < types_1.length; _i++) { + var type = types_1[_i]; var indexType = getIndexTypeOfType(type, kind); if (!indexType) { return undefined; @@ -16522,12 +16970,12 @@ var ts; function createUnionOrIntersectionProperty(containingType, name) { var types = containingType.types; var props; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { + var current = types_2[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationFlagsFromSymbol(prop) & (32 /* Private */ | 64 /* Protected */))) { + if (prop && !(getDeclarationFlagsFromSymbol(prop) & (16 /* Private */ | 32 /* Protected */))) { if (!props) { props = [prop]; } @@ -16549,8 +16997,8 @@ var ts; } var propTypes = []; var declarations = []; - for (var _a = 0; _a < props.length; _a++) { - var prop = props[_a]; + for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { + var prop = props_1[_a]; if (prop.declarations) { ts.addRange(declarations, prop.declarations); } @@ -16908,8 +17356,8 @@ var ts; // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types) { var result = 0; - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { + var type = types_3[_i]; result |= type.flags; } return result & 14680064 /* PropagatingFlags */; @@ -17059,8 +17507,8 @@ var ts; function getTypeOfGlobalSymbol(symbol, arity) { function getTypeDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) { + var declaration = declarations_3[_i]; switch (declaration.kind) { case 214 /* ClassDeclaration */: case 215 /* InterfaceDeclaration */: @@ -17170,8 +17618,8 @@ var ts; // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToSet(typeSet, types, typeSetKind) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_4 = types; _i < types_4.length; _i++) { + var type = types_4[_i]; addTypeToSet(typeSet, type, typeSetKind); } } @@ -17193,8 +17641,8 @@ var ts; } } function containsTypeAny(types) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_5 = types; _i < types_5.length; _i++) { + var type = types_5[_i]; if (isTypeAny(type)) { return true; } @@ -17310,7 +17758,8 @@ var ts; var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); var parent = container && container.parent; if (parent && (ts.isClassLike(parent) || parent.kind === 215 /* InterfaceDeclaration */)) { - if (!(container.flags & 128 /* Static */)) { + if (!(container.flags & 64 /* Static */) && + (container.kind !== 144 /* Constructor */ || ts.isNodeDescendentOf(node, container.body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -17377,8 +17826,8 @@ var ts; function instantiateList(items, mapper, instantiator) { if (items && items.length) { var result = []; - for (var _i = 0; _i < items.length; _i++) { - var v = items[_i]; + for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { + var v = items_1[_i]; result.push(instantiator(v, mapper)); } return result; @@ -17417,8 +17866,8 @@ var ts; case 2: return createBinaryTypeEraser(sources[0], sources[1]); } return function (t) { - for (var _i = 0; _i < sources.length; _i++) { - var source = sources[_i]; + for (var _i = 0, sources_1 = sources; _i < sources_1.length; _i++) { + var source = sources_1[_i]; if (t === source) { return anyType; } @@ -17836,8 +18285,8 @@ var ts; function eachTypeRelatedToSomeType(source, target) { var result = -1 /* True */; var sourceTypes = source.types; - for (var _i = 0; _i < sourceTypes.length; _i++) { - var sourceType = sourceTypes[_i]; + for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) { + var sourceType = sourceTypes_1[_i]; var related = typeRelatedToSomeType(sourceType, target, false); if (!related) { return 0 /* False */; @@ -17859,8 +18308,8 @@ var ts; function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; var targetTypes = target.types; - for (var _i = 0; _i < targetTypes.length; _i++) { - var targetType = targetTypes[_i]; + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var targetType = targetTypes_1[_i]; var related = isRelatedTo(source, targetType, reportErrors); if (!related) { return 0 /* False */; @@ -17882,8 +18331,8 @@ var ts; function eachTypeRelatedToType(source, target, reportErrors) { var result = -1 /* True */; var sourceTypes = source.types; - for (var _i = 0; _i < sourceTypes.length; _i++) { - var sourceType = sourceTypes[_i]; + for (var _i = 0, sourceTypes_2 = sourceTypes; _i < sourceTypes_2.length; _i++) { + var sourceType = sourceTypes_2[_i]; var related = isRelatedTo(sourceType, target, reportErrors); if (!related) { return 0 /* False */; @@ -18008,8 +18457,8 @@ var ts; var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 524288 /* ObjectLiteral */); - for (var _i = 0; _i < properties.length; _i++) { - var targetProp = properties[_i]; + for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { + var targetProp = properties_1[_i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -18023,20 +18472,20 @@ var ts; else if (!(targetProp.flags & 134217728 /* Prototype */)) { var sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); - if (sourcePropFlags & 32 /* Private */ || targetPropFlags & 32 /* Private */) { + if (sourcePropFlags & 16 /* Private */ || targetPropFlags & 16 /* Private */) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { - if (sourcePropFlags & 32 /* Private */ && targetPropFlags & 32 /* Private */) { + if (sourcePropFlags & 16 /* Private */ && targetPropFlags & 16 /* Private */) { reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp)); } else { - reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 32 /* Private */ ? source : target), typeToString(sourcePropFlags & 32 /* Private */ ? target : source)); + reportError(ts.Diagnostics.Property_0_is_private_in_type_1_but_not_in_type_2, symbolToString(targetProp), typeToString(sourcePropFlags & 16 /* Private */ ? source : target), typeToString(sourcePropFlags & 16 /* Private */ ? target : source)); } } return 0 /* False */; } } - else if (targetPropFlags & 64 /* Protected */) { + else if (targetPropFlags & 32 /* Protected */) { var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32 /* Class */; var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; var targetClass = getDeclaredTypeOfSymbol(targetProp.parent); @@ -18047,7 +18496,7 @@ var ts; return 0 /* False */; } } - else if (sourcePropFlags & 64 /* Protected */) { + else if (sourcePropFlags & 32 /* Protected */) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -18089,8 +18538,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var _i = 0; _i < sourceProperties.length; _i++) { - var sourceProp = sourceProperties[_i]; + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProp = sourceProperties_1[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return 0 /* False */; @@ -18130,13 +18579,13 @@ var ts; return result; } } - outer: for (var _i = 0; _i < targetSignatures.length; _i++) { - var t = targetSignatures[_i]; + outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) { + var t = targetSignatures_1[_i]; if (!t.hasStringLiterals || target.flags & 262144 /* FromSignature */) { var localErrors = reportErrors; var checkedAbstractAssignability = false; - for (var _a = 0; _a < sourceSignatures.length; _a++) { - var s = sourceSignatures[_a]; + for (var _a = 0, sourceSignatures_1 = sourceSignatures; _a < sourceSignatures_1.length; _a++) { + var s = sourceSignatures_1[_a]; if (!s.hasStringLiterals || source.flags & 262144 /* FromSignature */) { var related = signatureRelatedTo(s, t, localErrors); if (related) { @@ -18167,8 +18616,8 @@ var ts; var targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); var sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); var targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 256 /* Abstract */; - var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 256 /* Abstract */; + var sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & 128 /* Abstract */; + var targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & 128 /* Abstract */; if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { // if target isn't a class-declaration type, then it can be new'd, so we forbid the assignment. if (reportErrors) { @@ -18284,7 +18733,7 @@ var ts; var targetType = getIndexTypeOfType(target, 0 /* String */); if (targetType) { if ((targetType.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */)) { - // non-primitive assignment to any is always allowed, eg + // non-primitive assignment to any is always allowed, eg // `var x: { [index: string]: any } = { property: 12 };` return -1 /* True */; } @@ -18313,7 +18762,7 @@ var ts; var targetType = getIndexTypeOfType(target, 1 /* Number */); if (targetType) { if ((targetType.flags & 1 /* Any */) && !(originalSource.flags & 16777726 /* Primitive */)) { - // non-primitive assignment to any is always allowed, eg + // non-primitive assignment to any is always allowed, eg // `var x: { [index: number]: any } = { property: 12 };` return -1 /* True */; } @@ -18386,8 +18835,8 @@ var ts; if (sourceProp === targetProp) { return -1 /* True */; } - var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (32 /* Private */ | 64 /* Protected */); - var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (32 /* Private */ | 64 /* Protected */); + var sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (16 /* Private */ | 32 /* Protected */); + var targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (16 /* Private */ | 32 /* Protected */); if (sourcePropAccessibility !== targetPropAccessibility) { return 0 /* False */; } @@ -18455,8 +18904,8 @@ var ts; return signature.hasRestParameter && parameterIndex >= signature.parameters.length - 1; } function isSupertypeOfEach(candidate, types) { - for (var _i = 0; _i < types.length; _i++) { - var type = types[_i]; + for (var _i = 0, types_6 = types; _i < types_6.length; _i++) { + var type = types_6[_i]; if (candidate !== type && !isTypeSubtypeOf(type, candidate)) return false; } @@ -18692,8 +19141,8 @@ var ts; } function createInferenceContext(typeParameters, inferUnionTypes) { var inferences = []; - for (var _i = 0; _i < typeParameters.length; _i++) { - var unused = typeParameters[_i]; + for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) { + var unused = typeParameters_1[_i]; inferences.push({ primary: undefined, secondary: undefined, isFixed: false }); @@ -18774,8 +19223,8 @@ var ts; var typeParameterCount = 0; var typeParameter; // First infer to each type in union or intersection that isn't a type parameter - for (var _i = 0; _i < targetTypes.length; _i++) { - var t = targetTypes[_i]; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var t = targetTypes_2[_i]; if (t.flags & 512 /* TypeParameter */ && ts.contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; @@ -18797,8 +19246,8 @@ var ts; else if (source.flags & 49152 /* UnionOrIntersection */) { // Source is a union or intersection type, infer from each consituent type var sourceTypes = source.types; - for (var _a = 0; _a < sourceTypes.length; _a++) { - var sourceType = sourceTypes[_a]; + for (var _a = 0, sourceTypes_3 = sourceTypes; _a < sourceTypes_3.length; _a++) { + var sourceType = sourceTypes_3[_a]; inferFromTypes(sourceType, target); } } @@ -18832,8 +19281,8 @@ var ts; } function inferFromProperties(source, target) { var properties = getPropertiesOfObjectType(target); - for (var _i = 0; _i < properties.length; _i++) { - var targetProp = properties[_i]; + for (var _i = 0, properties_2 = properties; _i < properties_2.length; _i++) { + var targetProp = properties_2[_i]; var sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); @@ -19324,9 +19773,9 @@ var ts; symbol.valueDeclaration.parent.kind === 244 /* CatchClause */) { return; } - // 1. walk from the use site up to the declaration and check + // 1. walk from the use site up to the declaration and check // if there is anything function like between declaration and use-site (is binding/class is captured in function). - // 2. walk from the declaration up to the boundary of lexical environment and check + // 2. walk from the declaration up to the boundary of lexical environment and check // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement) var container; if (symbol.flags & 32 /* Class */) { @@ -19398,7 +19847,7 @@ var ts; break; case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: - if (container.flags & 128 /* Static */) { + if (container.flags & 64 /* Static */) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; @@ -19411,7 +19860,7 @@ var ts; } if (ts.isClassLike(container.parent)) { var symbol = getSymbolOfNode(container.parent); - return container.flags & 128 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; + return container.flags & 64 /* Static */ ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType; } return anyType; } @@ -19441,7 +19890,7 @@ var ts; var nodeCheckFlag = 0; // always set NodeCheckFlags for 'super' expression node if (canUseSuperExpression) { - if ((container.flags & 128 /* Static */) || isCallExpression) { + if ((container.flags & 64 /* Static */) || isCallExpression) { nodeCheckFlag = 512 /* SuperStatic */; } else { @@ -19497,7 +19946,7 @@ var ts; // - In a static member function or static member accessor // topmost container must be something that is directly nested in the class declaration if (container && ts.isClassLike(container.parent)) { - if (container.flags & 128 /* Static */) { + if (container.flags & 64 /* Static */) { return container.kind === 143 /* MethodDeclaration */ || container.kind === 142 /* MethodSignature */ || container.kind === 145 /* GetAccessor */ || @@ -19654,8 +20103,8 @@ var ts; var types = type.types; var mappedType; var mappedTypes; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_7 = types; _i < types_7.length; _i++) { + var current = types_7[_i]; var t = mapper(current); if (t) { if (!mappedType) { @@ -19845,8 +20294,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_8 = types; _i < types_8.length; _i++) { + var current = types_8[_i]; var signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { @@ -19926,8 +20375,8 @@ var ts; var hasSpreadElement = false; var elementTypes = []; var inDestructuringPattern = isAssignmentTarget(node); - for (var _i = 0; _i < elements.length; _i++) { - var e = elements[_i]; + for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { + var e = elements_1[_i]; if (inDestructuringPattern && e.kind === 185 /* SpreadElementExpression */) { // Given the following situation: // var c: {}; @@ -20259,8 +20708,8 @@ var ts; function checkJsxSpreadAttribute(node, elementAttributesType, nameTable) { var type = checkExpression(node.expression); var props = getPropertiesOfType(type); - for (var _i = 0; _i < props.length; _i++) { - var prop = props[_i]; + for (var _i = 0, props_2 = props; _i < props_2.length; _i++) { + var prop = props_2[_i]; // Is there a corresponding property in the element attributes type? Skip checking of properties // that have already been assigned to, as these are not actually pushed into the resulting type if (!nameTable[prop.name]) { @@ -20479,7 +20928,6 @@ var ts; var prop = getPropertyOfType(attributesType, attrib.name.text); return prop || unknownSymbol; } - var jsxElementClassType = undefined; function getJsxGlobalElementClassType() { if (!jsxElementClassType) { jsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); @@ -20558,7 +21006,7 @@ var ts; return s.valueDeclaration ? s.valueDeclaration.kind : 141 /* PropertyDeclaration */; } function getDeclarationFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 16 /* Public */ | 128 /* Static */ : 0; + return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 8 /* Public */ | 64 /* Static */ : 0; } /** * Check whether the requested property access is valid. @@ -20588,7 +21036,7 @@ var ts; error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword); return false; } - if (flags & 256 /* Abstract */) { + if (flags & 128 /* Abstract */) { // A method cannot be accessed in a super property access if the method is abstract. // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an @@ -20598,7 +21046,7 @@ var ts; } } // Public properties are otherwise accessible. - if (!(flags & (32 /* Private */ | 64 /* Protected */))) { + if (!(flags & (16 /* Private */ | 32 /* Protected */))) { return true; } // Property is known to be private or protected at this point @@ -20606,7 +21054,7 @@ var ts; var enclosingClassDeclaration = ts.getContainingClass(node); var enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; // Private property is accessible if declaring and enclosing class are the same - if (flags & 32 /* Private */) { + if (flags & 16 /* Private */) { if (declaringClass !== enclosingClass) { error(node, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); return false; @@ -20624,7 +21072,7 @@ var ts; return false; } // No further restrictions for static properties - if (flags & 128 /* Static */) { + if (flags & 64 /* Static */) { return true; } // An instance property must be accessed through an instance of the enclosing class @@ -20851,8 +21299,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0; _i < signatures.length; _i++) { - var signature = signatures[_i]; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); var parent_5 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -21494,8 +21942,8 @@ var ts; // declare function f(a: { xa: number; xb: number; }); // f({ | if (!produceDiagnostics) { - for (var _i = 0; _i < candidates.length; _i++) { - var candidate = candidates[_i]; + for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) { + var candidate = candidates_1[_i]; if (hasCorrectArity(node, args, candidate)) { if (candidate.typeParameters && typeArguments) { candidate = getSignatureInstantiation(candidate, ts.map(typeArguments, getTypeFromTypeNode)); @@ -21514,8 +21962,8 @@ var ts; diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); } function chooseOverload(candidates, relation) { - for (var _i = 0; _i < candidates.length; _i++) { - var originalCandidate = candidates[_i]; + for (var _i = 0, candidates_2 = candidates; _i < candidates_2.length; _i++) { + var originalCandidate = candidates_2[_i]; if (!hasCorrectArity(node, args, originalCandidate)) { continue; } @@ -21652,7 +22100,7 @@ var ts; // In the case of a merged class-module or class-interface declaration, // only the class declaration node will have the Abstract flag set. var valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); - if (valueDecl && valueDecl.flags & 256 /* Abstract */) { + if (valueDecl && valueDecl.flags & 128 /* Abstract */) { error(node, ts.Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, ts.declarationNameToString(valueDecl.name)); return resolveErrorCall(node); } @@ -22017,19 +22465,11 @@ var ts; }); return aggregatedTypes; } - function bodyContainsAReturnStatement(funcBody) { - return ts.forEachReturnStatement(funcBody, function (returnStatement) { - return true; - }); - } - function bodyContainsSingleThrowStatement(body) { - return (body.statements.length === 1) && (body.statements[0].kind === 208 /* ThrowStatement */); - } // TypeScript Specification 1.0 (6.3) - July 2014 // An explicitly typed function whose return type isn't the Void or the Any type // must have at least one return statement somewhere in its body. // An exception to this rule is if the function implementation consists of a single 'throw' statement. - function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func, returnType) { + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) { if (!produceDiagnostics) { return; } @@ -22038,22 +22478,19 @@ var ts; return; } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 /* Block */) { + // also if HasImplicitReturnValue flags is not set this means that all codepaths in function body end with return of throw + if (ts.nodeIsMissing(func.body) || func.body.kind !== 192 /* Block */ || !(func.flags & 524288 /* HasImplicitReturn */)) { return; } - var bodyBlock = func.body; - // Ensure the body has at least one return expression. - if (bodyContainsAReturnStatement(bodyBlock)) { - return; + if (func.flags & 1048576 /* HasExplicitReturn */) { + if (compilerOptions.noImplicitReturns) { + error(func.type, ts.Diagnostics.Not_all_code_paths_return_a_value); + } } - // If there are no return expressions, then we need to check if - // the function body consists solely of a throw statement; - // this is to make an exception for unimplemented functions. - if (bodyContainsSingleThrowStatement(bodyBlock)) { - return; + else { + // This function does not conform to the specification. + error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } - // This function does not conform to the specification. - error(func.type, ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement); } function checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper) { ts.Debug.assert(node.kind !== 143 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node)); @@ -22120,7 +22557,7 @@ var ts; promisedType = checkAsyncFunctionReturnType(node); } if (returnType && !node.asteriskToken) { - checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); } if (node.body) { if (!node.type) { @@ -22205,7 +22642,7 @@ var ts; case 69 /* Identifier */: case 166 /* PropertyAccessExpression */: { var symbol = findSymbol(n); - return symbol && (symbol.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 32768 /* Const */) !== 0; + return symbol && (symbol.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & 16384 /* Const */) !== 0; } case 167 /* ElementAccessExpression */: { var index = n.argumentExpression; @@ -22213,7 +22650,7 @@ var ts; if (symbol && index && index.kind === 9 /* StringLiteral */) { var name_12 = index.text; var prop = getPropertyOfType(getTypeOfSymbol(symbol), name_12); - return prop && (prop.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 32768 /* Const */) !== 0; + return prop && (prop.flags & 3 /* Variable */) !== 0 && (getDeclarationFlagsFromSymbol(prop) & 16384 /* Const */) !== 0; } return false; } @@ -22298,8 +22735,8 @@ var ts; } if (type.flags & 49152 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_9 = types; _i < types_9.length; _i++) { + var current = types_9[_i]; if (current.flags & kind) { return true; } @@ -22315,8 +22752,8 @@ var ts; } if (type.flags & 49152 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0; _i < types.length; _i++) { - var current = types[_i]; + for (var _i = 0, types_10 = types; _i < types_10.length; _i++) { + var current = types_10[_i]; if (!(current.flags & kind)) { return false; } @@ -22361,8 +22798,8 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType, contextualMapper) { var properties = node.properties; - for (var _i = 0; _i < properties.length; _i++) { - var p = properties[_i]; + for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) { + var p = properties_3[_i]; if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { // TODO(andersh): Computed property support var name_13 = p.name; @@ -22896,7 +23333,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & 112 /* AccessibilityModifier */) { + if (node.flags & 56 /* AccessibilityModifier */) { func = ts.getContainingFunction(node); if (!(func.kind === 144 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); @@ -23096,7 +23533,7 @@ var ts; checkFunctionLikeDeclaration(node); // Abstract methods cannot have an implementation. // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node. - if (node.flags & 256 /* Abstract */ && node.body) { + if (node.flags & 128 /* Abstract */ && node.body) { error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name)); } } @@ -23147,7 +23584,7 @@ var ts; } function isInstancePropertyWithInitializer(n) { return n.kind === 141 /* PropertyDeclaration */ && - !(n.flags & 128 /* Static */) && + !(n.flags & 64 /* Static */) && !!n.initializer; } // TS 1.0 spec (April 2014): 8.3.2 @@ -23168,14 +23605,14 @@ var ts; // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. var superCallShouldBeFirst = ts.forEach(node.parent.members, isInstancePropertyWithInitializer) || - ts.forEach(node.parameters, function (p) { return p.flags & (16 /* Public */ | 32 /* Private */ | 64 /* Protected */); }); + ts.forEach(node.parameters, function (p) { return p.flags & (8 /* Public */ | 16 /* Private */ | 32 /* Protected */); }); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { var statements = node.body.statements; var superCallStatement; - for (var _i = 0; _i < statements.length; _i++) { - var statement = statements[_i]; + for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { + var statement = statements_2[_i]; if (statement.kind === 195 /* ExpressionStatement */ && isSuperCallExpression(statement.expression)) { superCallStatement = statement; break; @@ -23203,8 +23640,15 @@ var ts; // Grammar checking accessors checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); if (node.kind === 145 /* GetAccessor */) { - if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { - error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); + if (!ts.isInAmbientContext(node) && ts.nodeIsPresent(node.body) && (node.flags & 524288 /* HasImplicitReturn */)) { + if (node.flags & 1048576 /* HasExplicitReturn */) { + if (compilerOptions.noImplicitReturns) { + error(node.name, ts.Diagnostics.Not_all_code_paths_return_a_value); + } + } + else { + error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value); + } } } if (!ts.hasDynamicName(node)) { @@ -23213,7 +23657,7 @@ var ts; var otherKind = node.kind === 145 /* GetAccessor */ ? 146 /* SetAccessor */ : 145 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { - if (((node.flags & 112 /* AccessibilityModifier */) !== (otherAccessor.flags & 112 /* AccessibilityModifier */))) { + if (((node.flags & 56 /* AccessibilityModifier */) !== (otherAccessor.flags & 56 /* AccessibilityModifier */))) { error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } var currentAccessorType = getAnnotatedAccessorType(node); @@ -23284,7 +23728,7 @@ var ts; ts.forEach(node.types, checkSourceElement); } function isPrivateWithinAmbient(node) { - return (node.flags & 32 /* Private */) && ts.isInAmbientContext(node); + return (node.flags & 16 /* Private */) && ts.isInAmbientContext(node); } function checkSpecializedSignatureDeclaration(signatureDeclarationNode) { if (!produceDiagnostics) { @@ -23316,8 +23760,8 @@ var ts; else { signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); } - for (var _i = 0; _i < signaturesToCheck.length; _i++) { - var otherSignature = signaturesToCheck[_i]; + for (var _i = 0, signaturesToCheck_1 = signaturesToCheck; _i < signaturesToCheck_1.length; _i++) { + var otherSignature = signaturesToCheck_1[_i]; if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { return; } @@ -23332,11 +23776,11 @@ var ts; n.parent.kind !== 214 /* ClassDeclaration */ && n.parent.kind !== 186 /* ClassExpression */ && ts.isInAmbientContext(n)) { - if (!(flags & 2 /* Ambient */)) { + if (!(flags & 4 /* Ambient */)) { // It is nested in an ambient context, which means it is automatically exported - flags |= 1 /* Export */; + flags |= 2 /* Export */; } - flags |= 2 /* Ambient */; + flags |= 4 /* Ambient */; } return flags & flagsToCheck; } @@ -23361,16 +23805,16 @@ var ts; var canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); ts.forEach(overloads, function (o) { var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; - if (deviation & 1 /* Export */) { + if (deviation & 2 /* Export */) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); } - else if (deviation & 2 /* Ambient */) { + else if (deviation & 4 /* Ambient */) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient); } - else if (deviation & (32 /* Private */ | 64 /* Protected */)) { + else if (deviation & (16 /* Private */ | 32 /* Protected */)) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected); } - else if (deviation & 256 /* Abstract */) { + else if (deviation & 128 /* Abstract */) { error(o.name, ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_not_abstract); } }); @@ -23387,7 +23831,7 @@ var ts; }); } } - var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 32 /* Private */ | 64 /* Protected */ | 256 /* Abstract */; + var flagsToCheck = 2 /* Export */ | 4 /* Ambient */ | 16 /* Private */ | 32 /* Protected */ | 128 /* Abstract */; var someNodeFlags = 0; var allNodeFlags = flagsToCheck; var someHaveQuestionToken = false; @@ -23418,8 +23862,8 @@ var ts; if (node.name && subsequentNode.name && node.name.text === subsequentNode.name.text) { // the only situation when this is possible (same kind\same name but different symbol) - mixed static and instance class members ts.Debug.assert(node.kind === 143 /* MethodDeclaration */ || node.kind === 142 /* MethodSignature */); - ts.Debug.assert((node.flags & 128 /* Static */) !== (subsequentNode.flags & 128 /* Static */)); - var diagnostic = node.flags & 128 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; + ts.Debug.assert((node.flags & 64 /* Static */) !== (subsequentNode.flags & 64 /* Static */)); + var diagnostic = node.flags & 64 /* Static */ ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static; error(errorNode_1, diagnostic); return; } @@ -23436,7 +23880,7 @@ var ts; else { // Report different errors regarding non-consecutive blocks of declarations depending on whether // the node in question is abstract. - if (node.flags & 256 /* Abstract */) { + if (node.flags & 128 /* Abstract */) { error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive); } else { @@ -23449,8 +23893,8 @@ var ts; var isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & 1536 /* Module */; var duplicateFunctionDeclaration = false; var multipleConstructorImplementation = false; - for (var _i = 0; _i < declarations.length; _i++) { - var current = declarations[_i]; + for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { + var current = declarations_4[_i]; var node = current; var inAmbientContext = ts.isInAmbientContext(node); var inAmbientContextOrInterface = node.parent.kind === 215 /* InterfaceDeclaration */ || node.parent.kind === 155 /* TypeLiteral */ || inAmbientContext; @@ -23507,7 +23951,7 @@ var ts; } // Abstract methods can't have an implementation -- in particular, they don't need one. if (!isExportSymbolInsideModule && lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && - !(lastSeenNonAmbientDeclaration.flags & 256 /* Abstract */)) { + !(lastSeenNonAmbientDeclaration.flags & 128 /* Abstract */)) { reportImplementationExpectedError(lastSeenNonAmbientDeclaration); } if (hasOverloads) { @@ -23533,8 +23977,8 @@ var ts; // function g(x: string, y: string) { } // // The implementation is completely unrelated to the specialized signature, yet we do not check this. - for (var _a = 0; _a < signatures.length; _a++) { - var signature = signatures[_a]; + for (var _a = 0, signatures_3 = signatures; _a < signatures_3.length; _a++) { + var signature = signatures_3[_a]; if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -23571,9 +24015,9 @@ var ts; for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var d = _a[_i]; var declarationSpaces = getDeclarationSpaces(d); - var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 1024 /* Default */); - if (effectiveDeclarationFlags & 1 /* Export */) { - if (effectiveDeclarationFlags & 1024 /* Default */) { + var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 2 /* Export */ | 512 /* Default */); + if (effectiveDeclarationFlags & 2 /* Export */) { + if (effectiveDeclarationFlags & 512 /* Default */) { defaultExportedDeclarationSpaces |= declarationSpaces; } else { @@ -23826,9 +24270,12 @@ var ts; // type as a value. As such, we will just return unknownType; return unknownType; } - var promiseConstructor = getMergedSymbol(promiseType.symbol); + var promiseConstructor = getNodeLinks(node.type).resolvedSymbol; if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { - error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeToString(promiseType)); + var typeName = promiseConstructor + ? symbolToString(promiseConstructor) + : typeToString(promiseType); + error(node, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); return unknownType; } // Validate the promise constructor type. @@ -24020,7 +24467,7 @@ var ts; if (isAsync) { promisedType = checkAsyncFunctionReturnType(node); } - checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); } if (produceDiagnostics && !node.type) { // Report an implicit any error if there is no body, no explicit return type, and node is not a private method @@ -24162,7 +24609,7 @@ var ts; // let x = 0; // symbol for this declaration will be 'symbol' // } // skip block-scoped variables and parameters - if ((ts.getCombinedNodeFlags(node) & 49152 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { + if ((ts.getCombinedNodeFlags(node) & 24576 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) { return; } // skip variable declarations that don't have initializers @@ -24177,7 +24624,7 @@ var ts; if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) { - if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 49152 /* BlockScoped */) { + if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & 24576 /* BlockScoped */) { var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 212 /* VariableDeclarationList */); var container = varDeclList.parent.kind === 193 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent @@ -24330,6 +24777,9 @@ var ts; checkGrammarStatementInAmbientContext(node); checkExpression(node.expression); checkSourceElement(node.thenStatement); + if (node.thenStatement.kind === 194 /* EmptyStatement */) { + error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement); + } checkSourceElement(node.elseStatement); } function checkDoStatement(node) { @@ -24688,7 +25138,7 @@ var ts; error(node.expression, ts.Diagnostics.Setters_cannot_return_a_value); } else if (func.kind === 144 /* Constructor */) { - if (!isTypeAssignableTo(exprType, returnType)) { + if (!checkTypeAssignableTo(exprType, returnType, node.expression)) { error(node.expression, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class); } } @@ -24835,7 +25285,7 @@ var ts; // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. - if (!(member.flags & 128 /* Static */) && ts.hasDynamicName(member)) { + if (!(member.flags & 64 /* Static */) && ts.hasDynamicName(member)) { var propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); @@ -24921,7 +25371,7 @@ var ts; return getTypeOfSymbol(getSymbolOfNode(node)); } function checkClassDeclaration(node) { - if (!node.name && !(node.flags & 1024 /* Default */)) { + if (!node.name && !(node.flags & 512 /* Default */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name); } checkClassLikeDeclaration(node); @@ -24975,8 +25425,8 @@ var ts; } var implementedTypeNodes = ts.getClassImplementsHeritageClauseElements(node); if (implementedTypeNodes) { - for (var _b = 0; _b < implementedTypeNodes.length; _b++) { - var typeRefNode = implementedTypeNodes[_b]; + for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) { + var typeRefNode = implementedTypeNodes_1[_b]; if (!ts.isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } @@ -25024,8 +25474,8 @@ var ts; // derived class instance member variables and accessors, but not by other kinds of members. // NOTE: assignability is checked in checkClassDeclaration var baseProperties = getPropertiesOfObjectType(baseType); - for (var _i = 0; _i < baseProperties.length; _i++) { - var baseProperty = baseProperties[_i]; + for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) { + var baseProperty = baseProperties_1[_i]; var base = getTargetSymbol(baseProperty); if (base.flags & 134217728 /* Prototype */) { continue; @@ -25043,7 +25493,7 @@ var ts; // It is an error to inherit an abstract member without implementing it or being declared abstract. // If there is no declaration for the derived class (as in the case of class expressions), // then the class cannot be declared abstract. - if (baseDeclarationFlags & 256 /* Abstract */ && (!derivedClassDecl || !(derivedClassDecl.flags & 256 /* Abstract */))) { + if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !(derivedClassDecl.flags & 128 /* Abstract */))) { if (derivedClassDecl.kind === 186 /* ClassExpression */) { error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType)); } @@ -25055,11 +25505,11 @@ var ts; else { // derived overrides base. var derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); - if ((baseDeclarationFlags & 32 /* Private */) || (derivedDeclarationFlags & 32 /* Private */)) { + if ((baseDeclarationFlags & 16 /* Private */) || (derivedDeclarationFlags & 16 /* Private */)) { // either base or derived property is private - not override, skip it continue; } - if ((baseDeclarationFlags & 128 /* Static */) !== (derivedDeclarationFlags & 128 /* Static */)) { + if ((baseDeclarationFlags & 64 /* Static */) !== (derivedDeclarationFlags & 64 /* Static */)) { // value of 'static' is not the same for properties - not override, skip it continue; } @@ -25130,11 +25580,11 @@ var ts; var seen = {}; ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen[p.name] = { prop: p, containingType: type }; }); var ok = true; - for (var _i = 0; _i < baseTypes.length; _i++) { - var base = baseTypes[_i]; + for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) { + var base = baseTypes_2[_i]; var properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (var _a = 0; _a < properties.length; _a++) { - var prop = properties[_a]; + for (var _a = 0, properties_4 = properties; _a < properties_4.length; _a++) { + var prop = properties_4[_a]; if (!ts.hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } @@ -25431,8 +25881,8 @@ var ts; } function getFirstNonAmbientClassOrFunctionDeclaration(symbol) { var declarations = symbol.declarations; - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) { + var declaration = declarations_5[_i]; if ((declaration.kind === 214 /* ClassDeclaration */ || (declaration.kind === 213 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) && !ts.isInAmbientContext(declaration)) { @@ -25571,7 +26021,7 @@ var ts; // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { @@ -25599,7 +26049,7 @@ var ts; checkGrammarDecorators(node) || checkGrammarModifiers(node); if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) { checkImportBinding(node); - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { markExportAsReferenced(node); } if (ts.isInternalModuleImportEqualsDeclaration(node)) { @@ -25630,7 +26080,7 @@ var ts; // If we hit an export in an illegal context, just bail out to avoid cascading errors. return; } - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers); } if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) { @@ -25674,7 +26124,7 @@ var ts; return; } // Grammar checking - if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 2035 /* Modifier */)) { + if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && (node.flags & 1022 /* Modifier */)) { grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers); } if (node.expression.kind === 69 /* Identifier */) { @@ -26087,7 +26537,7 @@ var ts; // add the type parameters into the symbol table // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol. // Note: that the memberFlags come from previous iteration. - if (!(memberFlags & 128 /* Static */)) { + if (!(memberFlags & 64 /* Static */)) { copySymbols(getSymbolOfNode(location).members, meaning & 793056 /* Type */); } break; @@ -26388,7 +26838,7 @@ var ts; */ function getParentTypeOfClassElement(node) { var classSymbol = getSymbolOfNode(node.parent); - return node.flags & 128 /* Static */ + return node.flags & 64 /* Static */ ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); } @@ -26709,7 +27159,7 @@ var ts; function initializeTypeChecker() { // Bind all source files and propagate errors ts.forEach(host.getSourceFiles(), function (file) { - ts.bindSourceFile(file); + ts.bindSourceFile(file, compilerOptions); }); // Initialize global symbol table ts.forEach(host.getSourceFiles(), function (file) { @@ -26863,19 +27313,19 @@ var ts; text = "private"; lastPrivate = modifier; } - if (flags & 112 /* AccessibilityModifier */) { + if (flags & 56 /* AccessibilityModifier */) { return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen); } - else if (flags & 128 /* Static */) { + else if (flags & 64 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async"); } else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_element, text); } - else if (flags & 256 /* Abstract */) { + else if (flags & 128 /* Abstract */) { if (modifier.kind === 110 /* PrivateKeyword */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract"); } @@ -26886,10 +27336,10 @@ var ts; flags |= ts.modifierToFlag(modifier.kind); break; case 113 /* StaticKeyword */: - if (flags & 128 /* Static */) { + if (flags & 64 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async"); } else if (node.parent.kind === 219 /* ModuleBlock */ || node.parent.kind === 248 /* SourceFile */) { @@ -26898,23 +27348,23 @@ var ts; else if (node.kind === 138 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static"); } - else if (flags & 256 /* Abstract */) { + else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - flags |= 128 /* Static */; + flags |= 64 /* Static */; lastStatic = modifier; break; case 82 /* ExportKeyword */: - if (flags & 1 /* Export */) { + if (flags & 2 /* Export */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export"); } - else if (flags & 2 /* Ambient */) { + else if (flags & 4 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare"); } - else if (flags & 256 /* Abstract */) { + else if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async"); } else if (node.parent.kind === 214 /* ClassDeclaration */) { @@ -26923,13 +27373,13 @@ var ts; else if (node.kind === 138 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export"); } - flags |= 1 /* Export */; + flags |= 2 /* Export */; break; case 122 /* DeclareKeyword */: - if (flags & 2 /* Ambient */) { + if (flags & 4 /* Ambient */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } else if (node.parent.kind === 214 /* ClassDeclaration */) { @@ -26941,69 +27391,69 @@ var ts; else if (ts.isInAmbientContext(node.parent) && node.parent.kind === 219 /* ModuleBlock */) { return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context); } - flags |= 2 /* Ambient */; + flags |= 4 /* Ambient */; lastDeclare = modifier; break; case 115 /* AbstractKeyword */: - if (flags & 256 /* Abstract */) { + if (flags & 128 /* Abstract */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract"); } if (node.kind !== 214 /* ClassDeclaration */) { if (node.kind !== 143 /* MethodDeclaration */) { return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_or_method_declaration); } - if (!(node.parent.kind === 214 /* ClassDeclaration */ && node.parent.flags & 256 /* Abstract */)) { + if (!(node.parent.kind === 214 /* ClassDeclaration */ && node.parent.flags & 128 /* Abstract */)) { return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class); } - if (flags & 128 /* Static */) { + if (flags & 64 /* Static */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract"); } - if (flags & 32 /* Private */) { + if (flags & 16 /* Private */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract"); } } - flags |= 256 /* Abstract */; + flags |= 128 /* Abstract */; break; case 118 /* AsyncKeyword */: - if (flags & 512 /* Async */) { + if (flags & 256 /* Async */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async"); } - else if (flags & 2 /* Ambient */ || ts.isInAmbientContext(node.parent)) { + else if (flags & 4 /* Ambient */ || ts.isInAmbientContext(node.parent)) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async"); } else if (node.kind === 138 /* Parameter */) { return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async"); } - flags |= 512 /* Async */; + flags |= 256 /* Async */; lastAsync = modifier; break; } } if (node.kind === 144 /* Constructor */) { - if (flags & 128 /* Static */) { + if (flags & 64 /* Static */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static"); } - if (flags & 256 /* Abstract */) { + if (flags & 128 /* Abstract */) { return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); } - else if (flags & 64 /* Protected */) { + else if (flags & 32 /* Protected */) { return grammarErrorOnNode(lastProtected, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "protected"); } - else if (flags & 32 /* Private */) { + else if (flags & 16 /* Private */) { return grammarErrorOnNode(lastPrivate, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "private"); } - else if (flags & 512 /* Async */) { + else if (flags & 256 /* Async */) { return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async"); } return; } - else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) { + else if ((node.kind === 222 /* ImportDeclaration */ || node.kind === 221 /* ImportEqualsDeclaration */) && flags & 4 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare"); } - else if (node.kind === 138 /* Parameter */ && (flags & 112 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { + else if (node.kind === 138 /* Parameter */ && (flags & 56 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); } - if (flags & 512 /* Async */) { + if (flags & 256 /* Async */) { return checkGrammarAsyncModifier(node, lastAsync); } } @@ -27104,7 +27554,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter); } - if (parameter.flags & 2035 /* Modifier */) { + if (parameter.flags & 1022 /* Modifier */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier); } if (parameter.questionToken) { @@ -27124,7 +27574,7 @@ var ts; } } function checkGrammarForIndexSignatureModifier(node) { - if (node.flags & 2035 /* Modifier */) { + if (node.flags & 1022 /* Modifier */) { grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_not_permitted_on_index_signature_members); } } @@ -27147,8 +27597,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0; _i < args.length; _i++) { - var arg = args[_i]; + for (var _i = 0, args_1 = args; _i < args_1.length; _i++) { + var arg = args_1[_i]; if (arg.kind === 187 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -27403,7 +27853,7 @@ var ts; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter); } - else if (parameter.flags & 2035 /* Modifier */) { + else if (parameter.flags & 1022 /* Modifier */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } else if (parameter.questionToken) { @@ -27554,8 +28004,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0; _i < elements.length; _i++) { - var element = elements[_i]; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; if (element.kind !== 187 /* OmittedExpression */) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -27691,8 +28141,8 @@ var ts; node.kind === 221 /* ImportEqualsDeclaration */ || node.kind === 228 /* ExportDeclaration */ || node.kind === 227 /* ExportAssignment */ || - (node.flags & 2 /* Ambient */) || - (node.flags & (1 /* Export */ | 1024 /* Default */))) { + (node.flags & 4 /* Ambient */) || + (node.flags & (2 /* Export */ | 512 /* Default */))) { return false; } return grammarErrorOnFirstToken(node, ts.Diagnostics.A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file); @@ -27739,7 +28189,7 @@ var ts; } function checkGrammarNumericLiteral(node) { // Grammar checking - if (node.flags & 65536 /* OctalLiteral */ && languageVersion >= 1 /* ES5 */) { + if (node.flags & 32768 /* OctalLiteral */ && languageVersion >= 1 /* ES5 */) { return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } @@ -27793,7 +28243,7 @@ var ts; ts.forEach(root.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, root, fileReference); // All the references that are not going to be part of same file - if (referencedFile && ((referencedFile.flags & 8192 /* DeclarationFile */) || + if (referencedFile && ((referencedFile.flags & 4096 /* DeclarationFile */) || ts.shouldEmitToOwnFile(referencedFile, compilerOptions) || !addedGlobalFileReference)) { writeReferencePath(referencedFile); @@ -27988,15 +28438,15 @@ var ts; } } function emitLines(nodes) { - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) { + var node = nodes_2[_i]; emit(node); } } function emitSeparatedList(nodes, separator, eachNodeEmitFn, canEmitFn) { var currentWriterPos = writer.getTextPos(); - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_3 = nodes; _i < nodes_3.length; _i++) { + var node = nodes_3[_i]; if (!canEmitFn || canEmitFn(node)) { if (currentWriterPos !== writer.getTextPos()) { write(separator); @@ -28142,6 +28592,7 @@ var ts; function emitSourceFile(node) { currentSourceFile = node; enclosingDeclaration = node; + ts.emitDetachedComments(currentSourceFile, writer, ts.writeCommentRange, node, newLine, true /* remove comments */); emitLines(node.statements); } // Return a temp variable name to be used in `export default` statements. @@ -28258,10 +28709,10 @@ var ts; // If the node is parented in the current source file we need to emit export declare or just export if (node.parent === currentSourceFile) { // If the node is exported - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { write("export "); } - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { write("default "); } else if (node.kind !== 215 /* InterfaceDeclaration */) { @@ -28270,16 +28721,16 @@ var ts; } } function emitClassMemberDeclarationFlags(node) { - if (node.flags & 32 /* Private */) { + if (node.flags & 16 /* Private */) { write("private "); } - else if (node.flags & 64 /* Protected */) { + else if (node.flags & 32 /* Protected */) { write("protected "); } - if (node.flags & 128 /* Static */) { + if (node.flags & 64 /* Static */) { write("static "); } - if (node.flags & 256 /* Abstract */) { + if (node.flags & 128 /* Abstract */) { write("abstract "); } } @@ -28287,7 +28738,7 @@ var ts; // note usage of writer. methods instead of aliases created, just to make sure we are using // correct writer especially to handle asynchronous alias writing emitJsDocComments(node); - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { write("export "); } write("import "); @@ -28322,12 +28773,12 @@ var ts; } } function writeImportDeclaration(node) { - if (!node.importClause && !(node.flags & 1 /* Export */)) { + if (!node.importClause && !(node.flags & 2 /* Export */)) { // do not write non-exported import declarations that don't have import clauses return; } emitJsDocComments(node); - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { write("export "); } write("import "); @@ -28392,7 +28843,7 @@ var ts; function writeModuleDeclaration(node) { emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 131072 /* Namespace */) { + if (node.flags & 65536 /* Namespace */) { write("namespace "); } else { @@ -28464,7 +28915,7 @@ var ts; writeLine(); } function isPrivateMethodTypeParameter(node) { - return node.parent.kind === 143 /* MethodDeclaration */ && (node.parent.flags & 32 /* Private */); + return node.parent.kind === 143 /* MethodDeclaration */ && (node.parent.flags & 16 /* Private */); } function emitTypeParameters(typeParameters) { function emitTypeParameter(node) { @@ -28508,7 +28959,7 @@ var ts; break; case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - if (node.parent.flags & 128 /* Static */) { + if (node.parent.flags & 64 /* Static */) { diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; } else if (node.parent.parent.kind === 214 /* ClassDeclaration */) { @@ -28574,7 +29025,7 @@ var ts; function emitParameterProperties(constructorDeclaration) { if (constructorDeclaration) { ts.forEach(constructorDeclaration.parameters, function (param) { - if (param.flags & 112 /* AccessibilityModifier */) { + if (param.flags & 56 /* AccessibilityModifier */) { emitPropertyDeclaration(param); } }); @@ -28582,7 +29033,7 @@ var ts; } emitJsDocComments(node); emitModuleElementDeclarationFlags(node); - if (node.flags & 256 /* Abstract */) { + if (node.flags & 128 /* Abstract */) { write("abstract "); } write("class "); @@ -28652,7 +29103,7 @@ var ts; if ((node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) && node.parent.kind === 155 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.flags & 32 /* Private */)) { + else if (!(node.flags & 16 /* Private */)) { writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); } } @@ -28667,7 +29118,7 @@ var ts; } else if (node.kind === 141 /* PropertyDeclaration */ || node.kind === 140 /* PropertySignature */) { // TODO(jfreeman): Deal with computed properties in error reporting. - if (node.flags & 128 /* Static */) { + if (node.flags & 64 /* Static */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -28771,7 +29222,7 @@ var ts; emitJsDocComments(accessors.setAccessor); emitClassMemberDeclarationFlags(node); writeTextOfNode(currentSourceFile, node.name); - if (!(node.flags & 32 /* Private */)) { + if (!(node.flags & 16 /* Private */)) { accessorWithTypeAnnotation = node; var type = getTypeAnnotationFromAccessor(node); if (!type) { @@ -28800,7 +29251,7 @@ var ts; var diagnosticMessage; if (accessorWithTypeAnnotation.kind === 146 /* SetAccessor */) { // Setters have to have type named and cannot infer it so, the type should always be named - if (accessorWithTypeAnnotation.parent.flags & 128 /* Static */) { + if (accessorWithTypeAnnotation.parent.flags & 64 /* Static */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_name_1_from_private_module_2 : ts.Diagnostics.Parameter_0_of_public_static_property_setter_from_exported_class_has_or_is_using_private_name_1; @@ -28818,7 +29269,7 @@ var ts; }; } else { - if (accessorWithTypeAnnotation.flags & 128 /* Static */) { + if (accessorWithTypeAnnotation.flags & 64 /* Static */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_property_getter_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -28905,7 +29356,7 @@ var ts; emitType(node.type); } } - else if (node.kind !== 144 /* Constructor */ && !(node.flags & 32 /* Private */)) { + else if (node.kind !== 144 /* Constructor */ && !(node.flags & 16 /* Private */)) { writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); } enclosingDeclaration = prevEnclosingDeclaration; @@ -28936,7 +29387,7 @@ var ts; break; case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - if (node.flags & 128 /* Static */) { + if (node.flags & 64 /* Static */) { diagnosticMessage = symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : @@ -28997,7 +29448,7 @@ var ts; node.parent.parent.kind === 155 /* TypeLiteral */) { emitTypeOfVariableDeclarationFromTypeLiteral(node); } - else if (!(node.parent.flags & 32 /* Private */)) { + else if (!(node.parent.flags & 16 /* Private */)) { writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); } function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult) { @@ -29028,7 +29479,7 @@ var ts; ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: - if (node.parent.flags & 128 /* Static */) { + if (node.parent.flags & 64 /* Static */) { return symbolAccesibilityResult.errorModuleName ? symbolAccesibilityResult.accessibility === 2 /* CannotBeNamed */ ? ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : @@ -29170,7 +29621,7 @@ var ts; } } function writeReferencePath(referencedFile) { - var declFileName = referencedFile.flags & 8192 /* DeclarationFile */ + var declFileName = referencedFile.flags & 4096 /* DeclarationFile */ ? referencedFile.fileName // Declaration file, use declaration file name : ts.shouldEmitToOwnFile(referencedFile, compilerOptions) ? ts.getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file @@ -29216,6 +29667,12 @@ var ts; return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); } ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; + var Jump; + (function (Jump) { + Jump[Jump["Break"] = 2] = "Break"; + Jump[Jump["Continue"] = 4] = "Continue"; + Jump[Jump["Return"] = 8] = "Return"; + })(Jump || (Jump = {})); var entities = { "quot": 0x0022, "amp": 0x0026, @@ -29525,16 +29982,8 @@ var ts; diagnostics: diagnostics, sourceMaps: sourceMapDataList }; - function isNodeDescendentOf(node, ancestor) { - while (node) { - if (node === ancestor) - return true; - node = node.parent; - } - return false; - } function isUniqueLocalName(name, container) { - for (var node = container; isNodeDescendentOf(node, container); node = node.nextContainer) { + for (var node = container; ts.isNodeDescendentOf(node, container); node = node.nextContainer) { if (node.locals && ts.hasProperty(node.locals, name)) { // We conservatively include alias symbols to cover cases where they're emitted as locals if (node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) { @@ -29544,12 +29993,6 @@ var ts; } return true; } - var Jump; - (function (Jump) { - Jump[Jump["Break"] = 2] = "Break"; - Jump[Jump["Continue"] = 4] = "Continue"; - Jump[Jump["Return"] = 8] = "Return"; - })(Jump || (Jump = {})); function setLabeledJump(state, isBreak, labelText, labelMarker) { if (isBreak) { if (!state.labeledNonLocalBreaks) { @@ -31026,7 +31469,7 @@ var ts; write("]"); } else { - emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ (node.flags & 2048 /* MultiLine */) !== 0, + emitListWithSpread(elements, /*needsUniqueCopy*/ true, /*multiLine*/ (node.flags & 1024 /* MultiLine */) !== 0, /*trailingComma*/ elements.hasTrailingComma, /*useConcat*/ true); } } @@ -31045,7 +31488,7 @@ var ts; emitLinePreservingList(node, properties, /* allowTrailingComma */ languageVersion >= 1 /* ES5 */, /* spacesBetweenBraces */ true); } else { - var multiLine = (node.flags & 2048 /* MultiLine */) !== 0; + var multiLine = (node.flags & 1024 /* MultiLine */) !== 0; if (!multiLine) { write(" "); } @@ -31064,7 +31507,7 @@ var ts; write("}"); } function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = (node.flags & 2048 /* MultiLine */) !== 0; + var multiLine = (node.flags & 1024 /* MultiLine */) !== 0; var properties = node.properties; write("("); if (multiLine) { @@ -31693,7 +32136,7 @@ var ts; var current = node; while (current) { if (current.kind === 248 /* SourceFile */) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 1 /* Export */) !== 0); + return !isExported || ((ts.getCombinedNodeFlags(node) & 2 /* Export */) !== 0); } else if (ts.isFunctionLike(current) || current.kind === 219 /* ModuleBlock */) { return false; @@ -31934,7 +32377,7 @@ var ts; // variables in variable declaration list were already hoisted return false; } - if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 49152 /* BlockScoped */) === 0) { + if (convertedLoopState && (ts.getCombinedNodeFlags(decl) & 24576 /* BlockScoped */) === 0) { // we are inside a converted loop - this can only happen in downlevel scenarios // record names for all variable declarations for (var _a = 0, _b = decl.declarations; _a < _b.length; _a++) { @@ -32019,7 +32462,7 @@ var ts; break; } var loopParameters; - if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 49152 /* BlockScoped */)) { + if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 24576 /* BlockScoped */)) { // if loop initializer contains block scoped variables - they should be passed to converted loop body as parameters loopParameters = []; for (var _a = 0, _b = loopInitializer.declarations; _a < _b.length; _a++) { @@ -32334,10 +32777,12 @@ var ts; // // for (let v of arr) { } // - // we don't want to emit a temporary variable for the RHS, just use it directly. - var rhsIsIdentifier = node.expression.kind === 69 /* Identifier */; + // we can't reuse 'arr' because it might be modified within the body of the loop. var counter = createTempVariable(268435456 /* _i */); - var rhsReference = rhsIsIdentifier ? node.expression : createTempVariable(0 /* Auto */); + var rhsReference = ts.createSynthesizedNode(69 /* Identifier */); + rhsReference.text = node.expression.kind === 69 /* Identifier */ ? + makeUniqueName(node.expression.text) : + makeTempVariableName(0 /* Auto */); // This is the let keyword for the counter and rhsReference. The let keyword for // the LHS will be emitted inside the body. emitStart(node.expression); @@ -32346,15 +32791,13 @@ var ts; emitNodeWithoutSourceMap(counter); write(" = 0"); emitEnd(node.expression); - if (!rhsIsIdentifier) { - // , _a = expr - write(", "); - emitStart(node.expression); - emitNodeWithoutSourceMap(rhsReference); - write(" = "); - emitNodeWithoutSourceMap(node.expression); - emitEnd(node.expression); - } + // , _a = expr + write(", "); + emitStart(node.expression); + emitNodeWithoutSourceMap(rhsReference); + write(" = "); + emitNodeWithoutSourceMap(node.expression); + emitEnd(node.expression); write("; "); // _i < _a.length; emitStart(node.initializer); @@ -32609,7 +33052,7 @@ var ts; } function emitModuleMemberName(node) { emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 1 /* Export */) { + if (ts.getCombinedNodeFlags(node) & 2 /* Export */) { var container = getContainingModule(node); if (container) { write(getGeneratedNameForNode(container)); @@ -32631,7 +33074,7 @@ var ts; } function emitEs6ExportDefaultCompat(node) { if (node.parent.kind === 248 /* SourceFile */) { - ts.Debug.assert(!!(node.flags & 1024 /* Default */) || node.kind === 227 /* ExportAssignment */); + ts.Debug.assert(!!(node.flags & 512 /* Default */) || node.kind === 227 /* ExportAssignment */); // only allow export default at a source file level if (modulekind === 1 /* CommonJS */ || modulekind === 2 /* AMD */ || modulekind === 3 /* UMD */) { if (!currentSourceFile.symbol.exports["___esModule"]) { @@ -32649,7 +33092,7 @@ var ts; } } function emitExportMemberAssignment(node) { - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { writeLine(); emitStart(node); // emit call to exporter only for top level nodes @@ -32657,7 +33100,7 @@ var ts; // emit export default as // export("default", ) write(exportFunctionForFile + "(\""); - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { write("default"); } else { @@ -32668,7 +33111,7 @@ var ts; write(")"); } else { - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { emitEs6ExportDefaultCompat(node); if (languageVersion === 0 /* ES3 */) { write("exports[\"default\"]"); @@ -32772,7 +33215,7 @@ var ts; // because actual variable declarations are hoisted var canDefineTempVariablesInPlace = false; if (root.kind === 211 /* VariableDeclaration */) { - var isExported = ts.getCombinedNodeFlags(root) & 1 /* Export */; + var isExported = ts.getCombinedNodeFlags(root) & 2 /* Export */; var isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } @@ -32854,8 +33297,8 @@ var ts; // to ensure value is evaluated exactly once. value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); } - for (var _a = 0; _a < properties.length; _a++) { - var p = properties[_a]; + for (var _a = 0, properties_5 = properties; _a < properties_5.length; _a++) { + var p = properties_5[_a]; if (p.kind === 245 /* PropertyAssignment */ || p.kind === 246 /* ShorthandPropertyAssignment */) { var propName = p.name; var target_1 = p.kind === 246 /* ShorthandPropertyAssignment */ ? p : p.initializer || propName; @@ -32990,7 +33433,7 @@ var ts; // this is necessary to preserve ES6 semantic in scenarios like // for (...) { let x; console.log(x); x = 1 } // assignment on one iteration should not affect other iterations var isLetDefinedInLoop = (resolver.getNodeCheckFlags(node) & 16384 /* BlockScopedBindingInLoop */) && - (getCombinedFlagsForIdentifier(node.name) & 16384 /* Let */); + (getCombinedFlagsForIdentifier(node.name) & 8192 /* Let */); // NOTE: default initialization should not be added to let bindings in for-in\for-of statements if (isLetDefinedInLoop && node.parent.parent.kind !== 200 /* ForInStatement */ && @@ -33030,13 +33473,13 @@ var ts; return ts.getCombinedNodeFlags(node.parent); } function isES6ExportedDeclaration(node) { - return !!(node.flags & 1 /* Export */) && + return !!(node.flags & 2 /* Export */) && modulekind === 5 /* ES6 */ && node.parent.kind === 248 /* SourceFile */; } function emitVariableStatement(node) { var startIsEmitted = false; - if (node.flags & 1 /* Export */) { + if (node.flags & 2 /* Export */) { if (isES6ExportedDeclaration(node)) { // Exported ES6 module member write("export "); @@ -33063,7 +33506,7 @@ var ts; function shouldEmitLeadingAndTrailingCommentsForVariableStatement(node) { // If we're not exporting the variables, there's nothing special here. // Always emit comments for these nodes. - if (!(node.flags & 1 /* Export */)) { + if (!(node.flags & 2 /* Export */)) { return true; } // If we are exporting, but it's a top-level ES6 module exports, @@ -33246,7 +33689,7 @@ var ts; if (!shouldEmitAsArrowFunction(node)) { if (isES6ExportedDeclaration(node)) { write("export "); - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { write("default "); } } @@ -33466,7 +33909,7 @@ var ts; emitRestParameter(node); } function emitExpressionFunctionBody(node, body) { - if (languageVersion < 2 /* ES6 */ || node.flags & 512 /* Async */) { + if (languageVersion < 2 /* ES6 */ || node.flags & 256 /* Async */) { emitDownLevelExpressionFunctionBody(node, body); return; } @@ -33487,7 +33930,7 @@ var ts; scopeEmitStart(node); increaseIndent(); var outPos = writer.getTextPos(); - emitDetachedComments(node.body); + emitDetachedCommentsAndUpdateCommentsInfo(node.body); emitFunctionBodyPreamble(node); var preambleEmitted = writer.getTextPos() !== outPos; decreaseIndent(); @@ -33525,7 +33968,7 @@ var ts; scopeEmitStart(node); var initialTextPos = writer.getTextPos(); increaseIndent(); - emitDetachedComments(body.statements); + emitDetachedCommentsAndUpdateCommentsInfo(body.statements); // Emit all the directive prologues (like "use strict"). These have to come before // any other preamble code we write (like parameter initializers). var startIndex = emitDirectivePrologues(body.statements, /*startWithNewLine*/ true); @@ -33569,7 +34012,7 @@ var ts; } function emitParameterPropertyAssignments(node) { ts.forEach(node.parameters, function (param) { - if (param.flags & 112 /* AccessibilityModifier */) { + if (param.flags & 56 /* AccessibilityModifier */) { writeLine(); emitStart(param); emitStart(param.name); @@ -33604,15 +34047,15 @@ var ts; var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 141 /* PropertyDeclaration */ && isStatic === ((member.flags & 128 /* Static */) !== 0) && member.initializer) { + if (member.kind === 141 /* PropertyDeclaration */ && isStatic === ((member.flags & 64 /* Static */) !== 0) && member.initializer) { properties.push(member); } } return properties; } function emitPropertyDeclarations(node, properties) { - for (var _a = 0; _a < properties.length; _a++) { - var property = properties[_a]; + for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) { + var property = properties_6[_a]; emitPropertyDeclaration(node, property); } } @@ -33625,7 +34068,7 @@ var ts; emit(receiver); } else { - if (property.flags & 128 /* Static */) { + if (property.flags & 64 /* Static */) { emitDeclarationName(node); } else { @@ -33724,7 +34167,7 @@ var ts; writeLine(); emitLeadingComments(member); emitStart(member); - if (member.flags & 128 /* Static */) { + if (member.flags & 64 /* Static */) { write("static "); } if (member.kind === 145 /* GetAccessor */) { @@ -33774,7 +34217,7 @@ var ts; emitCommentsOnNotEmittedNode(member); } // Check if there is any non-static property assignment - if (member.kind === 141 /* PropertyDeclaration */ && member.initializer && (member.flags & 128 /* Static */) === 0) { + if (member.kind === 141 /* PropertyDeclaration */ && member.initializer && (member.flags & 64 /* Static */) === 0) { hasInstancePropertyWithInitializer = true; } }); @@ -33821,7 +34264,7 @@ var ts; // Emit all the directive prologues (like "use strict"). These have to come before // any other preamble code we write (like parameter initializers). startIndex = emitDirectivePrologues(ctor.body.statements, /*startWithNewLine*/ true); - emitDetachedComments(ctor.body.statements); + emitDetachedCommentsAndUpdateCommentsInfo(ctor.body.statements); } emitCaptureThisForNodeIfNecessary(node); var superCall; @@ -33941,7 +34384,7 @@ var ts; // _default = __decorate([dec], _default); // export default _default; // - if (isES6ExportedDeclaration(node) && !(node.flags & 1024 /* Default */)) { + if (isES6ExportedDeclaration(node) && !(node.flags & 512 /* Default */)) { write("export "); } write("let "); @@ -33950,7 +34393,7 @@ var ts; } else if (isES6ExportedDeclaration(node)) { write("export "); - if (node.flags & 1024 /* Default */) { + if (node.flags & 512 /* Default */) { write("default "); } } @@ -33980,7 +34423,7 @@ var ts; // emit name if // - node has a name // - this is default export with static initializers - if ((node.name || (node.flags & 1024 /* Default */ && staticProperties.length > 0)) && !thisNodeIsDecorated) { + if ((node.name || (node.flags & 512 /* Default */ && staticProperties.length > 0)) && !thisNodeIsDecorated) { write(" "); emitDeclarationName(node); } @@ -34016,8 +34459,8 @@ var ts; // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. if (isClassExpressionWithStaticProperties) { - for (var _a = 0; _a < staticProperties.length; _a++) { - var property = staticProperties[_a]; + for (var _a = 0, staticProperties_1 = staticProperties; _a < staticProperties_1.length; _a++) { + var property = staticProperties_1[_a]; write(","); writeLine(); emitPropertyDeclaration(node, property, /*receiver:*/ tempVariable, /*isExpression:*/ true); @@ -34035,7 +34478,7 @@ var ts; } // If this is an exported class, but not on the top level (i.e. on an internal // module), export it - if (!isES6ExportedDeclaration(node) && (node.flags & 1 /* Export */)) { + if (!isES6ExportedDeclaration(node) && (node.flags & 2 /* Export */)) { writeLine(); emitStart(node); emitModuleMemberName(node); @@ -34044,7 +34487,7 @@ var ts; emitEnd(node); write(";"); } - else if (isES6ExportedDeclaration(node) && (node.flags & 1024 /* Default */) && thisNodeIsDecorated) { + else if (isES6ExportedDeclaration(node) && (node.flags & 512 /* Default */) && thisNodeIsDecorated) { // if this is a top level default export of decorated class, write the export after the declaration. writeLine(); write("export default "); @@ -34126,13 +34569,13 @@ var ts; } function emitClassMemberPrefix(node, member) { emitDeclarationName(node); - if (!(member.flags & 128 /* Static */)) { + if (!(member.flags & 64 /* Static */)) { write(".prototype"); } } function emitDecoratorsOfClass(node) { emitDecoratorsOfMembers(node, /*staticFlag*/ 0); - emitDecoratorsOfMembers(node, 128 /* Static */); + emitDecoratorsOfMembers(node, 64 /* Static */); emitDecoratorsOfConstructor(node); } function emitDecoratorsOfConstructor(node) { @@ -34179,7 +34622,7 @@ var ts; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; // only emit members in the correct group - if ((member.flags & 128 /* Static */) !== staticFlag) { + if ((member.flags & 64 /* Static */) !== staticFlag) { continue; } // skip members that cannot be decorated (such as the constructor) @@ -34580,7 +35023,7 @@ var ts; } if (!shouldHoistDeclarationInSystemJsModule(node)) { // do not emit var if variable was already hoisted - if (!(node.flags & 1 /* Export */) || isES6ExportedDeclaration(node)) { + if (!(node.flags & 2 /* Export */) || isES6ExportedDeclaration(node)) { emitStart(node); if (isES6ExportedDeclaration(node)) { write("export "); @@ -34611,7 +35054,7 @@ var ts; emitModuleMemberName(node); write(" = {}));"); emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 1 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) { + if (!isES6ExportedDeclaration(node) && node.flags & 2 /* Export */ && !shouldHoistDeclarationInSystemJsModule(node)) { // do not emit var if variable was already hoisted writeLine(); emitStart(node); @@ -34623,7 +35066,7 @@ var ts; write(";"); } if (modulekind !== 5 /* ES6 */ && node.parent === currentSourceFile) { - if (modulekind === 4 /* System */ && (node.flags & 1 /* Export */)) { + if (modulekind === 4 /* System */ && (node.flags & 2 /* Export */)) { // write the call to exporter for enum writeLine(); write(exportFunctionForFile + "(\""); @@ -34728,7 +35171,7 @@ var ts; } write(")("); // write moduleDecl = containingModule.m only if it is not exported es6 module member - if ((node.flags & 1 /* Export */) && !isES6ExportedDeclaration(node)) { + if ((node.flags & 2 /* Export */) && !isES6ExportedDeclaration(node)) { emit(node.name); write(" = "); } @@ -34738,7 +35181,7 @@ var ts; write(" = {}));"); emitEnd(node); if (!isES6ExportedDeclaration(node) && node.name.kind === 69 /* Identifier */ && node.parent === currentSourceFile) { - if (modulekind === 4 /* System */ && (node.flags & 1 /* Export */)) { + if (modulekind === 4 /* System */ && (node.flags & 2 /* Export */)) { writeLine(); write(exportFunctionForFile + "(\""); emitDeclarationName(node); @@ -34841,7 +35284,7 @@ var ts; } function emitExternalImportDeclaration(node) { if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 221 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0; + var isExportedImport = node.kind === 221 /* ImportEqualsDeclaration */ && (node.flags & 2 /* Export */) !== 0; var namespaceDeclaration = getNamespaceDeclarationNode(node); if (modulekind !== 2 /* AMD */) { emitLeadingComments(node); @@ -34923,7 +35366,7 @@ var ts; write("export "); write("var "); } - else if (!(node.flags & 1 /* Export */)) { + else if (!(node.flags & 2 /* Export */)) { write("var "); } } @@ -35014,8 +35457,8 @@ var ts; function emitExportOrImportSpecifierList(specifiers, shouldEmit) { ts.Debug.assert(modulekind === 5 /* ES6 */); var needsComma = false; - for (var _a = 0; _a < specifiers.length; _a++) { - var specifier = specifiers[_a]; + for (var _a = 0, specifiers_1 = specifiers; _a < specifiers_1.length; _a++) { + var specifier = specifiers_1[_a]; if (shouldEmit(specifier)) { if (needsComma) { write(", "); @@ -35158,8 +35601,8 @@ var ts; } writeLine(); var started = false; - for (var _a = 0; _a < externalImports.length; _a++) { - var importNode = externalImports[_a]; + for (var _a = 0, externalImports_1 = externalImports; _a < externalImports_1.length; _a++) { + var importNode = externalImports_1[_a]; // do not create variable declaration for exports and imports that lack import clause var skipNode = importNode.kind === 228 /* ExportDeclaration */ || (importNode.kind === 222 /* ImportDeclaration */ && !importNode.importClause); @@ -35193,8 +35636,8 @@ var ts; // no exported declarations (export var ...) or export specifiers (export {x}) // check if we have any non star export declarations. var hasExportDeclarationWithExportClause = false; - for (var _a = 0; _a < externalImports.length; _a++) { - var externalImport = externalImports[_a]; + for (var _a = 0, externalImports_2 = externalImports; _a < externalImports_2.length; _a++) { + var externalImport = externalImports_2[_a]; if (externalImport.kind === 228 /* ExportDeclaration */ && externalImport.exportClause) { hasExportDeclarationWithExportClause = true; break; @@ -35225,8 +35668,8 @@ var ts; } } } - for (var _d = 0; _d < externalImports.length; _d++) { - var externalImport = externalImports[_d]; + for (var _d = 0, externalImports_3 = externalImports; _d < externalImports_3.length; _d++) { + var externalImport = externalImports_3[_d]; if (externalImport.kind !== 228 /* ExportDeclaration */) { continue; } @@ -35275,7 +35718,7 @@ var ts; function writeExportedName(node) { // do not record default exports // they are local to module and never overwritten (explicitly skipped) by star export - if (node.kind !== 69 /* Identifier */ && node.flags & 1024 /* Default */) { + if (node.kind !== 69 /* Identifier */ && node.flags & 512 /* Default */) { return; } if (started) { @@ -35338,7 +35781,7 @@ var ts; emit(local); } var flags = ts.getCombinedNodeFlags(local.kind === 69 /* Identifier */ ? local.parent : local); - if (flags & 1 /* Export */) { + if (flags & 2 /* Export */) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -35348,11 +35791,11 @@ var ts; write(";"); } if (hoistedFunctionDeclarations) { - for (var _a = 0; _a < hoistedFunctionDeclarations.length; _a++) { - var f = hoistedFunctionDeclarations[_a]; + for (var _a = 0, hoistedFunctionDeclarations_1 = hoistedFunctionDeclarations; _a < hoistedFunctionDeclarations_1.length; _a++) { + var f = hoistedFunctionDeclarations_1[_a]; writeLine(); emit(f); - if (f.flags & 1 /* Export */) { + if (f.flags & 2 /* Export */) { if (!exportedDeclarations) { exportedDeclarations = []; } @@ -35362,7 +35805,7 @@ var ts; } return exportedDeclarations; function visit(node) { - if (node.flags & 2 /* Ambient */) { + if (node.flags & 4 /* Ambient */) { return; } if (node.kind === 213 /* FunctionDeclaration */) { @@ -35437,7 +35880,7 @@ var ts; // - it is top level block scoped // if block scoped variables are nested in some another block then // no other functions can use them except ones that are defined at least in the same block - return (ts.getCombinedNodeFlags(node) & 49152 /* BlockScoped */) === 0 || + return (ts.getCombinedNodeFlags(node) & 24576 /* BlockScoped */) === 0 || ts.getEnclosingBlockScopeContainer(node).kind === 248 /* SourceFile */; } function isCurrentFileSystemExternalModule() { @@ -35509,8 +35952,8 @@ var ts; var parameterName = makeUniqueName(ts.forEach(group, getLocalNameForExternalImport) || ""); write("function (" + parameterName + ") {"); increaseIndent(); - for (var _a = 0; _a < group.length; _a++) { - var entry = group[_a]; + for (var _a = 0, group_1 = group; _a < group_1.length; _a++) { + var entry = group_1[_a]; var importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { case 222 /* ImportDeclaration */: @@ -35679,8 +36122,8 @@ var ts; unaliasedModuleNames.push("\"" + amdDependency.path + "\""); } } - for (var _c = 0; _c < externalImports.length; _c++) { - var importNode = externalImports[_c]; + for (var _c = 0, externalImports_4 = externalImports; _c < externalImports_4.length; _c++) { + var importNode = externalImports_4[_c]; // Find the name of the external module var externalModuleName = getExternalModuleNameText(importNode); // Find the name of the module alias, if there is one @@ -35959,7 +36402,7 @@ var ts; // Start new file on new line writeLine(); emitShebang(); - emitDetachedComments(node); + emitDetachedCommentsAndUpdateCommentsInfo(node); if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { var emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[1 /* CommonJS */]; emitModule(node); @@ -35983,7 +36426,7 @@ var ts; } function emitNodeConsideringCommentsOption(node, emitNodeConsideringSourcemap) { if (node) { - if (node.flags & 2 /* Ambient */) { + if (node.flags & 4 /* Ambient */) { return emitCommentsOnNotEmittedNode(node); } if (isSpecializedCommentHandling(node)) { @@ -36232,10 +36675,6 @@ var ts; } return leadingComments; } - function isPinnedComments(comment) { - return currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ && - currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; - } /** * Determine if the given comment is a triple-slash * @@ -36350,57 +36789,14 @@ var ts; // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space ts.emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); } - function emitDetachedComments(node) { - var leadingComments; - if (compilerOptions.removeComments) { - // removeComments is true, only reserve pinned comment at the top of file - // For example: - // /*! Pinned Comment */ - // - // var x = 10; - if (node.pos === 0) { - leadingComments = ts.filter(ts.getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComments); + function emitDetachedCommentsAndUpdateCommentsInfo(node) { + var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments); + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); } - } - else { - // removeComments is false, just get detached as normal and bypass the process to filter comment - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); - } - if (leadingComments) { - var detachedComments = []; - var lastComment; - ts.forEach(leadingComments, function (comment) { - if (lastComment) { - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, lastComment.end); - var commentLine = ts.getLineOfLocalPosition(currentSourceFile, comment.pos); - if (commentLine >= lastCommentLine + 2) { - // There was a blank line between the last comment and this comment. This - // comment is not part of the copyright comments. Return what we have so - // far. - return detachedComments; - } - } - detachedComments.push(comment); - lastComment = comment; - }); - if (detachedComments.length) { - // All comments look like they could have been part of the copyright header. Make - // sure there is at least one blank line between it and the node. If not, it's not - // a copyright header. - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); - var nodeLine = ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); - if (nodeLine >= lastCommentLine + 2) { - // Valid detachedComments - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - ts.emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); - var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; } } } @@ -36716,7 +37112,7 @@ var ts; var resolveModuleNamesWorker = host.resolveModuleNames ? (function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }) : (function (moduleNames, containingFile) { return ts.map(moduleNames, function (moduleName) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }); }); - var filesByName = ts.createFileMap(getCanonicalFileName); + var filesByName = ts.createFileMap(); // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; @@ -36774,8 +37170,8 @@ var ts; // Initialize a checker so that all our files are bound. getTypeChecker(); classifiableNames = {}; - for (var _i = 0; _i < files.length; _i++) { - var sourceFile = files[_i]; + for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { + var sourceFile = files_3[_i]; ts.copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -36793,7 +37189,7 @@ var ts; } // check if program source files has changed in the way that can affect structure of the program var newSourceFiles = []; - var normalizedAbsoluteFileNames = []; + var filePaths = []; var modifiedSourceFiles = []; for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { var oldSourceFile = _a[_i]; @@ -36801,8 +37197,8 @@ var ts; if (!newSourceFile) { return false; } - var normalizedAbsolutePath = ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory); - normalizedAbsoluteFileNames.push(normalizedAbsolutePath); + newSourceFile.path = oldSourceFile.path; + filePaths.push(newSourceFile.path); if (oldSourceFile !== newSourceFile) { if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) { // value of no-default-lib has changed @@ -36822,7 +37218,7 @@ var ts; } if (resolveModuleNamesWorker) { var moduleNames = ts.map(newSourceFile.imports, function (name) { return name.text; }); - var resolutions = resolveModuleNamesWorker(moduleNames, normalizedAbsolutePath); + var resolutions = resolveModuleNamesWorker(moduleNames, ts.getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); // ensure that module resolution results are still correct for (var i = 0; i < moduleNames.length; ++i) { var newResolution = resolutions[i]; @@ -36850,12 +37246,12 @@ var ts; } // update fileName -> file mapping for (var i = 0, len = newSourceFiles.length; i < len; ++i) { - filesByName.set(normalizedAbsoluteFileNames[i], newSourceFiles[i]); + filesByName.set(filePaths[i], newSourceFiles[i]); } files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (var _b = 0; _b < modifiedSourceFiles.length; _b++) { - var modifiedFile = modifiedSourceFiles[_b]; + for (var _b = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _b < modifiedSourceFiles_1.length; _b++) { + var modifiedFile = modifiedSourceFiles_1[_b]; fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); } oldProgram.structureIsReused = true; @@ -36905,7 +37301,7 @@ var ts; return emitResult; } function getSourceFile(fileName) { - return filesByName.get(ts.getNormalizedAbsolutePath(fileName, currentDirectory)); + return filesByName.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)); } function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) { if (sourceFile) { @@ -37024,7 +37420,7 @@ var ts; } break; case 218 /* ModuleDeclaration */: - if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 2 /* Ambient */ || ts.isDeclarationFile(file))) { + if (node.name.kind === 9 /* StringLiteral */ && (node.flags & 4 /* Ambient */ || ts.isDeclarationFile(file))) { // TypeScript 1.0 spec (April 2014): 12.1.6 // An AmbientExternalModuleDeclaration declares an external module. // This type of declaration is permitted only in the global module. @@ -37049,7 +37445,7 @@ var ts; diagnostic = ts.Diagnostics.File_0_has_unsupported_extension_The_only_supported_extensions_are_1; diagnosticArgument = [fileName, "'" + ts.supportedExtensions.join("', '") + "'"]; } - else if (!findSourceFile(fileName, ts.getNormalizedAbsolutePath(fileName, currentDirectory), isDefaultLib, refFile, refPos, refEnd)) { + else if (!findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd)) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } @@ -37059,13 +37455,13 @@ var ts; } } else { - var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.getNormalizedAbsolutePath(fileName, currentDirectory), isDefaultLib, refFile, refPos, refEnd); + var nonTsFile = options.allowNonTsExtensions && findSourceFile(fileName, ts.toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = ts.Diagnostics.File_0_not_found; diagnosticArgument = [fileName]; } - else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.getNormalizedAbsolutePath(fileName + extension, currentDirectory), isDefaultLib, refFile, refPos, refEnd); })) { + else if (!ts.forEach(ts.supportedExtensions, function (extension) { return findSourceFile(fileName + extension, ts.toPath(fileName + extension, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); })) { diagnostic = ts.Diagnostics.File_0_not_found; fileName += ".ts"; diagnosticArgument = [fileName]; @@ -37111,6 +37507,7 @@ var ts; }); filesByName.set(normalizedAbsolutePath, file); if (file) { + file.path = normalizedAbsolutePath; if (host.useCaseSensitiveFileNames()) { // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case var existingFile = filesByNameIgnoreCase.get(normalizedAbsolutePath); @@ -37157,13 +37554,7 @@ var ts; var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); if (resolution && !options.noResolve) { - var absoluteImportPath = ts.isRootedDiskPath(resolution.resolvedFileName) - ? resolution.resolvedFileName - : ts.getNormalizedAbsolutePath(resolution.resolvedFileName, currentDirectory); - // convert an absolute import path to path that is relative to current directory - // this was host still can locate it but files names in user output will be shorter (and thus look nicer). - var relativePath = ts.getRelativePathToDirectoryOrUrl(currentDirectory, absoluteImportPath, currentDirectory, getCanonicalFileName, false); - var importedFile = findSourceFile(relativePath, absoluteImportPath, /* isDefaultLib */ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + var importedFile = findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /* isDefaultLib */ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { if (!ts.isExternalModule(importedFile)) { var start_2 = ts.getTokenPosOfNode(file.imports[i], file); @@ -37219,8 +37610,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0; _i < sourceFiles.length; _i++) { - var sourceFile = sourceFiles[_i]; + for (var _i = 0, sourceFiles_1 = sourceFiles; _i < sourceFiles_1.length; _i++) { + var sourceFile = sourceFiles_1[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -37344,6 +37735,7 @@ var ts; /// /// /// +/// /// var ts; (function (ts) { @@ -37493,6 +37885,12 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code }, + { + name: "pretty", + paramType: ts.Diagnostics.KIND, + description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental, + type: "boolean" + }, { name: "project", shortName: "p", @@ -37591,11 +37989,31 @@ var ts; description: ts.Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, error: ts.Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic }, + { + name: "allowUnusedLabels", + type: "boolean", + description: ts.Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "noImplicitReturns", + type: "boolean", + description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + { + name: "allowUnreachableCode", + type: "boolean", + description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code + }, { name: "forceConsistentCasingInFileNames", type: "boolean", description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file - }, + } ]; var optionNameMapCache; /* @internal */ @@ -37734,13 +38152,38 @@ var ts; */ function parseConfigFileTextToJson(fileName, jsonText) { try { - return { config: /\S/.test(jsonText) ? JSON.parse(jsonText) : {} }; + var jsonTextWithoutComments = removeComments(jsonText); + return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; } } ts.parseConfigFileTextToJson = parseConfigFileTextToJson; + /** + * Remove the comments from a json like text. + * Comments can be single line comments (starting with # or //) or multiline comments using / * * / + * + * This method replace comment content by whitespace rather than completely remove them to keep positions in json parsing error reporting accurate. + */ + function removeComments(jsonText) { + var output = ""; + var scanner = ts.createScanner(1 /* ES5 */, /* skipTrivia */ false, 0 /* Standard */, jsonText); + var token; + while ((token = scanner.scan()) !== 1 /* EndOfFileToken */) { + switch (token) { + case 2 /* SingleLineCommentTrivia */: + case 3 /* MultiLineCommentTrivia */: + // replace comments with whitespace to preserve original character positions + output += scanner.getTokenText().replace(/\S/g, " "); + break; + default: + output += scanner.getTokenText(); + break; + } + } + return output; + } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -37871,8 +38314,8 @@ var ts; var lastSingleLineCommentEnd = -1; var isFirstSingleLineComment = true; var singleLineCommentCount = 0; - for (var _i = 0; _i < comments.length; _i++) { - var currentComment = comments[_i]; + for (var _i = 0, comments_2 = comments; _i < comments_2.length; _i++) { + var currentComment = comments_2[_i]; // For single line comments, combine consecutive ones (2 or more) into // a single span from the start of the first till the end of the last if (currentComment.kind === 2 /* SingleLineCommentTrivia */) { @@ -38004,6 +38447,8 @@ var ts; function getNavigateToItems(program, cancellationToken, searchValue, maxResultCount) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; + // This means "compare in a case insensitive manner." + var baseSensitivity = { sensitivity: "base" }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); @@ -38017,8 +38462,8 @@ var ts; if (!matches) { continue; } - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) { + var declaration = declarations_6[_i]; // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. if (patternMatcher.patternContainsDots) { @@ -38047,8 +38492,8 @@ var ts; function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0; _i < matches.length; _i++) { - var match = matches[_i]; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; if (!match.isCaseSensitive) { return false; } @@ -38123,8 +38568,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0; _i < matches.length; _i++) { - var match = matches[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -38132,8 +38577,6 @@ var ts; } return bestMatchKind; } - // This means "compare in a case insensitive manner." - var baseSensitivity = { sensitivity: "base" }; function compareNavigateToItems(i1, i2) { // TODO(cyrusn): get the gamut of comparisons that VS already uses here. // Right now we just sort by kind first, and then by name of the item. @@ -38296,8 +38739,8 @@ var ts; } function addTopLevelNodes(nodes, topLevelNodes) { nodes = sortNodes(nodes); - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) { + var node = nodes_4[_i]; switch (node.kind) { case 214 /* ClassDeclaration */: case 217 /* EnumDeclaration */: @@ -38340,8 +38783,8 @@ var ts; function getItemsWorker(nodes, createItem) { var items = []; var keyToItem = {}; - for (var _i = 0; _i < nodes.length; _i++) { - var child = nodes[_i]; + for (var _i = 0, nodes_5 = nodes; _i < nodes_5.length; _i++) { + var child = nodes_5[_i]; var item = createItem(child); if (item !== undefined) { if (item.text.length > 0) { @@ -38389,7 +38832,7 @@ var ts; if (ts.isBindingPattern(node.name)) { break; } - if ((node.flags & 2035 /* Modifier */) === 0) { + if ((node.flags & 1022 /* Modifier */) === 0) { return undefined; } return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.memberVariableElement); @@ -38693,8 +39136,8 @@ var ts; // word part. That way we don't match something like 'Class' when the user types 'a'. // But we would match 'FooAttribute' (since 'Attribute' starts with 'a'). var wordSpans = getWordSpans(candidate); - for (var _i = 0; _i < wordSpans.length; _i++) { - var span = wordSpans[_i]; + for (var _i = 0, wordSpans_1 = wordSpans; _i < wordSpans_1.length; _i++) { + var span = wordSpans_1[_i]; if (partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ true)) { return createPatternMatch(PatternMatchKind.substring, punctuationStripped, /*isCaseSensitive:*/ partStartsWith(candidate, span, chunk.text, /*ignoreCase:*/ false)); @@ -38800,8 +39243,8 @@ var ts; // Only if all words have some sort of match is the pattern considered matched. var subWordTextChunks = segment.subWordTextChunks; var matches = undefined; - for (var _i = 0; _i < subWordTextChunks.length; _i++) { - var subWordTextChunk = subWordTextChunks[_i]; + for (var _i = 0, subWordTextChunks_1 = subWordTextChunks; _i < subWordTextChunks_1.length; _i++) { + var subWordTextChunk = subWordTextChunks_1[_i]; // Try to match the candidate with this word var result = matchTextChunk(candidate, subWordTextChunk, /*punctuationStripped:*/ true); if (!result) { @@ -39386,8 +39829,8 @@ var ts; var nameToDeclarations = sourceFile_1.getNamedDeclarations(); var declarations = ts.getProperty(nameToDeclarations, name.text); if (declarations) { - for (var _b = 0; _b < declarations.length; _b++) { - var declaration = declarations[_b]; + for (var _b = 0, declarations_7 = declarations; _b < declarations_7.length; _b++) { + var declaration = declarations_7[_b]; var symbol = declaration.symbol; if (symbol) { var type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration); @@ -39503,8 +39946,8 @@ var ts; // arg index. var argumentIndex = 0; var listChildren = argumentsList.getChildren(); - for (var _i = 0; _i < listChildren.length; _i++) { - var child = listChildren[_i]; + for (var _i = 0, listChildren_1 = listChildren; _i < listChildren_1.length; _i++) { + var child = listChildren_1[_i]; if (child === node) { break; } @@ -40049,8 +40492,8 @@ var ts; return n; } var children = n.getChildren(); - for (var _i = 0; _i < children.length; _i++) { - var child = children[_i]; + for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { + var child = children_1[_i]; var shouldDiveInChildNode = // previous token is enclosed somewhere in the child (child.pos <= previousToken.pos && child.end > previousToken.end) || @@ -40212,17 +40655,17 @@ var ts; function getNodeModifiers(node) { var flags = ts.getCombinedNodeFlags(node); var result = []; - if (flags & 32 /* Private */) + if (flags & 16 /* Private */) result.push(ts.ScriptElementKindModifier.privateMemberModifier); - if (flags & 64 /* Protected */) + if (flags & 32 /* Protected */) result.push(ts.ScriptElementKindModifier.protectedMemberModifier); - if (flags & 16 /* Public */) + if (flags & 8 /* Public */) result.push(ts.ScriptElementKindModifier.publicMemberModifier); - if (flags & 128 /* Static */) + if (flags & 64 /* Static */) result.push(ts.ScriptElementKindModifier.staticModifier); - if (flags & 256 /* Abstract */) + if (flags & 128 /* Abstract */) result.push(ts.ScriptElementKindModifier.abstractModifier); - if (flags & 1 /* Export */) + if (flags & 2 /* Export */) result.push(ts.ScriptElementKindModifier.exportedModifier); if (ts.isInAmbientContext(node)) result.push(ts.ScriptElementKindModifier.ambientModifier); @@ -42366,8 +42809,8 @@ var ts; } } var inheritedIndentation = -1 /* Unknown */; - for (var _i = 0; _i < nodes.length; _i++) { - var child = nodes[_i]; + for (var _i = 0, nodes_6 = nodes; _i < nodes_6.length; _i++) { + var child = nodes_6[_i]; inheritedIndentation = processChildNode(child, inheritedIndentation, node, listDynamicIndentation, startLine, startLine, /*isListElement*/ true); } if (listEndToken !== 0 /* Unknown */) { @@ -42458,8 +42901,8 @@ var ts; } } function processTrivia(trivia, parent, contextNode, dynamicIndentation) { - for (var _i = 0; _i < trivia.length; _i++) { - var triviaItem = trivia[_i]; + for (var _i = 0, trivia_1 = trivia; _i < trivia_1.length; _i++) { + var triviaItem = trivia_1[_i]; if (ts.isComment(triviaItem.kind) && ts.rangeContainsRange(originalRange, triviaItem)) { var triviaItemStart = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos); processRange(triviaItem, triviaItemStart, parent, contextNode, dynamicIndentation); @@ -43056,7 +43499,6 @@ var ts; return node; } } - return node; } } function deriveActualIndentationFromList(list, index, sourceFile, options) { @@ -43307,17 +43749,17 @@ var ts; while (pos < end) { var token = scanner.scan(); var textPos = scanner.getTextPos(); - nodes.push(createNode(token, pos, textPos, 4096 /* Synthetic */, this)); + nodes.push(createNode(token, pos, textPos, 2048 /* Synthetic */, this)); pos = textPos; } return pos; }; NodeObject.prototype.createSyntaxList = function (nodes) { - var list = createNode(271 /* SyntaxList */, nodes.pos, nodes.end, 4096 /* Synthetic */, this); + var list = createNode(271 /* SyntaxList */, nodes.pos, nodes.end, 2048 /* Synthetic */, this); list._children = []; var pos = nodes.pos; - for (var _i = 0; _i < nodes.length; _i++) { - var node = nodes[_i]; + for (var _i = 0, nodes_7 = nodes; _i < nodes_7.length; _i++) { + var node = nodes_7[_i]; if (pos < node.pos) { pos = this.addSyntheticNodes(list._children, pos, node.pos); } @@ -43872,7 +44314,7 @@ var ts; break; case 138 /* Parameter */: // Only consider properties defined as constructor parameters - if (!(node.flags & 112 /* AccessibilityModifier */)) { + if (!(node.flags & 56 /* AccessibilityModifier */)) { break; } // fall through @@ -44148,13 +44590,15 @@ var ts; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; + this.getCanonicalFileName = getCanonicalFileName; // script id => script index - this.fileNameToEntry = ts.createFileMap(getCanonicalFileName); + this.currentDirectory = host.getCurrentDirectory(); + this.fileNameToEntry = ts.createFileMap(); // Initialize the list with the root file names var rootFileNames = host.getScriptFileNames(); - for (var _i = 0; _i < rootFileNames.length; _i++) { - var fileName = rootFileNames[_i]; - this.createEntry(fileName); + for (var _i = 0, rootFileNames_1 = rootFileNames; _i < rootFileNames_1.length; _i++) { + var fileName = rootFileNames_1[_i]; + this.createEntry(fileName, ts.toPath(fileName, this.currentDirectory, getCanonicalFileName)); } // store the compilation settings this._compilationSettings = host.getCompilationSettings() || getDefaultCompilerOptions(); @@ -44162,7 +44606,7 @@ var ts; HostCache.prototype.compilationSettings = function () { return this._compilationSettings; }; - HostCache.prototype.createEntry = function (fileName) { + HostCache.prototype.createEntry = function (fileName, path) { var entry; var scriptSnapshot = this.host.getScriptSnapshot(fileName); if (scriptSnapshot) { @@ -44172,36 +44616,37 @@ var ts; scriptSnapshot: scriptSnapshot }; } - this.fileNameToEntry.set(fileName, entry); + this.fileNameToEntry.set(path, entry); return entry; }; - HostCache.prototype.getEntry = function (fileName) { - return this.fileNameToEntry.get(fileName); + HostCache.prototype.getEntry = function (path) { + return this.fileNameToEntry.get(path); }; - HostCache.prototype.contains = function (fileName) { - return this.fileNameToEntry.contains(fileName); + HostCache.prototype.contains = function (path) { + return this.fileNameToEntry.contains(path); }; HostCache.prototype.getOrCreateEntry = function (fileName) { - if (this.contains(fileName)) { - return this.getEntry(fileName); + var path = ts.toPath(fileName, this.currentDirectory, this.getCanonicalFileName); + if (this.contains(path)) { + return this.getEntry(path); } - return this.createEntry(fileName); + return this.createEntry(fileName, path); }; HostCache.prototype.getRootFileNames = function () { var fileNames = []; - this.fileNameToEntry.forEachValue(function (value) { + this.fileNameToEntry.forEachValue(function (path, value) { if (value) { fileNames.push(value.hostFileName); } }); return fileNames; }; - HostCache.prototype.getVersion = function (fileName) { - var file = this.getEntry(fileName); + HostCache.prototype.getVersion = function (path) { + var file = this.getEntry(path); return file && file.version; }; - HostCache.prototype.getScriptSnapshot = function (fileName) { - var file = this.getEntry(fileName); + HostCache.prototype.getScriptSnapshot = function (path) { + var file = this.getEntry(path); return file && file.scriptSnapshot; }; return HostCache; @@ -44383,7 +44828,8 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; - function createDocumentRegistry(useCaseSensitiveFileNames) { + function createDocumentRegistry(useCaseSensitiveFileNames, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } // Maps from compiler setting target (ES3, ES5, etc.) to all the cached documents we have // for those settings. var buckets = {}; @@ -44395,7 +44841,7 @@ var ts; var key = getKeyFromCompilationSettings(settings); var bucket = ts.lookUp(buckets, key); if (!bucket && createIfMissing) { - buckets[key] = bucket = ts.createFileMap(getCanonicalFileName); + buckets[key] = bucket = ts.createFileMap(); } return bucket; } @@ -44403,14 +44849,13 @@ var ts; var bucketInfoArray = Object.keys(buckets).filter(function (name) { return name && name.charAt(0) === '_'; }).map(function (name) { var entries = ts.lookUp(buckets, name); var sourceFiles = []; - for (var i in entries) { - var entry = entries.get(i); + entries.forEachValue(function (key, entry) { sourceFiles.push({ - name: i, + name: key, refCount: entry.languageServiceRefCount, references: entry.owners.slice(0) }); - } + }); sourceFiles.sort(function (x, y) { return y.refCount - x.refCount; }); return { bucket: name, @@ -44427,7 +44872,8 @@ var ts; } function acquireOrUpdateDocument(fileName, compilationSettings, scriptSnapshot, version, acquiring) { var bucket = getBucketForCompilationSettings(compilationSettings, /*createIfMissing*/ true); - var entry = bucket.get(fileName); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = bucket.get(path); if (!entry) { ts.Debug.assert(acquiring, "How could we be trying to update a document that the registry doesn't have?"); // Have never seen this file with these settings. Create a new source file for it. @@ -44437,7 +44883,7 @@ var ts; languageServiceRefCount: 0, owners: [] }; - bucket.set(fileName, entry); + bucket.set(path, entry); } else { // We have an entry for this file. However, it may be for a different version of @@ -44460,11 +44906,12 @@ var ts; function releaseDocument(fileName, compilationSettings) { var bucket = getBucketForCompilationSettings(compilationSettings, false); ts.Debug.assert(bucket !== undefined); - var entry = bucket.get(fileName); + var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + var entry = bucket.get(path); entry.languageServiceRefCount--; ts.Debug.assert(entry.languageServiceRefCount >= 0); if (entry.languageServiceRefCount === 0) { - bucket.remove(fileName); + bucket.remove(path); } } return { @@ -44871,7 +45318,7 @@ var ts; case 144 /* Constructor */: return ScriptElementKind.constructorImplementationElement; case 137 /* TypeParameter */: return ScriptElementKind.typeParameterElement; case 247 /* EnumMember */: return ScriptElementKind.variableElement; - case 138 /* Parameter */: return (node.flags & 112 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; + case 138 /* Parameter */: return (node.flags & 56 /* AccessibilityModifier */) ? ScriptElementKind.memberVariableElement : ScriptElementKind.parameterElement; case 221 /* ImportEqualsDeclaration */: case 226 /* ImportSpecifier */: case 223 /* ImportClause */: @@ -44897,13 +45344,14 @@ var ts; return CancellationTokenObject; })(); function createLanguageService(host, documentRegistry) { - if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(); } + if (documentRegistry === void 0) { documentRegistry = createDocumentRegistry(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(), host.getCurrentDirectory()); } var syntaxTreeCache = new SyntaxTreeCache(host); var ruleProvider; var program; var lastProjectVersion; var useCaseSensitivefileNames = false; var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); + var currentDirectory = host.getCurrentDirectory(); // Check if the localized messages json is set, otherwise query the host for it if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { ts.localizedDiagnosticMessages = host.getLocalizedDiagnosticMessages(); @@ -44915,8 +45363,7 @@ var ts; } var getCanonicalFileName = createGetCanonicalFileName(useCaseSensitivefileNames); function getValidSourceFile(fileName) { - fileName = ts.normalizeSlashes(fileName); - var sourceFile = program.getSourceFile(getCanonicalFileName(fileName)); + var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { throw new Error("Could not find file: '" + fileName + "'."); } @@ -44968,7 +45415,7 @@ var ts; getNewLine: function () { return ts.getNewLineOrDefaultFromHost(host); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: function (fileName, data, writeByteOrderMark) { }, - getCurrentDirectory: function () { return host.getCurrentDirectory(); }, + getCurrentDirectory: function () { return currentDirectory; }, fileExists: function (fileName) { // stub missing host functionality ts.Debug.assert(!host.resolveModuleNames); @@ -44988,11 +45435,10 @@ var ts; // not part of the new program. if (program) { var oldSourceFiles = program.getSourceFiles(); - for (var _i = 0; _i < oldSourceFiles.length; _i++) { - var oldSourceFile = oldSourceFiles[_i]; - var fileName = oldSourceFile.fileName; - if (!newProgram.getSourceFile(fileName) || changesInCompilationSettingsAffectSyntax) { - documentRegistry.releaseDocument(fileName, oldSettings); + for (var _i = 0, oldSourceFiles_1 = oldSourceFiles; _i < oldSourceFiles_1.length; _i++) { + var oldSourceFile = oldSourceFiles_1[_i]; + if (!newProgram.getSourceFile(oldSourceFile.fileName) || changesInCompilationSettingsAffectSyntax) { + documentRegistry.releaseDocument(oldSourceFile.fileName, oldSettings); } } } @@ -45048,7 +45494,8 @@ var ts; return documentRegistry.acquireDocument(fileName, newSettings, hostFileInformation.scriptSnapshot, hostFileInformation.version); } function sourceFileUpToDate(sourceFile) { - return sourceFile && sourceFile.version === hostCache.getVersion(sourceFile.fileName); + var path = sourceFile.path || ts.toPath(sourceFile.fileName, currentDirectory, getCanonicalFileName); + return sourceFile && sourceFile.version === hostCache.getVersion(path); } function programUpToDate() { // If we haven't create a program yet, then it is not up-to-date @@ -45061,8 +45508,8 @@ var ts; return false; } // If any file is not up-to-date, then the whole program is not up-to-date - for (var _i = 0; _i < rootFileNames.length; _i++) { - var fileName = rootFileNames[_i]; + for (var _i = 0, rootFileNames_2 = rootFileNames; _i < rootFileNames_2.length; _i++) { + var fileName = rootFileNames_2[_i]; if (!sourceFileUpToDate(program.getSourceFile(fileName))) { return false; } @@ -45237,8 +45684,8 @@ var ts; } function checkModifiers(modifiers) { if (modifiers) { - for (var _i = 0; _i < modifiers.length; _i++) { - var modifier = modifiers[_i]; + for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) { + var modifier = modifiers_1[_i]; switch (modifier.kind) { case 112 /* PublicKeyword */: case 110 /* PrivateKeyword */: @@ -45940,8 +46387,8 @@ var ts; */ function filterNamedImportOrExportCompletionItems(exportsOfModule, namedImportsOrExports) { var exisingImportsOrExports = {}; - for (var _i = 0; _i < namedImportsOrExports.length; _i++) { - var element = namedImportsOrExports[_i]; + for (var _i = 0, namedImportsOrExports_1 = namedImportsOrExports; _i < namedImportsOrExports_1.length; _i++) { + var element = namedImportsOrExports_1[_i]; // If this is the current item we are editing right now, do not filter it out if (element.getStart() <= position && position <= element.getEnd()) { continue; @@ -45965,8 +46412,8 @@ var ts; return contextualMemberSymbols; } var existingMemberNames = {}; - for (var _i = 0; _i < existingMembers.length; _i++) { - var m = existingMembers[_i]; + for (var _i = 0, existingMembers_1 = existingMembers; _i < existingMembers_1.length; _i++) { + var m = existingMembers_1[_i]; // Ignore omitted expressions for missing members if (m.kind !== 245 /* PropertyAssignment */ && m.kind !== 246 /* ShorthandPropertyAssignment */ && @@ -45999,8 +46446,8 @@ var ts; */ function filterJsxAttributes(symbols, attributes) { var seenNames = {}; - for (var _i = 0; _i < attributes.length; _i++) { - var attr = attributes[_i]; + for (var _i = 0, attributes_1 = attributes; _i < attributes_1.length; _i++) { + var attr = attributes_1[_i]; // If this is the current item we are editing right now, do not filter it out if (attr.getStart() <= position && position <= attr.getEnd()) { continue; @@ -46101,8 +46548,8 @@ var ts; var entries = []; if (symbols) { var nameToSymbol = {}; - for (var _i = 0; _i < symbols.length; _i++) { - var symbol = symbols[_i]; + for (var _i = 0, symbols_3 = symbols; _i < symbols_3.length; _i++) { + var symbol = symbols_3[_i]; var entry = createCompletionEntry(symbol, location); if (entry) { var id = ts.escapeIdentifier(entry.name); @@ -46844,8 +47291,8 @@ var ts; } var fileNameToDocumentHighlights = {}; var result = []; - for (var _i = 0; _i < referencedSymbols.length; _i++) { - var referencedSymbol = referencedSymbols[_i]; + for (var _i = 0, referencedSymbols_1 = referencedSymbols; _i < referencedSymbols_1.length; _i++) { + var referencedSymbol = referencedSymbols_1[_i]; for (var _a = 0, _b = referencedSymbol.references; _a < _b.length; _a++) { var referenceEntry = _b[_a]; var fileName_1 = referenceEntry.fileName; @@ -46989,7 +47436,6 @@ var ts; ts.forEachChild(node, aggregate); } } - ; } /** * For lack of a better name, this function takes a throw statement and returns the @@ -47027,7 +47473,6 @@ var ts; ts.forEachChild(node, aggregate); } } - ; } function ownsBreakOrContinueStatement(owner, statement) { var actualOwner = getBreakOrContinueOwner(statement); @@ -47096,7 +47541,7 @@ var ts; case 219 /* ModuleBlock */: case 248 /* SourceFile */: // Container is either a class declaration or the declaration is a classDeclaration - if (modifierFlag & 256 /* Abstract */) { + if (modifierFlag & 128 /* Abstract */) { nodes = declaration.members.concat(declaration); } else { @@ -47111,7 +47556,7 @@ var ts; nodes = container.members; // If we're an accessibility modifier, we're in an instance member and should search // the constructor's parameter list for instance members as well. - if (modifierFlag & 112 /* AccessibilityModifier */) { + if (modifierFlag & 56 /* AccessibilityModifier */) { var constructor = ts.forEach(container.members, function (member) { return member.kind === 144 /* Constructor */ && member; }); @@ -47119,7 +47564,7 @@ var ts; nodes = nodes.concat(constructor.parameters); } } - else if (modifierFlag & 256 /* Abstract */) { + else if (modifierFlag & 128 /* Abstract */) { nodes = nodes.concat(container); } break; @@ -47135,19 +47580,19 @@ var ts; function getFlagFromModifier(modifier) { switch (modifier) { case 112 /* PublicKeyword */: - return 16 /* Public */; + return 8 /* Public */; case 110 /* PrivateKeyword */: - return 32 /* Private */; + return 16 /* Private */; case 111 /* ProtectedKeyword */: - return 64 /* Protected */; + return 32 /* Protected */; case 113 /* StaticKeyword */: - return 128 /* Static */; + return 64 /* Static */; case 82 /* ExportKeyword */: - return 1 /* Export */; + return 2 /* Export */; case 122 /* DeclareKeyword */: - return 2 /* Ambient */; + return 4 /* Ambient */; case 115 /* AbstractKeyword */: - return 256 /* Abstract */; + return 128 /* Abstract */; default: ts.Debug.fail(); } @@ -47346,8 +47791,8 @@ var ts; return undefined; } var result = []; - for (var _i = 0; _i < documentHighlights.length; _i++) { - var entry = documentHighlights[_i]; + for (var _i = 0, documentHighlights_1 = documentHighlights; _i < documentHighlights_1.length; _i++) { + var entry = documentHighlights_1[_i]; for (var _a = 0, _b = entry.highlightSpans; _a < _b.length; _a++) { var highlightSpan = _b[_a]; result.push({ @@ -47365,8 +47810,8 @@ var ts; return undefined; } var referenceEntries = []; - for (var _i = 0; _i < referenceSymbols.length; _i++) { - var referenceSymbol = referenceSymbols[_i]; + for (var _i = 0, referenceSymbols_1 = referenceSymbols; _i < referenceSymbols_1.length; _i++) { + var referenceSymbol = referenceSymbols_1[_i]; ts.addRange(referenceEntries, referenceSymbol.references); } return referenceEntries; @@ -47451,8 +47896,8 @@ var ts; } else { var internedName = getInternedName(symbol, node, declarations); - for (var _i = 0; _i < sourceFiles.length; _i++) { - var sourceFile = sourceFiles[_i]; + for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) { + var sourceFile = sourceFiles_2[_i]; cancellationToken.throwIfCancellationRequested(); var nameTable = getNameTable(sourceFile); if (ts.lookUp(nameTable, internedName)) { @@ -47512,7 +47957,7 @@ var ts; } // If this is private property or method, the scope is the containing class if (symbol.flags & (4 /* Property */ | 8192 /* Method */)) { - var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 32 /* Private */) ? d : undefined; }); + var privateDeclaration = ts.forEach(symbol.getDeclarations(), function (d) { return (d.flags & 16 /* Private */) ? d : undefined; }); if (privateDeclaration) { return ts.getAncestor(privateDeclaration, 214 /* ClassDeclaration */); } @@ -47530,8 +47975,8 @@ var ts; var scope = undefined; var declarations = symbol.getDeclarations(); if (declarations) { - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) { + var declaration = declarations_8[_i]; var container = getContainerNode(declaration); if (!container) { return undefined; @@ -47711,7 +48156,7 @@ var ts; return undefined; } // Whether 'super' occurs in a static context within a class. - var staticFlag = 128 /* Static */; + var staticFlag = 64 /* Static */; switch (searchSpaceNode.kind) { case 141 /* PropertyDeclaration */: case 140 /* PropertySignature */: @@ -47739,7 +48184,7 @@ var ts; // If we have a 'super' container, we must have an enclosing class. // Now make sure the owning class is the same as the search-space // and has the same static qualifier as the original 'super's owner. - if (container && (128 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { + if (container && (64 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { references.push(getReferenceEntryFromNode(node)); } }); @@ -47749,7 +48194,7 @@ var ts; function getReferencesForThisKeyword(thisOrSuperKeyword, sourceFiles) { var searchSpaceNode = ts.getThisContainer(thisOrSuperKeyword, /* includeArrowFunctions */ false); // Whether 'this' occurs in a static context within a class. - var staticFlag = 128 /* Static */; + var staticFlag = 64 /* Static */; switch (searchSpaceNode.kind) { case 143 /* MethodDeclaration */: case 142 /* MethodSignature */: @@ -47827,7 +48272,7 @@ var ts; case 214 /* ClassDeclaration */: // Make sure the container belongs to the same class // and has the appropriate static modifier from the original container. - if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 128 /* Static */) === staticFlag) { + if (container.parent && searchSpaceNode.symbol === container.parent.symbol && (container.flags & 64 /* Static */) === staticFlag) { result.push(getReferenceEntryFromNode(node)); } break; @@ -47998,8 +48443,8 @@ var ts; // To achieve that we will keep iterating until the result stabilizes. // Remember the last meaning lastIterationMeaning = meaning; - for (var _i = 0; _i < declarations.length; _i++) { - var declaration = declarations[_i]; + for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) { + var declaration = declarations_9[_i]; var declarationMeaning = getMeaningFromDeclaration(declaration); if (declarationMeaning & meaning) { meaning |= declarationMeaning; @@ -48115,7 +48560,6 @@ var ts; return 4 /* Namespace */ | 1 /* Value */; } return 1 /* Value */ | 2 /* Type */ | 4 /* Namespace */; - ts.Debug.fail("Unknown declaration type"); } function isTypeReference(node) { if (ts.isRightSideOfQualifiedNameOrPropertyAccess(node)) { @@ -48694,8 +49138,8 @@ var ts; if (matchKind) { var parentElement = token.parent; var childNodes = parentElement.getChildren(sourceFile); - for (var _i = 0; _i < childNodes.length; _i++) { - var current = childNodes[_i]; + for (var _i = 0, childNodes_1 = childNodes; _i < childNodes_1.length; _i++) { + var current = childNodes_1[_i]; if (current.kind === matchKind) { var range1 = ts.createTextSpan(token.getStart(sourceFile), token.getWidth(sourceFile)); var range2 = ts.createTextSpan(current.getStart(sourceFile), current.getWidth(sourceFile)); @@ -49025,8 +49469,8 @@ var ts; // Disallow rename for elements that are defined in the standard TypeScript library. var defaultLibFileName = host.getDefaultLibFileName(host.getCompilationSettings()); if (defaultLibFileName) { - for (var _i = 0; _i < declarations.length; _i++) { - var current = declarations[_i]; + for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) { + var current = declarations_10[_i]; var sourceFile_2 = current.getSourceFile(); var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)); if (sourceFile_2 && getCanonicalFileName(ts.normalizePath(sourceFile_2.fileName)) === getCanonicalFileName(ts.normalizePath(defaultLibFileName))) { @@ -49609,7 +50053,7 @@ var ts; */ function spanInSourceFileAtLocation(sourceFile, position) { // Cannot set breakpoint in dts file - if (sourceFile.flags & 8192 /* DeclarationFile */) { + if (sourceFile.flags & 4096 /* DeclarationFile */) { return undefined; } var tokenAtLocation = ts.getTokenAtPosition(sourceFile, position); @@ -49827,7 +50271,7 @@ var ts; ? variableDeclaration.parent.parent.initializer.declarations : undefined; // Breakpoint is possible in variableDeclaration only if there is initialization - if (variableDeclaration.initializer || (variableDeclaration.flags & 1 /* Export */)) { + if (variableDeclaration.initializer || (variableDeclaration.flags & 2 /* Export */)) { if (declarations && declarations[0] === variableDeclaration) { if (isParentVariableStatement) { // First declaration - include let keyword @@ -49853,7 +50297,7 @@ var ts; function canHaveSpanInParameterDeclaration(parameter) { // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier return !!parameter.initializer || parameter.dotDotDotToken !== undefined || - !!(parameter.flags & 16 /* Public */) || !!(parameter.flags & 32 /* Private */); + !!(parameter.flags & 8 /* Public */) || !!(parameter.flags & 16 /* Private */); } function spanInParameterDeclaration(parameter) { if (canHaveSpanInParameterDeclaration(parameter)) { @@ -49873,7 +50317,7 @@ var ts; } } function canFunctionHaveSpanInWholeDeclaration(functionDeclaration) { - return !!(functionDeclaration.flags & 1 /* Export */) || + return !!(functionDeclaration.flags & 2 /* Export */) || (functionDeclaration.parent.kind === 214 /* ClassDeclaration */ && functionDeclaration.kind !== 144 /* Constructor */); } function spanInFunctionDeclaration(functionDeclaration) { @@ -49967,7 +50411,6 @@ var ts; // fall through. case 244 /* CatchClause */: return spanInNode(ts.lastOrUndefined(node.parent.statements)); - ; case 220 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; @@ -50008,8 +50451,6 @@ var ts; default: return spanInNode(node.parent); } - // Default to parent node - return spanInNode(node.parent); } function spanInColonToken(node) { // Is this : specifying return annotation of the function declaration @@ -50138,7 +50579,6 @@ var ts; // TODO: should this be '==='? if (settingsJson == null || settingsJson == "") { throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings"); - return null; } return JSON.parse(settingsJson); }; diff --git a/scripts/tslint/preferConstRule.ts b/scripts/tslint/preferConstRule.ts new file mode 100644 index 00000000000..29160a9c634 --- /dev/null +++ b/scripts/tslint/preferConstRule.ts @@ -0,0 +1,228 @@ +/// +/// + + +export class Rule extends Lint.Rules.AbstractRule { + public static FAILURE_STRING_FACTORY = (identifier: string) => `Identifier '${identifier}' never appears on the LHS of an assignment - use const instead of let for its declaration.`; + + public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { + return this.applyWithWalker(new PreferConstWalker(sourceFile, this.getOptions())); + } +} + +function isBindingPattern(node: ts.Node): node is ts.BindingPattern { + return !!node && (node.kind === ts.SyntaxKind.ArrayBindingPattern || node.kind === ts.SyntaxKind.ObjectBindingPattern); +} + +function walkUpBindingElementsAndPatterns(node: ts.Node): ts.Node { + while (node && (node.kind === ts.SyntaxKind.BindingElement || isBindingPattern(node))) { + node = node.parent; + } + + return node; +} + +function getCombinedNodeFlags(node: ts.Node): ts.NodeFlags { + node = walkUpBindingElementsAndPatterns(node); + + let flags = node.flags; + if (node.kind === ts.SyntaxKind.VariableDeclaration) { + node = node.parent; + } + + if (node && node.kind === ts.SyntaxKind.VariableDeclarationList) { + flags |= node.flags; + node = node.parent; + } + + if (node && node.kind === ts.SyntaxKind.VariableStatement) { + flags |= node.flags; + } + + return flags; +} + +function isLet(node: ts.Node) { + return !!(getCombinedNodeFlags(node) & ts.NodeFlags.Let); +} + +function isExported(node: ts.Node) { + return !!(getCombinedNodeFlags(node) & ts.NodeFlags.Export); +} + +function isAssignmentOperator(token: ts.SyntaxKind): boolean { + return token >= ts.SyntaxKind.FirstAssignment && token <= ts.SyntaxKind.LastAssignment; +} + +function isBindingLiteralExpression(node: ts.Node): node is (ts.ArrayLiteralExpression | ts.ObjectLiteralExpression) { + return (!!node) && (node.kind === ts.SyntaxKind.ObjectLiteralExpression || node.kind === ts.SyntaxKind.ArrayLiteralExpression); +} + +interface DeclarationUsages { + declaration: ts.VariableDeclaration; + usages: number; +} + +class PreferConstWalker extends Lint.RuleWalker { + private inScopeLetDeclarations: ts.Map[] = []; + private errors: Lint.RuleFailure[] = []; + private markAssignment(identifier: ts.Identifier) { + const name = identifier.text; + for (let i = this.inScopeLetDeclarations.length - 1; i >= 0; i--) { + const declarations = this.inScopeLetDeclarations[i]; + if (declarations[name]) { + declarations[name].usages++; + break; + } + } + } + + visitSourceFile(node: ts.SourceFile) { + super.visitSourceFile(node); + // Sort errors by position because tslint doesn't + this.errors.sort((a, b) => a.getStartPosition().getPosition() - b.getStartPosition().getPosition()).forEach(e => this.addFailure(e)); + } + + visitBinaryExpression(node: ts.BinaryExpression) { + if (isAssignmentOperator(node.operatorToken.kind)) { + this.visitLHSExpressions(node.left); + } + super.visitBinaryExpression(node); + } + + private visitLHSExpressions(node: ts.Expression) { + while (node.kind === ts.SyntaxKind.ParenthesizedExpression) { + node = (node as ts.ParenthesizedExpression).expression; + } + if (node.kind === ts.SyntaxKind.Identifier) { + this.markAssignment(node as ts.Identifier); + } + else if (isBindingLiteralExpression(node)) { + this.visitBindingLiteralExpression(node as (ts.ArrayLiteralExpression | ts.ObjectLiteralExpression)); + } + } + + private visitBindingLiteralExpression(node: ts.ArrayLiteralExpression | ts.ObjectLiteralExpression) { + if (node.kind === ts.SyntaxKind.ObjectLiteralExpression) { + const pattern = node as ts.ObjectLiteralExpression; + for (const element of pattern.properties) { + if (element.name.kind === ts.SyntaxKind.Identifier) { + this.markAssignment(element.name as ts.Identifier) + } + else if (isBindingPattern(element.name)) { + this.visitBindingPatternIdentifiers(element.name as ts.BindingPattern); + } + } + } + else if (node.kind === ts.SyntaxKind.ArrayLiteralExpression) { + const pattern = node as ts.ArrayLiteralExpression; + for (const element of pattern.elements) { + this.visitLHSExpressions(element); + } + } + } + + private visitBindingPatternIdentifiers(pattern: ts.BindingPattern) { + for (const element of pattern.elements) { + if (element.name.kind === ts.SyntaxKind.Identifier) { + this.markAssignment(element.name as ts.Identifier); + } + else { + this.visitBindingPatternIdentifiers(element.name as ts.BindingPattern); + } + } + } + + visitPrefixUnaryExpression(node: ts.PrefixUnaryExpression) { + this.visitAnyUnaryExpression(node); + super.visitPrefixUnaryExpression(node); + } + + visitPostfixUnaryExpression(node: ts.PostfixUnaryExpression) { + this.visitAnyUnaryExpression(node); + super.visitPostfixUnaryExpression(node); + } + + private visitAnyUnaryExpression(node: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression) { + if (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken) { + this.visitLHSExpressions(node.operand); + } + } + + visitModuleDeclaration(node: ts.ModuleDeclaration) { + if (node.body.kind === ts.SyntaxKind.ModuleBlock) { + // For some reason module blocks are left out of the visit block traversal + this.visitBlock(node.body as ts.ModuleBlock); + } + super.visitModuleDeclaration(node); + } + + visitForOfStatement(node: ts.ForOfStatement) { + this.visitAnyForStatement(node); + super.visitForOfStatement(node); + this.popDeclarations(); + } + + visitForInStatement(node: ts.ForInStatement) { + this.visitAnyForStatement(node); + super.visitForInStatement(node); + this.popDeclarations(); + } + + private visitAnyForStatement(node: ts.ForOfStatement | ts.ForInStatement) { + const names: ts.Map = {}; + if (isLet(node.initializer)) { + if (node.initializer.kind === ts.SyntaxKind.VariableDeclarationList) { + this.collectLetIdentifiers(node.initializer as ts.VariableDeclarationList, names); + } + } + this.inScopeLetDeclarations.push(names); + } + + private popDeclarations() { + const completed = this.inScopeLetDeclarations.pop(); + for (const name in completed) { + if (Object.hasOwnProperty.call(completed, name)) { + const element = completed[name]; + if (element.usages === 0) { + this.errors.push(this.createFailure(element.declaration.getStart(this.getSourceFile()), element.declaration.getWidth(this.getSourceFile()), Rule.FAILURE_STRING_FACTORY(name))); + } + } + } + } + + visitBlock(node: ts.Block) { + const names: ts.Map = {}; + for (const statement of node.statements) { + if (statement.kind === ts.SyntaxKind.VariableStatement) { + this.collectLetIdentifiers((statement as ts.VariableStatement).declarationList, names); + } + } + this.inScopeLetDeclarations.push(names); + super.visitBlock(node); + this.popDeclarations(); + } + + private collectLetIdentifiers(list: ts.VariableDeclarationList, ret: ts.Map) { + for (const node of list.declarations) { + if (isLet(node) && !isExported(node)) { + this.collectNameIdentifiers(node, node.name, ret); + } + } + } + + private collectNameIdentifiers(value: ts.VariableDeclaration, node: ts.Identifier | ts.BindingPattern, table: ts.Map) { + if (node.kind === ts.SyntaxKind.Identifier) { + table[(node as ts.Identifier).text] = {declaration: value, usages: 0}; + } + else { + this.collectBindingPatternIdentifiers(value, node as ts.BindingPattern, table); + } + } + + private collectBindingPatternIdentifiers(value: ts.VariableDeclaration, pattern: ts.BindingPattern, table: ts.Map) { + for (const element of pattern.elements) { + this.collectNameIdentifiers(value, element.name, table); + } + } +} diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index c12a9afad62..6edba58cb11 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -10,6 +10,21 @@ namespace ts { ConstEnumOnly = 2 } + const enum Reachability { + Unintialized = 1 << 0, + Reachable = 1 << 1, + Unreachable = 1 << 2, + ReportedUnreachable = 1 << 3 + } + + function or(state1: Reachability, state2: Reachability): Reachability { + return (state1 | state2) & Reachability.Reachable + ? Reachability.Reachable + : (state1 & state2) & Reachability.ReportedUnreachable + ? Reachability.ReportedUnreachable + : Reachability.Unreachable; + } + export function getModuleInstanceState(node: Node): ModuleInstanceState { // A module is uninstantiated if it contains only // 1. interface declarations, type alias declarations @@ -77,35 +92,64 @@ namespace ts { IsContainerWithLocals = IsContainer | HasLocals } - export function bindSourceFile(file: SourceFile) { - let start = new Date().getTime(); - bindSourceFileWorker(file); + const binder = createBinder(); + + export function bindSourceFile(file: SourceFile, options: CompilerOptions) { + const start = new Date().getTime(); + binder(file, options); bindTime += new Date().getTime() - start; } - function bindSourceFileWorker(file: SourceFile) { + function createBinder(): (file: SourceFile, options: CompilerOptions) => void { + let file: SourceFile; + let options: CompilerOptions; let parent: Node; let container: Node; let blockScopeContainer: Node; let lastContainer: Node; let seenThisKeyword: boolean; + // state used by reachability checks + let hasExplicitReturn: boolean; + let currentReachabilityState: Reachability; + let labelStack: Reachability[]; + let labelIndexMap: Map; + let implicitLabels: number[]; + // If this file is an external module, then it is automatically in strict-mode according to // ES6. If it is not an external module, then we'll determine if it is in strict mode or // not depending on if we see "use strict" in certain places (or if we hit a class/namespace). - let inStrictMode = !!file.externalModuleIndicator; + let inStrictMode: boolean; let symbolCount = 0; - let Symbol = objectAllocator.getSymbolConstructor(); - let classifiableNames: Map = {}; + let Symbol: { new (flags: SymbolFlags, name: string): Symbol }; + let classifiableNames: Map; - if (!file.locals) { - bind(file); - file.symbolCount = symbolCount; - file.classifiableNames = classifiableNames; + function bindSourceFile(f: SourceFile, opts: CompilerOptions) { + file = f; + options = opts; + inStrictMode = !!file.externalModuleIndicator; + classifiableNames = {}; + Symbol = objectAllocator.getSymbolConstructor(); + + if (!file.locals) { + bind(file); + file.symbolCount = symbolCount; + file.classifiableNames = classifiableNames; + } + + parent = undefined; + container = undefined; + blockScopeContainer = undefined; + lastContainer = undefined; + seenThisKeyword = false; + hasExplicitReturn = false; + labelStack = undefined; + labelIndexMap = undefined; + implicitLabels = undefined; } - return; + return bindSourceFile; function createSymbol(flags: SymbolFlags, name: string): Symbol { symbolCount++; @@ -143,7 +187,7 @@ namespace ts { return `"${(node.name).text}"`; } if (node.name.kind === SyntaxKind.ComputedPropertyName) { - let nameExpression = (node.name).expression; + const nameExpression = (node.name).expression; Debug.assert(isWellKnownSymbolSyntactically(nameExpression)); return getPropertyNameForKnownSymbolName((nameExpression).name.text); } @@ -185,9 +229,9 @@ namespace ts { function declareSymbol(symbolTable: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol { Debug.assert(!hasDynamicName(node)); - let isDefaultExport = node.flags & NodeFlags.Default; + const isDefaultExport = node.flags & NodeFlags.Default; // The exported symbol for an export default function/class node is always named "default" - let name = isDefaultExport && parent ? "default" : getDeclarationName(node); + const name = isDefaultExport && parent ? "default" : getDeclarationName(node); let symbol: Symbol; if (name !== undefined) { @@ -254,7 +298,7 @@ namespace ts { } function declareModuleMember(node: Declaration, symbolFlags: SymbolFlags, symbolExcludes: SymbolFlags): Symbol { - let hasExportModifier = getCombinedNodeFlags(node) & NodeFlags.Export; + const hasExportModifier = getCombinedNodeFlags(node) & NodeFlags.Export; if (symbolFlags & SymbolFlags.Alias) { if (node.kind === SyntaxKind.ExportSpecifier || (node.kind === SyntaxKind.ImportEqualsDeclaration && hasExportModifier)) { return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); @@ -276,11 +320,11 @@ namespace ts { // but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way // when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope. if (hasExportModifier || container.flags & NodeFlags.ExportContext) { - let exportKind = + const exportKind = (symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) | (symbolFlags & SymbolFlags.Type ? SymbolFlags.ExportType : 0) | (symbolFlags & SymbolFlags.Namespace ? SymbolFlags.ExportNamespace : 0); - let local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); + const local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes); local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); node.localSymbol = local; return local; @@ -298,9 +342,9 @@ namespace ts { // Before we recurse into a node's chilren, we first save the existing parent, container // and block-container. Then after we pop out of processing the children, we restore // these saved values. - let saveParent = parent; - let saveContainer = container; - let savedBlockScopeContainer = blockScopeContainer; + const saveParent = parent; + const saveContainer = container; + const savedBlockScopeContainer = blockScopeContainer; // This node will now be set as the parent of all of its children as we recurse into them. parent = node; @@ -322,7 +366,7 @@ namespace ts { // reusing a node from a previous compilation, that node may have had 'locals' created // for it. We must clear this so we don't accidently move any stale data forward from // a previous compilation. - let containerFlags = getContainerFlags(node); + const containerFlags = getContainerFlags(node); if (containerFlags & ContainerFlags.IsContainer) { container = blockScopeContainer = node; @@ -338,13 +382,56 @@ namespace ts { blockScopeContainer.locals = undefined; } - if (node.kind === SyntaxKind.InterfaceDeclaration) { + let savedReachabilityState: Reachability; + let savedLabelStack: Reachability[]; + let savedLabels: Map; + let savedImplicitLabels: number[]; + let savedHasExplicitReturn: boolean; + + const kind = node.kind; + let flags = node.flags; + + // reset all reachability check related flags on node (for incremental scenarios) + flags &= ~NodeFlags.ReachabilityCheckFlags; + + if (kind === SyntaxKind.InterfaceDeclaration) { seenThisKeyword = false; - forEachChild(node, bind); - node.flags = seenThisKeyword ? node.flags | NodeFlags.ContainsThis : node.flags & ~NodeFlags.ContainsThis; } - else { - forEachChild(node, bind); + + const saveState = kind === SyntaxKind.SourceFile || kind === SyntaxKind.ModuleBlock || isFunctionLikeKind(kind); + if (saveState) { + savedReachabilityState = currentReachabilityState; + savedLabelStack = labelStack; + savedLabels = labelIndexMap; + savedImplicitLabels = implicitLabels; + savedHasExplicitReturn = hasExplicitReturn; + + currentReachabilityState = Reachability.Reachable; + hasExplicitReturn = false; + labelStack = labelIndexMap = implicitLabels = undefined; + } + + bindReachableStatement(node); + + if (currentReachabilityState === Reachability.Reachable && isFunctionLikeKind(kind) && nodeIsPresent((node).body)) { + flags |= NodeFlags.HasImplicitReturn; + if (hasExplicitReturn) { + flags |= NodeFlags.HasExplicitReturn; + } + } + + if (kind === SyntaxKind.InterfaceDeclaration) { + flags = seenThisKeyword ? flags | NodeFlags.ContainsThis : flags & ~NodeFlags.ContainsThis; + } + + node.flags = flags; + + if (saveState) { + hasExplicitReturn = savedHasExplicitReturn; + currentReachabilityState = savedReachabilityState; + labelStack = savedLabelStack; + labelIndexMap = savedLabels; + implicitLabels = savedImplicitLabels; } container = saveContainer; @@ -352,6 +439,220 @@ namespace ts { blockScopeContainer = savedBlockScopeContainer; } + /** + * Returns true if node and its subnodes were successfully traversed. + * Returning false means that node was not examined and caller needs to dive into the node himself. + */ + function bindReachableStatement(node: Node): void { + if (checkUnreachable(node)) { + forEachChild(node, bind); + return; + } + + switch (node.kind) { + case SyntaxKind.WhileStatement: + bindWhileStatement(node); + break; + case SyntaxKind.DoStatement: + bindDoStatement(node); + break; + case SyntaxKind.ForStatement: + bindForStatement(node); + break; + case SyntaxKind.ForInStatement: + case SyntaxKind.ForOfStatement: + bindForInOrForOfStatement(node); + break; + case SyntaxKind.IfStatement: + bindIfStatement(node); + break; + case SyntaxKind.ReturnStatement: + case SyntaxKind.ThrowStatement: + bindReturnOrThrow(node); + break; + case SyntaxKind.BreakStatement: + case SyntaxKind.ContinueStatement: + bindBreakOrContinueStatement(node); + break; + case SyntaxKind.TryStatement: + bindTryStatement(node); + break; + case SyntaxKind.SwitchStatement: + bindSwitchStatement(node); + break; + case SyntaxKind.CaseBlock: + bindCaseBlock(node); + break; + case SyntaxKind.LabeledStatement: + bindLabeledStatement(node); + break; + default: + forEachChild(node, bind); + break; + } + } + + function bindWhileStatement(n: WhileStatement): void { + const preWhileState = + n.expression.kind === SyntaxKind.FalseKeyword ? Reachability.Unreachable : currentReachabilityState; + const postWhileState = + n.expression.kind === SyntaxKind.TrueKeyword ? Reachability.Unreachable : currentReachabilityState; + + // bind expressions (don't affect reachability) + bind(n.expression); + + currentReachabilityState = preWhileState; + const postWhileLabel = pushImplicitLabel(); + bind(n.statement); + popImplicitLabel(postWhileLabel, postWhileState); + } + + function bindDoStatement(n: DoStatement): void { + const preDoState = currentReachabilityState; + + const postDoLabel = pushImplicitLabel(); + bind(n.statement); + const postDoState = n.expression.kind === SyntaxKind.TrueKeyword ? Reachability.Unreachable : preDoState; + popImplicitLabel(postDoLabel, postDoState); + + // bind expressions (don't affect reachability) + bind(n.expression); + } + + function bindForStatement(n: ForStatement): void { + const preForState = currentReachabilityState; + const postForLabel = pushImplicitLabel(); + + // bind expressions (don't affect reachability) + bind(n.initializer); + bind(n.condition); + bind(n.incrementor); + + bind(n.statement); + + // for statement is considered infinite when it condition is either omitted or is true keyword + // - for(..;;..) + // - for(..;true;..) + const isInfiniteLoop = (!n.condition || n.condition.kind === SyntaxKind.TrueKeyword); + const postForState = isInfiniteLoop ? Reachability.Unreachable : preForState; + popImplicitLabel(postForLabel, postForState); + } + + function bindForInOrForOfStatement(n: ForInStatement | ForOfStatement): void { + const preStatementState = currentReachabilityState; + const postStatementLabel = pushImplicitLabel(); + + // bind expressions (don't affect reachability) + bind(n.initializer); + bind(n.expression); + + bind(n.statement); + popImplicitLabel(postStatementLabel, preStatementState); + } + + function bindIfStatement(n: IfStatement): void { + // denotes reachability state when entering 'thenStatement' part of the if statement: + // i.e. if condition is false then thenStatement is unreachable + const ifTrueState = n.expression.kind === SyntaxKind.FalseKeyword ? Reachability.Unreachable : currentReachabilityState; + // denotes reachability state when entering 'elseStatement': + // i.e. if condition is true then elseStatement is unreachable + const ifFalseState = n.expression.kind === SyntaxKind.TrueKeyword ? Reachability.Unreachable : currentReachabilityState; + + currentReachabilityState = ifTrueState; + + // bind expression (don't affect reachability) + bind(n.expression); + + bind(n.thenStatement); + if (n.elseStatement) { + const preElseState = currentReachabilityState; + currentReachabilityState = ifFalseState; + bind(n.elseStatement); + currentReachabilityState = or(currentReachabilityState, preElseState); + } + else { + currentReachabilityState = or(currentReachabilityState, ifFalseState); + } + } + + function bindReturnOrThrow(n: ReturnStatement | ThrowStatement): void { + // bind expression (don't affect reachability) + bind(n.expression); + if (n.kind === SyntaxKind.ReturnStatement) { + hasExplicitReturn = true; + } + currentReachabilityState = Reachability.Unreachable; + } + + function bindBreakOrContinueStatement(n: BreakOrContinueStatement): void { + // call bind on label (don't affect reachability) + bind(n.label); + // for continue case touch label so it will be marked a used + const isValidJump = jumpToLabel(n.label, n.kind === SyntaxKind.BreakStatement ? currentReachabilityState : Reachability.Unreachable); + if (isValidJump) { + currentReachabilityState = Reachability.Unreachable; + } + } + + function bindTryStatement(n: TryStatement): void { + // catch\finally blocks has the same reachability as try block + const preTryState = currentReachabilityState; + bind(n.tryBlock); + const postTryState = currentReachabilityState; + + currentReachabilityState = preTryState; + bind(n.catchClause); + const postCatchState = currentReachabilityState; + + currentReachabilityState = preTryState; + bind(n.finallyBlock); + + // post catch/finally state is reachable if + // - post try state is reachable - control flow can fall out of try block + // - post catch state is reachable - control flow can fall out of catch block + currentReachabilityState = or(postTryState, postCatchState); + } + + function bindSwitchStatement(n: SwitchStatement): void { + const preSwitchState = currentReachabilityState; + const postSwitchLabel = pushImplicitLabel(); + + // bind expression (don't affect reachability) + bind(n.expression); + + bind(n.caseBlock); + + const hasDefault = forEach(n.caseBlock.clauses, c => c.kind === SyntaxKind.DefaultClause); + + // post switch state is unreachable if switch is exaustive (has a default case ) and does not have fallthrough from the last case + const postSwitchState = hasDefault && currentReachabilityState !== Reachability.Reachable ? Reachability.Unreachable : preSwitchState; + + popImplicitLabel(postSwitchLabel, postSwitchState); + } + + function bindCaseBlock(n: CaseBlock): void { + const startState = currentReachabilityState; + + for (const clause of n.clauses) { + currentReachabilityState = startState; + bind(clause); + if (clause.statements.length && currentReachabilityState === Reachability.Reachable && options.noFallthroughCasesInSwitch) { + errorOnFirstToken(clause, Diagnostics.Fallthrough_case_in_switch); + } + } + } + + function bindLabeledStatement(n: LabeledStatement): void { + // call bind on label (don't affect reachability) + bind(n.label); + + const ok = pushNamedLabel(n.label); + bind(n.statement); + if (ok) { + popNamedLabel(n.label, currentReachabilityState); + } + } + function getContainerFlags(node: Node): ContainerFlags { switch (node.kind) { case SyntaxKind.ClassExpression: @@ -488,21 +789,10 @@ namespace ts { : declareSymbol(file.locals, undefined, node, symbolFlags, symbolExcludes); } - function isAmbientContext(node: Node): boolean { - while (node) { - if (node.flags & NodeFlags.Ambient) { - return true; - } - - node = node.parent; - } - return false; - } - function hasExportDeclarations(node: ModuleDeclaration | SourceFile): boolean { - let body = node.kind === SyntaxKind.SourceFile ? node : (node).body; + const body = node.kind === SyntaxKind.SourceFile ? node : (node).body; if (body.kind === SyntaxKind.SourceFile || body.kind === SyntaxKind.ModuleBlock) { - for (let stat of (body).statements) { + for (const stat of (body).statements) { if (stat.kind === SyntaxKind.ExportDeclaration || stat.kind === SyntaxKind.ExportAssignment) { return true; } @@ -514,7 +804,7 @@ namespace ts { function setExportContextFlag(node: ModuleDeclaration | SourceFile) { // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular // declarations with export modifiers) is an export context in which declarations are implicitly exported. - if (isAmbientContext(node) && !hasExportDeclarations(node)) { + if (isInAmbientContext(node) && !hasExportDeclarations(node)) { node.flags |= NodeFlags.ExportContext; } else { @@ -528,7 +818,7 @@ namespace ts { declareSymbolAndAddToSymbolTable(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes); } else { - let state = getModuleInstanceState(node); + const state = getModuleInstanceState(node); if (state === ModuleInstanceState.NonInstantiated) { declareSymbolAndAddToSymbolTable(node, SymbolFlags.NamespaceModule, SymbolFlags.NamespaceModuleExcludes); } @@ -540,7 +830,7 @@ namespace ts { node.symbol.constEnumOnlyModule = false; } else { - let currentModuleIsConstEnumOnly = state === ModuleInstanceState.ConstEnumOnly; + const currentModuleIsConstEnumOnly = state === ModuleInstanceState.ConstEnumOnly; if (node.symbol.constEnumOnlyModule === undefined) { // non-merged case - use the current state node.symbol.constEnumOnlyModule = currentModuleIsConstEnumOnly; @@ -561,10 +851,10 @@ namespace ts { // We do that by making an anonymous type literal symbol, and then setting the function // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable // from an actual type literal symbol you would have gotten had you used the long form. - let symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node)); + const symbol = createSymbol(SymbolFlags.Signature, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, SymbolFlags.Signature); - let typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, "__type"); + const typeLiteralSymbol = createSymbol(SymbolFlags.TypeLiteral, "__type"); addDeclarationToSymbol(typeLiteralSymbol, node, SymbolFlags.TypeLiteral); typeLiteralSymbol.members = { [symbol.name]: symbol }; } @@ -576,14 +866,14 @@ namespace ts { } if (inStrictMode) { - let seen: Map = {}; + const seen: Map = {}; - for (let prop of node.properties) { + for (const prop of node.properties) { if (prop.name.kind !== SyntaxKind.Identifier) { continue; } - let identifier = prop.name; + const identifier = prop.name; // ECMA-262 11.1.5 Object Initialiser // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true @@ -593,18 +883,18 @@ namespace ts { // c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true. // d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields - let currentKind = prop.kind === SyntaxKind.PropertyAssignment || prop.kind === SyntaxKind.ShorthandPropertyAssignment || prop.kind === SyntaxKind.MethodDeclaration + const currentKind = prop.kind === SyntaxKind.PropertyAssignment || prop.kind === SyntaxKind.ShorthandPropertyAssignment || prop.kind === SyntaxKind.MethodDeclaration ? ElementKind.Property : ElementKind.Accessor; - let existingKind = seen[identifier.text]; + const existingKind = seen[identifier.text]; if (!existingKind) { seen[identifier.text] = currentKind; continue; } if (currentKind === ElementKind.Property && existingKind === ElementKind.Property) { - let span = getErrorSpanForNode(file, identifier); + const span = getErrorSpanForNode(file, identifier); file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode)); } @@ -615,7 +905,7 @@ namespace ts { } function bindAnonymousDeclaration(node: Declaration, symbolFlags: SymbolFlags, name: string) { - let symbol = createSymbol(symbolFlags, name); + const symbol = createSymbol(symbolFlags, name); addDeclarationToSymbol(symbol, node, symbolFlags); } @@ -694,7 +984,7 @@ namespace ts { if (inStrictMode && node.expression.kind === SyntaxKind.Identifier) { // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its // UnaryExpression is a direct reference to a variable, function argument, or function name - let span = getErrorSpanForNode(file, node.expression); + const span = getErrorSpanForNode(file, node.expression); file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode)); } } @@ -706,11 +996,11 @@ namespace ts { function checkStrictModeEvalOrArguments(contextNode: Node, name: Node) { if (name && name.kind === SyntaxKind.Identifier) { - let identifier = name; + const identifier = name; if (isEvalOrArgumentsIdentifier(identifier)) { // We check first if the name is inside class declaration or class expression; if so give explicit message // otherwise report generic error message. - let span = getErrorSpanForNode(file, name); + const span = getErrorSpanForNode(file, name); file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), identifier.text)); } @@ -766,12 +1056,12 @@ namespace ts { function checkStrictModeWithStatement(node: WithStatement) { // Grammar checking for withStatement if (inStrictMode) { - grammarErrorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_strict_mode); + errorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_strict_mode); } } - function grammarErrorOnFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any) { - let span = getSpanOfTokenAtPosition(file, node.pos); + function errorOnFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any) { + const span = getSpanOfTokenAtPosition(file, node.pos); file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2)); } @@ -780,9 +1070,13 @@ namespace ts { } function bind(node: Node) { + if (!node) { + return; + } + node.parent = parent; - let savedInStrictMode = inStrictMode; + const savedInStrictMode = inStrictMode; if (!savedInStrictMode) { updateStrictMode(node); } @@ -828,7 +1122,7 @@ namespace ts { } function updateStrictModeStatementList(statements: NodeArray) { - for (let statement of statements) { + for (const statement of statements) { if (!isPrologueDirective(statement)) { return; } @@ -842,7 +1136,7 @@ namespace ts { /// Should be called only on prologue directives (isPrologueDirective(node) should be true) function isUseStrictPrologueDirective(node: ExpressionStatement): boolean { - let nodeText = getTextOfNodeFromSourceText(file.text, node.expression); + const nodeText = getTextOfNodeFromSourceText(file.text, node.expression); // Note: the node text must be exactly "use strict" or 'use strict'. It is not ok for the // string to contain unicode escapes (as per ES5). @@ -917,7 +1211,7 @@ namespace ts { case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: checkStrictModeFunctionName(node); - let bindingName = (node).name ? (node).name.text : "__function"; + const bindingName = (node).name ? (node).name.text : "__function"; return bindAnonymousDeclaration(node, SymbolFlags.Function, bindingName); case SyntaxKind.ClassExpression: case SyntaxKind.ClassDeclaration: @@ -990,7 +1284,7 @@ namespace ts { bindBlockScopedDeclaration(node, SymbolFlags.Class, SymbolFlags.ClassExcludes); } else { - let bindingName = node.name ? node.name.text : "__class"; + const bindingName = node.name ? node.name.text : "__class"; bindAnonymousDeclaration(node, SymbolFlags.Class, bindingName); // Add name of class expression into the map for semantic classifier if (node.name) { @@ -998,7 +1292,7 @@ namespace ts { } } - let symbol = node.symbol; + const symbol = node.symbol; // TypeScript 1.0 spec (April 2014): 8.4 // Every class automatically contains a static property member named 'prototype', the @@ -1009,7 +1303,7 @@ namespace ts { // Note: we check for this here because this class may be merging into a module. The // module might have an exported variable called 'prototype'. We can't allow that as // that would clash with the built-in 'prototype' for the class. - let prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype"); + const prototypeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Prototype, "prototype"); if (hasProperty(symbol.exports, prototypeSymbol.name)) { if (node.name) { node.name.parent = node; @@ -1074,7 +1368,7 @@ namespace ts { node.parent.kind === SyntaxKind.Constructor && isClassLike(node.parent.parent)) { - let classDeclaration = node.parent.parent; + const classDeclaration = node.parent.parent; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes); } } @@ -1084,5 +1378,135 @@ namespace ts { ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); } + + // reachability checks + + function pushNamedLabel(name: Identifier): boolean { + initializeReachabilityStateIfNecessary(); + + if (hasProperty(labelIndexMap, name.text)) { + return false; + } + labelIndexMap[name.text] = labelStack.push(Reachability.Unintialized) - 1; + return true; + } + + function pushImplicitLabel(): number { + initializeReachabilityStateIfNecessary(); + + const index = labelStack.push(Reachability.Unintialized) - 1; + implicitLabels.push(index); + return index; + } + + function popNamedLabel(label: Identifier, outerState: Reachability): void { + const index = labelIndexMap[label.text]; + Debug.assert(index !== undefined); + Debug.assert(labelStack.length == index + 1); + + labelIndexMap[label.text] = undefined; + + setCurrentStateAtLabel(labelStack.pop(), outerState, label); + } + + function popImplicitLabel(implicitLabelIndex: number, outerState: Reachability): void { + if (labelStack.length !== implicitLabelIndex + 1) { + Debug.assert(false, `Label stack: ${labelStack.length}, index:${implicitLabelIndex}`); + } + + const i = implicitLabels.pop(); + + if (implicitLabelIndex !== i) { + Debug.assert(false, `i: ${i}, index: ${implicitLabelIndex}`); + } + + setCurrentStateAtLabel(labelStack.pop(), outerState, /*name*/ undefined); + } + + function setCurrentStateAtLabel(innerMergedState: Reachability, outerState: Reachability, label: Identifier): void { + if (innerMergedState === Reachability.Unintialized) { + if (label && !options.allowUnusedLabels) { + file.bindDiagnostics.push(createDiagnosticForNode(label, Diagnostics.Unused_label)); + } + currentReachabilityState = outerState; + } + else { + currentReachabilityState = or(innerMergedState, outerState); + } + } + + function jumpToLabel(label: Identifier, outerState: Reachability): boolean { + initializeReachabilityStateIfNecessary(); + + const index = label ? labelIndexMap[label.text] : lastOrUndefined(implicitLabels); + if (index === undefined) { + // reference to unknown label or + // break/continue used outside of loops + return false; + } + const stateAtLabel = labelStack[index]; + labelStack[index] = stateAtLabel === Reachability.Unintialized ? outerState : or(stateAtLabel, outerState); + return true; + } + + function checkUnreachable(node: Node): boolean { + switch (currentReachabilityState) { + case Reachability.Unreachable: + const reportError = + // report error on all statements except empty ones + (isStatement(node) && node.kind !== SyntaxKind.EmptyStatement) || + // report error on class declarations + node.kind === SyntaxKind.ClassDeclaration || + // report error on instantiated modules or const-enums only modules if preserveConstEnums is set + (node.kind === SyntaxKind.ModuleDeclaration && shouldReportErrorOnModuleDeclaration(node)) || + // report error on regular enums and const enums if preserveConstEnums is set + (node.kind === SyntaxKind.EnumDeclaration && (!isConstEnumDeclaration(node) || options.preserveConstEnums)); + + if (reportError) { + currentReachabilityState = Reachability.ReportedUnreachable; + + // unreachable code is reported if + // - user has explicitly asked about it AND + // - statement is in not ambient context (statements in ambient context is already an error + // so we should not report extras) AND + // - node is not variable statement OR + // - node is block scoped variable statement OR + // - node is not block scoped variable statement and at least one variable declaration has initializer + // Rationale: we don't want to report errors on non-initialized var's since they are hoisted + // On the other side we do want to report errors on non-initialized 'lets' because of TDZ + const reportUnreachableCode = + !options.allowUnreachableCode && + !isInAmbientContext(node) && + ( + node.kind !== SyntaxKind.VariableStatement || + getCombinedNodeFlags((node).declarationList) & NodeFlags.BlockScoped || + forEach((node).declarationList.declarations, d => d.initializer) + ); + + if (reportUnreachableCode) { + errorOnFirstToken(node, Diagnostics.Unreachable_code_detected); + } + } + case Reachability.ReportedUnreachable: + return true; + default: + return false; + } + + function shouldReportErrorOnModuleDeclaration(node: ModuleDeclaration): boolean { + const instanceState = getModuleInstanceState(node); + return instanceState === ModuleInstanceState.Instantiated || (instanceState === ModuleInstanceState.ConstEnumOnly && options.preserveConstEnums); + } + } + + function initializeReachabilityStateIfNecessary(): void { + if (labelIndexMap) { + return; + } + currentReachabilityState = Reachability.Reachable; + labelIndexMap = {}; + labelStack = []; + implicitLabels = []; + } } } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 2e8cd5f7eb2..fe0111a66b9 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -33,26 +33,26 @@ namespace ts { // they no longer need the information (for example, if the user started editing again). let cancellationToken: CancellationToken; - let Symbol = objectAllocator.getSymbolConstructor(); - let Type = objectAllocator.getTypeConstructor(); - let Signature = objectAllocator.getSignatureConstructor(); + const Symbol = objectAllocator.getSymbolConstructor(); + const Type = objectAllocator.getTypeConstructor(); + const Signature = objectAllocator.getSignatureConstructor(); let typeCount = 0; let symbolCount = 0; - let emptyArray: any[] = []; - let emptySymbols: SymbolTable = {}; + const emptyArray: any[] = []; + const emptySymbols: SymbolTable = {}; - let compilerOptions = host.getCompilerOptions(); - let languageVersion = compilerOptions.target || ScriptTarget.ES3; - let modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None; + const compilerOptions = host.getCompilerOptions(); + const languageVersion = compilerOptions.target || ScriptTarget.ES3; + const modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None; - let emitResolver = createResolver(); + const emitResolver = createResolver(); - let undefinedSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "undefined"); - let argumentsSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "arguments"); + const undefinedSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "undefined"); + const argumentsSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "arguments"); - let checker: TypeChecker = { + const checker: TypeChecker = { getNodeCount: () => sum(host.getSourceFiles(), "nodeCount"), getIdentifierCount: () => sum(host.getSourceFiles(), "identifierCount"), getSymbolCount: () => sum(host.getSourceFiles(), "symbolCount") + symbolCount, @@ -97,35 +97,35 @@ namespace ts { isOptionalParameter }; - let unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown"); - let resolvingSymbol = createSymbol(SymbolFlags.Transient, "__resolving__"); + const unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown"); + const resolvingSymbol = createSymbol(SymbolFlags.Transient, "__resolving__"); - let anyType = createIntrinsicType(TypeFlags.Any, "any"); - let stringType = createIntrinsicType(TypeFlags.String, "string"); - let numberType = createIntrinsicType(TypeFlags.Number, "number"); - let booleanType = createIntrinsicType(TypeFlags.Boolean, "boolean"); - let esSymbolType = createIntrinsicType(TypeFlags.ESSymbol, "symbol"); - let voidType = createIntrinsicType(TypeFlags.Void, "void"); - let undefinedType = createIntrinsicType(TypeFlags.Undefined | TypeFlags.ContainsUndefinedOrNull, "undefined"); - let nullType = createIntrinsicType(TypeFlags.Null | TypeFlags.ContainsUndefinedOrNull, "null"); - let unknownType = createIntrinsicType(TypeFlags.Any, "unknown"); - let circularType = createIntrinsicType(TypeFlags.Any, "__circular__"); + const anyType = createIntrinsicType(TypeFlags.Any, "any"); + const stringType = createIntrinsicType(TypeFlags.String, "string"); + const numberType = createIntrinsicType(TypeFlags.Number, "number"); + const booleanType = createIntrinsicType(TypeFlags.Boolean, "boolean"); + const esSymbolType = createIntrinsicType(TypeFlags.ESSymbol, "symbol"); + const voidType = createIntrinsicType(TypeFlags.Void, "void"); + const undefinedType = createIntrinsicType(TypeFlags.Undefined | TypeFlags.ContainsUndefinedOrNull, "undefined"); + const nullType = createIntrinsicType(TypeFlags.Null | TypeFlags.ContainsUndefinedOrNull, "null"); + const unknownType = createIntrinsicType(TypeFlags.Any, "unknown"); + const circularType = createIntrinsicType(TypeFlags.Any, "__circular__"); - let emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - let emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + const emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + const emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); emptyGenericType.instantiations = {}; - let anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + const anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. anyFunctionType.flags |= TypeFlags.ContainsAnyFunctionType; - let noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + const noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - let anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); - let unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); + const anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); + const unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, undefined, 0, false, false); - let globals: SymbolTable = {}; + const globals: SymbolTable = {}; let globalESSymbolConstructorSymbol: Symbol; @@ -160,29 +160,31 @@ namespace ts { let getGlobalPromiseConstructorLikeType: () => ObjectType; let getGlobalThenableType: () => ObjectType; - let tupleTypes: Map = {}; - let unionTypes: Map = {}; - let intersectionTypes: Map = {}; - let stringLiteralTypes: Map = {}; + let jsxElementClassType: Type; + + const tupleTypes: Map = {}; + const unionTypes: Map = {}; + const intersectionTypes: Map = {}; + const stringLiteralTypes: Map = {}; let emitExtends = false; let emitDecorate = false; let emitParam = false; let emitAwaiter = false; - let emitGenerator = false; + const emitGenerator = false; - let resolutionTargets: TypeSystemEntity[] = []; - let resolutionResults: boolean[] = []; - let resolutionPropertyNames: TypeSystemPropertyName[] = []; + const resolutionTargets: TypeSystemEntity[] = []; + const resolutionResults: boolean[] = []; + const resolutionPropertyNames: TypeSystemPropertyName[] = []; - let mergedSymbols: Symbol[] = []; - let symbolLinks: SymbolLinks[] = []; - let nodeLinks: NodeLinks[] = []; - let potentialThisCollisions: Node[] = []; - let awaitedTypeStack: number[] = []; + const mergedSymbols: Symbol[] = []; + const symbolLinks: SymbolLinks[] = []; + const nodeLinks: NodeLinks[] = []; + const potentialThisCollisions: Node[] = []; + const awaitedTypeStack: number[] = []; - let diagnostics = createDiagnosticCollection(); + const diagnostics = createDiagnosticCollection(); - let primitiveTypeInfo: Map<{ type: Type; flags: TypeFlags }> = { + const primitiveTypeInfo: Map<{ type: Type; flags: TypeFlags }> = { "string": { type: stringType, flags: TypeFlags.StringLike @@ -209,9 +211,9 @@ namespace ts { Element: "Element" }; - let subtypeRelation: Map = {}; - let assignableRelation: Map = {}; - let identityRelation: Map = {}; + const subtypeRelation: Map = {}; + const assignableRelation: Map = {}; + const identityRelation: Map = {}; // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. let _displayBuilder: SymbolDisplayBuilder; @@ -237,7 +239,7 @@ namespace ts { } function error(location: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): void { - let diagnostic = location + const diagnostic = location ? createDiagnosticForNode(location, message, arg0, arg1, arg2) : createCompilerDiagnostic(message, arg0, arg1, arg2); diagnostics.add(diagnostic); @@ -275,7 +277,7 @@ namespace ts { } function cloneSymbol(symbol: Symbol): Symbol { - let result = createSymbol(symbol.flags | SymbolFlags.Merged, symbol.name); + const result = createSymbol(symbol.flags | SymbolFlags.Merged, symbol.name); result.declarations = symbol.declarations.slice(0); result.parent = symbol.parent; if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration; @@ -308,7 +310,7 @@ namespace ts { recordMergedSymbol(target, source); } else { - let message = target.flags & SymbolFlags.BlockScopedVariable || source.flags & SymbolFlags.BlockScopedVariable + const message = target.flags & SymbolFlags.BlockScopedVariable || source.flags & SymbolFlags.BlockScopedVariable ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0; forEach(source.declarations, node => { error(node.name ? node.name : node, message, symbolToString(source)); @@ -320,8 +322,8 @@ namespace ts { } function cloneSymbolTable(symbolTable: SymbolTable): SymbolTable { - let result: SymbolTable = {}; - for (let id in symbolTable) { + const result: SymbolTable = {}; + for (const id in symbolTable) { if (hasProperty(symbolTable, id)) { result[id] = symbolTable[id]; } @@ -330,7 +332,7 @@ namespace ts { } function mergeSymbolTable(target: SymbolTable, source: SymbolTable) { - for (let id in source) { + for (const id in source) { if (hasProperty(source, id)) { if (!hasProperty(target, id)) { target[id] = source[id]; @@ -348,12 +350,12 @@ namespace ts { function getSymbolLinks(symbol: Symbol): SymbolLinks { if (symbol.flags & SymbolFlags.Transient) return symbol; - let id = getSymbolId(symbol); + const id = getSymbolId(symbol); return symbolLinks[id] || (symbolLinks[id] = {}); } function getNodeLinks(node: Node): NodeLinks { - let nodeId = getNodeId(node); + const nodeId = getNodeId(node); return nodeLinks[nodeId] || (nodeLinks[nodeId] = {}); } @@ -367,13 +369,13 @@ namespace ts { function getSymbol(symbols: SymbolTable, name: string, meaning: SymbolFlags): Symbol { if (meaning && hasProperty(symbols, name)) { - let symbol = symbols[name]; + const symbol = symbols[name]; Debug.assert((symbol.flags & SymbolFlags.Instantiated) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } if (symbol.flags & SymbolFlags.Alias) { - let target = resolveAlias(symbol); + const target = resolveAlias(symbol); // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors if (target === unknownSymbol || target.flags & meaning) { return symbol; @@ -419,7 +421,7 @@ namespace ts { else if (declaration.parent.parent.kind === SyntaxKind.ForOfStatement || declaration.parent.parent.kind === SyntaxKind.ForInStatement) { // ForIn/ForOf case - use site should not be used in expression part - let expression = (declaration.parent.parent).expression; + const expression = (declaration.parent.parent).expression; return isSameScopeDescendentOf(usage, expression, container); } } @@ -458,7 +460,7 @@ namespace ts { let result: Symbol; let lastLocation: Node; let propertyWithInvalidInitializer: Node; - let errorLocation = location; + const errorLocation = location; let grandparent: Node; loop: while (location) { @@ -480,7 +482,7 @@ namespace ts { case SyntaxKind.SourceFile: if (!isExternalModule(location)) break; case SyntaxKind.ModuleDeclaration: - let moduleExports = getSymbolOfNode(location).exports; + const moduleExports = getSymbolOfNode(location).exports; if (location.kind === SyntaxKind.SourceFile || (location.kind === SyntaxKind.ModuleDeclaration && (location).name.kind === SyntaxKind.StringLiteral)) { @@ -502,7 +504,7 @@ namespace ts { } result = moduleExports["default"]; - let localSymbol = getLocalSymbolForExportDefault(result); + const localSymbol = getLocalSymbolForExportDefault(result); if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } @@ -527,7 +529,7 @@ namespace ts { // by the same name as a constructor parameter or local variable are inaccessible // in initializer expressions for instance member variables. if (isClassLike(location.parent) && !(location.flags & NodeFlags.Static)) { - let ctor = findConstructorDeclaration(location.parent); + const ctor = findConstructorDeclaration(location.parent); if (ctor && ctor.locals) { if (getSymbol(ctor.locals, name, meaning & SymbolFlags.Value)) { // Remember the property node, it will be used later to report appropriate error @@ -550,7 +552,7 @@ namespace ts { break loop; } if (location.kind === SyntaxKind.ClassExpression && meaning & SymbolFlags.Class) { - let className = (location).name; + const className = (location).name; if (className && name === className.text) { result = location.symbol; break loop; @@ -595,7 +597,7 @@ namespace ts { } if (meaning & SymbolFlags.Function) { - let functionName = (location).name; + const functionName = (location).name; if (functionName && name === functionName.text) { result = location.symbol; break loop; @@ -645,7 +647,7 @@ namespace ts { if (propertyWithInvalidInitializer) { // We have a match, but the reference occurred within a property initializer and the identifier also binds // to a local variable in the constructor where the code will be emitted. - let propertyName = (propertyWithInvalidInitializer).name; + const propertyName = (propertyWithInvalidInitializer).name; error(errorLocation, Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, declarationNameToString(propertyName), typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg)); return undefined; @@ -657,7 +659,7 @@ namespace ts { // declare module foo { // interface bar {} // } - // let foo/*1*/: foo/*2*/.bar; + // const foo/*1*/: foo/*2*/.bar; // The foo at /*1*/ and /*2*/ will share same symbol with two meaning // block - scope variable and namespace module. However, only when we // try to resolve name in /*1*/ which is used in variable position, @@ -675,7 +677,7 @@ namespace ts { function checkResolvedBlockScopedVariable(result: Symbol, errorLocation: Node): void { Debug.assert((result.flags & SymbolFlags.BlockScopedVariable) !== 0); // Block-scoped variables cannot be used before their definition - let declaration = forEach(result.declarations, d => isBlockOrCatchScoped(d) ? d : undefined); + const declaration = forEach(result.declarations, d => isBlockOrCatchScoped(d) ? d : undefined); Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined"); @@ -725,9 +727,9 @@ namespace ts { } function getTargetOfImportClause(node: ImportClause): Symbol { - let moduleSymbol = resolveExternalModuleName(node, (node.parent).moduleSpecifier); + const moduleSymbol = resolveExternalModuleName(node, (node.parent).moduleSpecifier); if (moduleSymbol) { - let exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); + const exportDefaultSymbol = resolveSymbol(moduleSymbol.exports["default"]); if (!exportDefaultSymbol) { error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } @@ -736,13 +738,13 @@ namespace ts { } function getTargetOfNamespaceImport(node: NamespaceImport): Symbol { - let moduleSpecifier = (node.parent.parent).moduleSpecifier; + const moduleSpecifier = (node.parent.parent).moduleSpecifier; return resolveESModuleSymbol(resolveExternalModuleName(node, moduleSpecifier), moduleSpecifier); } function getMemberOfModuleVariable(moduleSymbol: Symbol, name: string): Symbol { if (moduleSymbol.flags & SymbolFlags.Variable) { - let typeAnnotation = (moduleSymbol.valueDeclaration).type; + const typeAnnotation = (moduleSymbol.valueDeclaration).type; if (typeAnnotation) { return getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name); } @@ -771,7 +773,7 @@ namespace ts { if (valueSymbol.flags & (SymbolFlags.Type | SymbolFlags.Namespace)) { return valueSymbol; } - let result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); + const result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.name); result.declarations = concatenate(valueSymbol.declarations, typeSymbol.declarations); result.parent = valueSymbol.parent || typeSymbol.parent; if (valueSymbol.valueDeclaration) result.valueDeclaration = valueSymbol.valueDeclaration; @@ -782,7 +784,7 @@ namespace ts { function getExportOfModule(symbol: Symbol, name: string): Symbol { if (symbol.flags & SymbolFlags.Module) { - let exports = getExportsOfSymbol(symbol); + const exports = getExportsOfSymbol(symbol); if (hasProperty(exports, name)) { return resolveSymbol(exports[name]); } @@ -791,7 +793,7 @@ namespace ts { function getPropertyOfVariable(symbol: Symbol, name: string): Symbol { if (symbol.flags & SymbolFlags.Variable) { - let typeAnnotation = (symbol.valueDeclaration).type; + const typeAnnotation = (symbol.valueDeclaration).type; if (typeAnnotation) { return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name)); } @@ -799,14 +801,14 @@ namespace ts { } function getExternalModuleMember(node: ImportDeclaration | ExportDeclaration, specifier: ImportOrExportSpecifier): Symbol { - let moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); - let targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); + const moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + const targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - let name = specifier.propertyName || specifier.name; + const name = specifier.propertyName || specifier.name; if (name.text) { - let symbolFromModule = getExportOfModule(targetSymbol, name.text); - let symbolFromVariable = getPropertyOfVariable(targetSymbol, name.text); - let symbol = symbolFromModule && symbolFromVariable ? + const symbolFromModule = getExportOfModule(targetSymbol, name.text); + const symbolFromVariable = getPropertyOfVariable(targetSymbol, name.text); + const symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { @@ -854,11 +856,11 @@ namespace ts { function resolveAlias(symbol: Symbol): Symbol { Debug.assert((symbol.flags & SymbolFlags.Alias) !== 0, "Should only get Alias here."); - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.target) { links.target = resolvingSymbol; - let node = getDeclarationOfAliasSymbol(symbol); - let target = getTargetOfAliasDeclaration(node); + const node = getDeclarationOfAliasSymbol(symbol); + const target = getTargetOfAliasDeclaration(node); if (links.target === resolvingSymbol) { links.target = target || unknownSymbol; } @@ -873,10 +875,10 @@ namespace ts { } function markExportAsReferenced(node: ImportEqualsDeclaration | ExportAssignment | ExportSpecifier) { - let symbol = getSymbolOfNode(node); - let target = resolveAlias(symbol); + const symbol = getSymbolOfNode(node); + const target = resolveAlias(symbol); if (target) { - let markAlias = + const markAlias = (target === unknownSymbol && compilerOptions.isolatedModules) || (target !== unknownSymbol && (target.flags & SymbolFlags.Value) && !isConstEnumOrConstEnumOnlyModule(target)); @@ -890,10 +892,10 @@ namespace ts { // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of // the alias as an expression (which recursively takes us back here if the target references another alias). function markAliasSymbolAsReferenced(symbol: Symbol) { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.referenced) { links.referenced = true; - let node = getDeclarationOfAliasSymbol(symbol); + const node = getDeclarationOfAliasSymbol(symbol); if (node.kind === SyntaxKind.ExportAssignment) { // export default checkExpressionCached((node).expression); @@ -948,7 +950,7 @@ namespace ts { let symbol: Symbol; if (name.kind === SyntaxKind.Identifier) { - let message = meaning === SymbolFlags.Namespace ? Diagnostics.Cannot_find_namespace_0 : Diagnostics.Cannot_find_name_0; + const message = meaning === SymbolFlags.Namespace ? Diagnostics.Cannot_find_namespace_0 : Diagnostics.Cannot_find_name_0; symbol = resolveName(name, (name).text, meaning, ignoreErrors ? undefined : message, name); if (!symbol) { @@ -956,10 +958,10 @@ namespace ts { } } else if (name.kind === SyntaxKind.QualifiedName || name.kind === SyntaxKind.PropertyAccessExpression) { - let left = name.kind === SyntaxKind.QualifiedName ? (name).left : (name).expression; - let right = name.kind === SyntaxKind.QualifiedName ? (name).right : (name).name; + const left = name.kind === SyntaxKind.QualifiedName ? (name).left : (name).expression; + const right = name.kind === SyntaxKind.QualifiedName ? (name).right : (name).name; - let namespace = resolveEntityName(left, SymbolFlags.Namespace, ignoreErrors); + const namespace = resolveEntityName(left, SymbolFlags.Namespace, ignoreErrors); if (!namespace || namespace === unknownSymbol || nodeIsMissing(right)) { return undefined; } @@ -983,26 +985,26 @@ namespace ts { return; } - let moduleReferenceLiteral = moduleReferenceExpression; - let searchPath = getDirectoryPath(getSourceFile(location).fileName); + const moduleReferenceLiteral = moduleReferenceExpression; + const searchPath = getDirectoryPath(getSourceFile(location).fileName); // Module names are escaped in our symbol table. However, string literal values aren't. // Escape the name in the "require(...)" clause to ensure we find the right symbol. - let moduleName = escapeIdentifier(moduleReferenceLiteral.text); + const moduleName = escapeIdentifier(moduleReferenceLiteral.text); if (moduleName === undefined) { return; } - let isRelative = isExternalModuleNameRelative(moduleName); + const isRelative = isExternalModuleNameRelative(moduleName); if (!isRelative) { - let symbol = getSymbol(globals, "\"" + moduleName + "\"", SymbolFlags.ValueModule); + const symbol = getSymbol(globals, "\"" + moduleName + "\"", SymbolFlags.ValueModule); if (symbol) { return symbol; } } - let resolvedModule = getResolvedModule(getSourceFile(location), moduleReferenceLiteral.text); - let sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); + const resolvedModule = getResolvedModule(getSourceFile(location), moduleReferenceLiteral.text); + const sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName); if (sourceFile) { if (sourceFile.symbol) { return sourceFile.symbol; @@ -1044,12 +1046,12 @@ namespace ts { } function getExportsOfModule(moduleSymbol: Symbol): SymbolTable { - let links = getSymbolLinks(moduleSymbol); + const links = getSymbolLinks(moduleSymbol); return links.resolvedExports || (links.resolvedExports = getExportsForModule(moduleSymbol)); } function extendExportSymbols(target: SymbolTable, source: SymbolTable) { - for (let id in source) { + for (const id in source) { if (id !== "default" && !hasProperty(target, id)) { target[id] = source[id]; } @@ -1058,7 +1060,7 @@ namespace ts { function getExportsForModule(moduleSymbol: Symbol): SymbolTable { let result: SymbolTable; - let visitedSymbols: Symbol[] = []; + const visitedSymbols: Symbol[] = []; visit(moduleSymbol); return result || moduleSymbol.exports; @@ -1074,9 +1076,9 @@ namespace ts { extendExportSymbols(result, symbol.exports); } // All export * declarations are collected in an __export symbol by the binder - let exportStars = symbol.exports["__export"]; + const exportStars = symbol.exports["__export"]; if (exportStars) { - for (let node of exportStars.declarations) { + for (const node of exportStars.declarations) { visit(resolveExternalModuleName(node, (node).moduleSpecifier)); } } @@ -1124,8 +1126,8 @@ namespace ts { } function findConstructorDeclaration(node: ClassLikeDeclaration): ConstructorDeclaration { - let members = node.members; - for (let member of members) { + const members = node.members; + for (const member of members) { if (member.kind === SyntaxKind.Constructor && nodeIsPresent((member).body)) { return member; } @@ -1133,19 +1135,19 @@ namespace ts { } function createType(flags: TypeFlags): Type { - let result = new Type(checker, flags); + const result = new Type(checker, flags); result.id = typeCount++; return result; } function createIntrinsicType(kind: TypeFlags, intrinsicName: string): IntrinsicType { - let type = createType(kind); + const type = createType(kind); type.intrinsicName = intrinsicName; return type; } function createObjectType(kind: TypeFlags, symbol?: Symbol): ObjectType { - let type = createType(kind); + const type = createType(kind); type.symbol = symbol; return type; } @@ -1163,11 +1165,11 @@ namespace ts { function getNamedMembers(members: SymbolTable): Symbol[] { let result: Symbol[]; - for (let id in members) { + for (const id in members) { if (hasProperty(members, id)) { if (!isReservedMemberName(id)) { if (!result) result = []; - let symbol = members[id]; + const symbol = members[id]; if (symbolIsValue(symbol)) { result.push(symbol); } @@ -1237,7 +1239,7 @@ namespace ts { } // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too - let accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); + const accessibleParent = getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing); return !!accessibleParent; } @@ -1265,14 +1267,14 @@ namespace ts { // Is this external alias, then use it to name ts.forEach(symbolFromSymbolTable.declarations, isExternalModuleImportEqualsDeclaration)) { - let resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); + const resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable); if (isAccessible(symbolFromSymbolTable, resolveAlias(symbolFromSymbolTable))) { return [symbolFromSymbolTable]; } // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain // but only if the symbolFromSymbolTable can be qualified - let accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; + const accessibleSymbolsFromExports = resolvedImportedSymbol.exports ? getAccessibleSymbolChainFromSymbolTable(resolvedImportedSymbol.exports) : undefined; if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) { return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports); } @@ -1317,13 +1319,13 @@ namespace ts { function isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult { if (symbol && enclosingDeclaration && !(symbol.flags & SymbolFlags.TypeParameter)) { - let initialSymbol = symbol; + const initialSymbol = symbol; let meaningToLook = meaning; while (symbol) { // Symbol is accessible if it by itself is accessible - let accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); + const accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); if (accessibleSymbolChain) { - let hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + const hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); if (!hasAccessibleDeclarations) { return { accessibility: SymbolAccessibility.NotAccessible, @@ -1341,7 +1343,7 @@ namespace ts { // export class c { // } // } - // let x: typeof m.c + // const x: typeof m.c // In the above example when we start with checking if typeof m.c symbol is accessible, // we are going to see if c can be accessed in scope directly. // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible @@ -1352,9 +1354,9 @@ namespace ts { // This could be a symbol that is not exported in the external module // or it could be a symbol from different external module that is not aliased and hence cannot be named - let symbolExternalModule = forEach(initialSymbol.declarations, getExternalModuleContainer); + const symbolExternalModule = forEach(initialSymbol.declarations, getExternalModuleContainer); if (symbolExternalModule) { - let enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); + const enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration); if (symbolExternalModule !== enclosingExternalModule) { // name from different external module that is not visible return { @@ -1400,7 +1402,7 @@ namespace ts { // Mark the unexported alias as visible if its parent is visible // because these kind of aliases can be used to name types in declaration file - let anyImportSyntax = getAnyImportSyntax(declaration); + const anyImportSyntax = getAnyImportSyntax(declaration); if (anyImportSyntax && !(anyImportSyntax.flags & NodeFlags.Export) && // import clause without export isDeclarationVisible(anyImportSyntax.parent)) { @@ -1442,8 +1444,8 @@ namespace ts { meaning = SymbolFlags.Type; } - let firstIdentifier = getFirstIdentifier(entityName); - let symbol = resolveName(enclosingDeclaration, (firstIdentifier).text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + const firstIdentifier = getFirstIdentifier(entityName); + const symbol = resolveName(enclosingDeclaration, (firstIdentifier).text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol)) || { @@ -1466,30 +1468,30 @@ namespace ts { } function symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string { - let writer = getSingleLineStringWriter(); + const writer = getSingleLineStringWriter(); getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - let result = writer.string(); + const result = writer.string(); releaseStringWriter(writer); return result; } function signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { - let writer = getSingleLineStringWriter(); + const writer = getSingleLineStringWriter(); getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); - let result = writer.string(); + const result = writer.string(); releaseStringWriter(writer); return result; } function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string { - let writer = getSingleLineStringWriter(); + const writer = getSingleLineStringWriter(); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); let result = writer.string(); releaseStringWriter(writer); - let maxLength = compilerOptions.noErrorTruncation || flags & TypeFormatFlags.NoTruncation ? undefined : 100; + const maxLength = compilerOptions.noErrorTruncation || flags & TypeFormatFlags.NoTruncation ? undefined : 100; if (maxLength && result.length >= maxLength) { result = result.substr(0, maxLength - "...".length) + "..."; } @@ -1513,7 +1515,7 @@ namespace ts { function getNameOfSymbol(symbol: Symbol): string { if (symbol.declarations && symbol.declarations.length) { - let declaration = symbol.declarations[0]; + const declaration = symbol.declarations[0]; if (declaration.name) { return declarationNameToString(declaration.name); } @@ -1560,7 +1562,7 @@ namespace ts { appendSymbolNameOnly(symbol, writer); } - // Let the writer know we just wrote out a symbol. The declaration emitter writer uses + // const the writer know we just wrote out a symbol. The declaration emitter writer uses // this to determine if an import it has previously seen (and not written out) needs // to be written to the file once the walk of the tree is complete. // @@ -1570,7 +1572,7 @@ namespace ts { writer.trackSymbol(symbol, enclosingDeclaration, meaning); function walkSymbol(symbol: Symbol, meaning: SymbolFlags): void { if (symbol) { - let accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & SymbolFormatFlags.UseOnlyExternalAliasing)); + const accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & SymbolFormatFlags.UseOnlyExternalAliasing)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { @@ -1582,7 +1584,7 @@ namespace ts { } if (accessibleSymbolChain) { - for (let accessibleSymbol of accessibleSymbolChain) { + for (const accessibleSymbol of accessibleSymbolChain) { appendParentTypeArgumentsAndSymbolName(accessibleSymbol); } } @@ -1605,8 +1607,8 @@ namespace ts { // Get qualified name if the symbol is not a type parameter // and there is an enclosing declaration or we specifically // asked for it - let isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; - let typeFormatFlag = TypeFormatFlags.UseFullyQualifiedType & typeFlags; + const isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; + const typeFormatFlag = TypeFormatFlags.UseFullyQualifiedType & typeFlags; if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { walkSymbol(symbol, meaning); return; @@ -1616,7 +1618,7 @@ namespace ts { } function buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]) { - let globalFlagsToPass = globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike; + const globalFlagsToPass = globalFlags & TypeFormatFlags.WriteOwnNameForAnyLike; let inObjectTypeLiteral = false; return writeType(type, globalFlags); @@ -1695,7 +1697,7 @@ namespace ts { } function writeTypeReference(type: TypeReference, flags: TypeFormatFlags) { - let typeArguments = type.typeArguments || emptyArray; + const typeArguments = type.typeArguments || emptyArray; if (type.target === globalArrayType && !(flags & TypeFormatFlags.WriteArrayAsGenericType)) { writeType(typeArguments[0], TypeFormatFlags.InElementType); writePunctuation(writer, SyntaxKind.OpenBracketToken); @@ -1705,14 +1707,14 @@ namespace ts { // Write the type reference in the format f.g.C where A and B are type arguments // for outer type parameters, and f and g are the respective declaring containers of those // type parameters. - let outerTypeParameters = type.target.outerTypeParameters; + const outerTypeParameters = type.target.outerTypeParameters; let i = 0; if (outerTypeParameters) { - let length = outerTypeParameters.length; + const length = outerTypeParameters.length; while (i < length) { // Find group of type arguments for type parameters with the same declaring container. - let start = i; - let parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + const start = i; + const parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; } while (i < length && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); @@ -1724,7 +1726,7 @@ namespace ts { } } } - let typeParameterCount = (type.target.typeParameters || emptyArray).length; + const typeParameterCount = (type.target.typeParameters || emptyArray).length; writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); } } @@ -1746,7 +1748,7 @@ namespace ts { } function writeAnonymousType(type: ObjectType, flags: TypeFormatFlags) { - let symbol = type.symbol; + const symbol = type.symbol; if (symbol) { // Always use 'typeof T' for type of class, enum, and module objects if (symbol.flags & (SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.ValueModule)) { @@ -1757,7 +1759,7 @@ namespace ts { } else if (contains(symbolStack, symbol)) { // If type is an anonymous type literal in a type alias declaration, use type alias name - let typeAlias = getTypeAliasForTypeLiteral(type); + const typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, flags); @@ -1784,9 +1786,9 @@ namespace ts { } function shouldWriteTypeOfFunctionSymbol() { - let isStaticMethodSymbol = !!(symbol.flags & SymbolFlags.Method && // typeof static method + const isStaticMethodSymbol = !!(symbol.flags & SymbolFlags.Method && // typeof static method forEach(symbol.declarations, declaration => declaration.flags & NodeFlags.Static)); - let isNonLocalFunctionSymbol = !!(symbol.flags & SymbolFlags.Function) && + const isNonLocalFunctionSymbol = !!(symbol.flags & SymbolFlags.Function) && (symbol.parent || // is exported function symbol forEach(symbol.declarations, declaration => declaration.parent.kind === SyntaxKind.SourceFile || declaration.parent.kind === SyntaxKind.ModuleBlock)); @@ -1805,7 +1807,7 @@ namespace ts { } function getIndexerParameterName(type: ObjectType, indexKind: IndexKind, fallbackName: string): string { - let declaration = getIndexDeclarationOfSymbol(type.symbol, indexKind); + const declaration = getIndexDeclarationOfSymbol(type.symbol, indexKind); if (!declaration) { // declaration might not be found if indexer was added from the contextual type. // in this case use fallback name @@ -1816,7 +1818,7 @@ namespace ts { } function writeLiteralType(type: ObjectType, flags: TypeFormatFlags) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); if (!resolved.properties.length && !resolved.stringIndexType && !resolved.numberIndexType) { if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { writePunctuation(writer, SyntaxKind.OpenBraceToken); @@ -1848,17 +1850,17 @@ namespace ts { } } - let saveInObjectTypeLiteral = inObjectTypeLiteral; + const saveInObjectTypeLiteral = inObjectTypeLiteral; inObjectTypeLiteral = true; writePunctuation(writer, SyntaxKind.OpenBraceToken); writer.writeLine(); writer.increaseIndent(); - for (let signature of resolved.callSignatures) { + for (const signature of resolved.callSignatures) { buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, symbolStack); writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } - for (let signature of resolved.constructSignatures) { + for (const signature of resolved.constructSignatures) { writeKeyword(writer, SyntaxKind.NewKeyword); writeSpace(writer); @@ -1894,11 +1896,11 @@ namespace ts { writePunctuation(writer, SyntaxKind.SemicolonToken); writer.writeLine(); } - for (let p of resolved.properties) { - let t = getTypeOfSymbol(p); + for (const p of resolved.properties) { + const t = getTypeOfSymbol(p); if (p.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfObjectType(t).length) { - let signatures = getSignaturesOfType(t, SignatureKind.Call); - for (let signature of signatures) { + const signatures = getSignaturesOfType(t, SignatureKind.Call); + for (const signature of signatures) { buildSymbolDisplay(p, writer); if (p.flags & SymbolFlags.Optional) { writePunctuation(writer, SyntaxKind.QuestionToken); @@ -1927,7 +1929,7 @@ namespace ts { } function buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaraiton?: Node, flags?: TypeFormatFlags) { - let targetSymbol = getTargetSymbol(symbol); + const targetSymbol = getTargetSymbol(symbol); if (targetSymbol.flags & SymbolFlags.Class || targetSymbol.flags & SymbolFlags.Interface || targetSymbol.flags & SymbolFlags.TypeAlias) { buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaraiton, flags); } @@ -1935,7 +1937,7 @@ namespace ts { function buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { appendSymbolNameOnly(tp.symbol, writer); - let constraint = getConstraintOfTypeParameter(tp); + const constraint = getConstraintOfTypeParameter(tp); if (constraint) { writeSpace(writer); writeKeyword(writer, SyntaxKind.ExtendsKeyword); @@ -1945,7 +1947,7 @@ namespace ts { } function buildParameterDisplay(p: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, symbolStack?: Symbol[]) { - let parameterNode = p.valueDeclaration; + const parameterNode = p.valueDeclaration; if (isRestParameter(parameterNode)) { writePunctuation(writer, SyntaxKind.DotDotDotToken); } @@ -2067,14 +2069,14 @@ namespace ts { function isUsedInExportAssignment(node: Node) { // Get source File and see if it is external module and has export assigned symbol - let externalModule = getContainingExternalModule(node); + const externalModule = getContainingExternalModule(node); let exportAssignmentSymbol: Symbol; let resolvedExportSymbol: Symbol; if (externalModule) { // This is export assigned symbol node - let externalModuleSymbol = getSymbolOfNode(externalModule); + const externalModuleSymbol = getSymbolOfNode(externalModule); exportAssignmentSymbol = getExportAssignmentSymbol(externalModuleSymbol); - let symbolOfNode = getSymbolOfNode(node); + const symbolOfNode = getSymbolOfNode(node); if (isSymbolUsedInExportAssignment(symbolOfNode)) { return true; } @@ -2129,7 +2131,7 @@ namespace ts { case SyntaxKind.FunctionDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.ImportEqualsDeclaration: - let parent = getDeclarationContainer(node); + const parent = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(getCombinedNodeFlags(node) & NodeFlags.Export) && !(node.kind !== SyntaxKind.ImportEqualsDeclaration && parent.kind !== SyntaxKind.SourceFile && isInAmbientContext(parent))) { @@ -2148,7 +2150,7 @@ namespace ts { // Private/protected properties/methods are not visible return false; } - // Public properties/methods are visible if its parents are visible, so let it fall into next case statement + // Public properties/methods are visible if its parents are visible, so const it fall into next case statement case SyntaxKind.Constructor: case SyntaxKind.ConstructSignature: @@ -2190,7 +2192,7 @@ namespace ts { } if (node) { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (links.isVisible === undefined) { links.isVisible = !!determineIfDeclarationIsVisible(); } @@ -2204,12 +2206,12 @@ namespace ts { exportSymbol = resolveName(node.parent, node.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, Diagnostics.Cannot_find_name_0, node); } else if (node.parent.kind === SyntaxKind.ExportSpecifier) { - let exportSpecifier = node.parent; + const exportSpecifier = node.parent; exportSymbol = (exportSpecifier.parent.parent).moduleSpecifier ? getExternalModuleMember(exportSpecifier.parent.parent, exportSpecifier) : resolveEntityName(exportSpecifier.propertyName || exportSpecifier.name, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias); } - let result: Node[] = []; + const result: Node[] = []; if (exportSymbol) { buildVisibleNodeList(exportSymbol.declarations); } @@ -2218,16 +2220,16 @@ namespace ts { function buildVisibleNodeList(declarations: Declaration[]) { forEach(declarations, declaration => { getNodeLinks(declaration).isVisible = true; - let resultNode = getAnyImportSyntax(declaration) || declaration; + const resultNode = getAnyImportSyntax(declaration) || declaration; if (!contains(result, resultNode)) { result.push(resultNode); } if (isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible - let internalModuleReference = (declaration).moduleReference; - let firstIdentifier = getFirstIdentifier(internalModuleReference); - let importSymbol = resolveName(declaration, firstIdentifier.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, + const internalModuleReference = (declaration).moduleReference; + const firstIdentifier = getFirstIdentifier(internalModuleReference); + const importSymbol = resolveName(declaration, firstIdentifier.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, Diagnostics.Cannot_find_name_0, firstIdentifier); buildVisibleNodeList(importSymbol.declarations); } @@ -2247,10 +2249,10 @@ namespace ts { * @param propertyName The property name that should be used to query the target for its type */ function pushTypeResolution(target: TypeSystemEntity, propertyName: TypeSystemPropertyName): boolean { - let resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); + const resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - let { length } = resolutionTargets; + const { length } = resolutionTargets; for (let i = resolutionCycleStartIndex; i < length; i++) { resolutionResults[i] = false; } @@ -2314,13 +2316,13 @@ namespace ts { // Every class automatically contains a static property member named 'prototype', // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter. // It is an error to explicitly declare a static property member with the name 'prototype'. - let classType = getDeclaredTypeOfSymbol(prototype.parent); + const classType = getDeclaredTypeOfSymbol(prototype.parent); return classType.typeParameters ? createTypeReference(classType, map(classType.typeParameters, _ => anyType)) : classType; } // Return the type of the given property in the given type, or undefined if no such property exists function getTypeOfPropertyOfType(type: Type, name: string): Type { - let prop = getPropertyOfType(type, name); + const prop = getPropertyOfType(type, name); return prop ? getTypeOfSymbol(prop) : undefined; } @@ -2331,14 +2333,14 @@ namespace ts { // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been // assigned by contextual typing. function getTypeForBindingElementParent(node: VariableLikeDeclaration) { - let symbol = getSymbolOfNode(node); + const symbol = getSymbolOfNode(node); return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node); } // Return the inferred type for a binding element function getTypeForBindingElement(declaration: BindingElement): Type { - let pattern = declaration.parent; - let parentType = getTypeForBindingElementParent(pattern.parent); + const pattern = declaration.parent; + const parentType = getTypeForBindingElementParent(pattern.parent); // If parent has the unknown (error) type, then so does this binding element if (parentType === unknownType) { return unknownType; @@ -2356,7 +2358,7 @@ namespace ts { let type: Type; if (pattern.kind === SyntaxKind.ObjectBindingPattern) { // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form) - let name = declaration.propertyName || declaration.name; + const name = declaration.propertyName || declaration.name; // Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature, // or otherwise the type of the string index signature. type = getTypeOfPropertyOfType(parentType, name.text) || @@ -2371,10 +2373,10 @@ namespace ts { // This elementType will be used if the specific property corresponding to this index is not // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). - let elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false); + const elementType = checkIteratedTypeOrElementType(parentType, pattern, /*allowStringInput*/ false); if (!declaration.dotDotDotToken) { // Use specific property type when parent is a tuple or numeric index type when parent is an array - let propName = "" + indexOf(pattern.elements, declaration); + const propName = "" + indexOf(pattern.elements, declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : elementType; @@ -2421,16 +2423,16 @@ namespace ts { } if (declaration.kind === SyntaxKind.Parameter) { - let func = declaration.parent; + const func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present if (func.kind === SyntaxKind.SetAccessor && !hasDynamicName(func)) { - let getter = getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor); + const getter = getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); } } // Use contextual parameter type if one is available - let type = getContextuallyTypedParameterType(declaration); + const type = getContextuallyTypedParameterType(declaration); if (type) { return type; } @@ -2470,16 +2472,16 @@ namespace ts { // Return the type implied by an object binding pattern function getTypeFromObjectBindingPattern(pattern: BindingPattern, includePatternInType: boolean): Type { - let members: SymbolTable = {}; + const members: SymbolTable = {}; forEach(pattern.elements, e => { - let flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : 0); - let name = e.propertyName || e.name; - let symbol = createSymbol(flags, name.text); + const flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : 0); + const name = e.propertyName || e.name; + const symbol = createSymbol(flags, name.text); symbol.type = getTypeFromBindingElement(e, includePatternInType); symbol.bindingElement = e; members[symbol.name] = symbol; }); - let result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined); + const result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined); if (includePatternInType) { result.pattern = pattern; } @@ -2488,14 +2490,14 @@ namespace ts { // Return the type implied by an array binding pattern function getTypeFromArrayBindingPattern(pattern: BindingPattern, includePatternInType: boolean): Type { - let elements = pattern.elements; + const elements = pattern.elements; if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) { return languageVersion >= ScriptTarget.ES6 ? createIterableType(anyType) : anyArrayType; } // If the pattern has at least one element, and no rest element, then it should imply a tuple type. - let elementTypes = map(elements, e => e.kind === SyntaxKind.OmittedExpression ? anyType : getTypeFromBindingElement(e, includePatternInType)); + const elementTypes = map(elements, e => e.kind === SyntaxKind.OmittedExpression ? anyType : getTypeFromBindingElement(e, includePatternInType)); if (includePatternInType) { - let result = createNewTupleType(elementTypes); + const result = createNewTupleType(elementTypes); result.pattern = pattern; return result; } @@ -2541,7 +2543,7 @@ namespace ts { // Report implicit any errors unless this is a private property within an ambient declaration if (reportErrors && compilerOptions.noImplicitAny) { - let root = getRootDeclaration(declaration); + const root = getRootDeclaration(declaration); if (!isPrivateWithinAmbient(root) && !(root.kind === SyntaxKind.Parameter && isPrivateWithinAmbient(root.parent))) { reportImplicitAnyError(declaration, type); } @@ -2550,14 +2552,14 @@ namespace ts { } function getTypeOfVariableOrParameterOrProperty(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.type) { // Handle prototype property if (symbol.flags & SymbolFlags.Prototype) { return links.type = getTypeOfPrototypeProperty(symbol); } // Handle catch clause variables - let declaration = symbol.valueDeclaration; + const declaration = symbol.valueDeclaration; if (declaration.parent.kind === SyntaxKind.CatchClause) { return links.type = anyType; } @@ -2597,7 +2599,7 @@ namespace ts { return accessor.type && getTypeFromTypeNode(accessor.type); } else { - let setterTypeAnnotation = getSetAccessorTypeAnnotationNode(accessor); + const setterTypeAnnotation = getSetAccessorTypeAnnotationNode(accessor); return setterTypeAnnotation && getTypeFromTypeNode(setterTypeAnnotation); } } @@ -2605,22 +2607,22 @@ namespace ts { } function getTypeOfAccessors(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.type) { if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { return unknownType; } - let getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); - let setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); + const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + const setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); let type: Type; // First try to see if the user specified a return type on the get-accessor. - let getterReturnType = getAnnotatedAccessorType(getter); + const getterReturnType = getAnnotatedAccessorType(getter); if (getterReturnType) { type = getterReturnType; } else { // If the user didn't specify a return type, try to use the set-accessor's parameter type. - let setterParameterType = getAnnotatedAccessorType(setter); + const setterParameterType = getAnnotatedAccessorType(setter); if (setterParameterType) { type = setterParameterType; } @@ -2641,7 +2643,7 @@ namespace ts { if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - let getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + const getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); error(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); } } @@ -2651,7 +2653,7 @@ namespace ts { } function getTypeOfFuncClassEnumModule(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.type) { links.type = createObjectType(TypeFlags.Anonymous, symbol); } @@ -2659,7 +2661,7 @@ namespace ts { } function getTypeOfEnumMember(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.type) { links.type = getDeclaredTypeOfEnum(getParentOfSymbol(symbol)); } @@ -2667,9 +2669,9 @@ namespace ts { } function getTypeOfAlias(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.type) { - let targetSymbol = resolveAlias(symbol); + const targetSymbol = resolveAlias(symbol); // It only makes sense to get the type of a value symbol. If the result of resolving // the alias is not a value, then it has no type. To get the type associated with a @@ -2684,7 +2686,7 @@ namespace ts { } function getTypeOfInstantiatedSymbol(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.type) { links.type = instantiateType(getTypeOfSymbol(links.target), links.mapper); } @@ -2720,7 +2722,7 @@ namespace ts { function hasBaseType(type: InterfaceType, checkBase: InterfaceType) { return check(type); function check(type: InterfaceType): boolean { - let target = getTargetType(type); + const target = getTargetType(type); return target === checkBase || forEach(getBaseTypes(target), check); } } @@ -2729,8 +2731,8 @@ namespace ts { // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set // in-place and returns the same array. function appendTypeParameters(typeParameters: TypeParameter[], declarations: TypeParameterDeclaration[]): TypeParameter[] { - for (let declaration of declarations) { - let tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); + for (const declaration of declarations) { + const tp = getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)); if (!typeParameters) { typeParameters = [tp]; } @@ -2753,7 +2755,7 @@ namespace ts { if (node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression || node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.FunctionExpression || node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.ArrowFunction) { - let declarations = (node).typeParameters; + const declarations = (node).typeParameters; if (declarations) { return appendTypeParameters(appendOuterTypeParameters(typeParameters, node), declarations); } @@ -2763,7 +2765,7 @@ namespace ts { // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol: Symbol): TypeParameter[] { - let declaration = symbol.flags & SymbolFlags.Class ? symbol.valueDeclaration : getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); + const declaration = symbol.flags & SymbolFlags.Class ? symbol.valueDeclaration : getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); return appendOuterTypeParameters(undefined, declaration); } @@ -2771,10 +2773,10 @@ namespace ts { // interface, or type alias. function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol: Symbol): TypeParameter[] { let result: TypeParameter[]; - for (let node of symbol.declarations) { + for (const node of symbol.declarations) { if (node.kind === SyntaxKind.InterfaceDeclaration || node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression || node.kind === SyntaxKind.TypeAliasDeclaration) { - let declaration = node; + const declaration = node; if (declaration.typeParameters) { result = appendTypeParameters(result, declaration.typeParameters); } @@ -2798,7 +2800,7 @@ namespace ts { } function getConstructorsForTypeArguments(type: ObjectType, typeArgumentNodes: TypeNode[]): Signature[] { - let typeArgCount = typeArgumentNodes ? typeArgumentNodes.length : 0; + const typeArgCount = typeArgumentNodes ? typeArgumentNodes.length : 0; return filter(getSignaturesOfType(type, SignatureKind.Construct), sig => (sig.typeParameters ? sig.typeParameters.length : 0) === typeArgCount); } @@ -2806,7 +2808,7 @@ namespace ts { function getInstantiatedConstructorsForTypeArguments(type: ObjectType, typeArgumentNodes: TypeNode[]): Signature[] { let signatures = getConstructorsForTypeArguments(type, typeArgumentNodes); if (typeArgumentNodes) { - let typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); + const typeArguments = map(typeArgumentNodes, getTypeFromTypeNode); signatures = map(signatures, sig => getSignatureInstantiation(sig, typeArguments)); } return signatures; @@ -2819,14 +2821,14 @@ namespace ts { // an object type with at least one construct signature. function getBaseConstructorTypeOfClass(type: InterfaceType): ObjectType { if (!type.resolvedBaseConstructorType) { - let baseTypeNode = getBaseTypeNodeOfClass(type); + const baseTypeNode = getBaseTypeNodeOfClass(type); if (!baseTypeNode) { return type.resolvedBaseConstructorType = undefinedType; } if (!pushTypeResolution(type, TypeSystemPropertyName.ResolvedBaseConstructorType)) { return unknownType; } - let baseConstructorType = checkExpression(baseTypeNode.expression); + const baseConstructorType = checkExpression(baseTypeNode.expression); if (baseConstructorType.flags & TypeFlags.ObjectType) { // Resolving the members of a class requires us to resolve the base class of that class. // We force resolution here such that we catch circularities now. @@ -2850,8 +2852,8 @@ namespace ts { } function getBaseTypes(type: InterfaceType): ObjectType[] { - let isClass = type.symbol.flags & SymbolFlags.Class; - let isInterface = type.symbol.flags & SymbolFlags.Interface; + const isClass = type.symbol.flags & SymbolFlags.Class; + const isInterface = type.symbol.flags & SymbolFlags.Interface; if (!type.resolvedBaseTypes) { if (!isClass && !isInterface) { Debug.fail("type must be class or interface"); @@ -2868,11 +2870,11 @@ namespace ts { function resolveBaseTypesOfClass(type: InterfaceType): void { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - let baseContructorType = getBaseConstructorTypeOfClass(type); + const baseContructorType = getBaseConstructorTypeOfClass(type); if (!(baseContructorType.flags & TypeFlags.ObjectType)) { return; } - let baseTypeNode = getBaseTypeNodeOfClass(type); + const baseTypeNode = getBaseTypeNodeOfClass(type); let baseType: Type; if (baseContructorType.symbol && baseContructorType.symbol.flags & SymbolFlags.Class) { // When base constructor type is a class we know that the constructors all have the same type parameters as the @@ -2884,7 +2886,7 @@ namespace ts { // The class derives from a "class-like" constructor function, check that we have at least one construct signature // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere // we check that all instantiated signatures return the same type. - let constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments); + const constructors = getInstantiatedConstructorsForTypeArguments(baseContructorType, baseTypeNode.typeArguments); if (!constructors.length) { error(baseTypeNode.expression, Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments); return; @@ -2913,10 +2915,10 @@ namespace ts { function resolveBaseTypesOfInterface(type: InterfaceType): void { type.resolvedBaseTypes = type.resolvedBaseTypes || emptyArray; - for (let declaration of type.symbol.declarations) { + for (const declaration of type.symbol.declarations) { if (declaration.kind === SyntaxKind.InterfaceDeclaration && getInterfaceBaseTypeNodes(declaration)) { - for (let node of getInterfaceBaseTypeNodes(declaration)) { - let baseType = getTypeFromTypeNode(node); + for (const node of getInterfaceBaseTypeNodes(declaration)) { + const baseType = getTypeFromTypeNode(node); if (baseType !== unknownType) { if (getTargetType(baseType).flags & (TypeFlags.Class | TypeFlags.Interface)) { if (type !== baseType && !hasBaseType(baseType, type)) { @@ -2944,16 +2946,16 @@ namespace ts { // true if the interface itself contains no references to "this" in its body, if all base types are interfaces, // and if none of the base interfaces have a "this" type. function isIndependentInterface(symbol: Symbol): boolean { - for (let declaration of symbol.declarations) { + for (const declaration of symbol.declarations) { if (declaration.kind === SyntaxKind.InterfaceDeclaration) { if (declaration.flags & NodeFlags.ContainsThis) { return false; } - let baseTypeNodes = getInterfaceBaseTypeNodes(declaration); + const baseTypeNodes = getInterfaceBaseTypeNodes(declaration); if (baseTypeNodes) { - for (let node of baseTypeNodes) { + for (const node of baseTypeNodes) { if (isSupportedExpressionWithTypeArguments(node)) { - let baseSymbol = resolveEntityName(node.expression, SymbolFlags.Type, /*ignoreErrors*/ true); + const baseSymbol = resolveEntityName(node.expression, SymbolFlags.Type, /*ignoreErrors*/ true); if (!baseSymbol || !(baseSymbol.flags & SymbolFlags.Interface) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) { return false; } @@ -2966,12 +2968,12 @@ namespace ts { } function getDeclaredTypeOfClassOrInterface(symbol: Symbol): InterfaceType { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.declaredType) { - let kind = symbol.flags & SymbolFlags.Class ? TypeFlags.Class : TypeFlags.Interface; - let type = links.declaredType = createObjectType(kind, symbol); - let outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); - let localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); + const kind = symbol.flags & SymbolFlags.Class ? TypeFlags.Class : TypeFlags.Interface; + const type = links.declaredType = createObjectType(kind, symbol); + const outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol); + const localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular, // property types inferred from initializers and method return types inferred from return statements are very hard @@ -2995,14 +2997,14 @@ namespace ts { } function getDeclaredTypeOfTypeAlias(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.declaredType) { // Note that we use the links object as the target here because the symbol object is used as the unique // identity for resolution of the 'type' property in SymbolLinks. if (!pushTypeResolution(symbol, TypeSystemPropertyName.DeclaredType)) { return unknownType; } - let declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); + const declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); let type = getTypeFromTypeNode(declaration.type); if (popTypeResolution()) { links.typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); @@ -3023,9 +3025,9 @@ namespace ts { } function getDeclaredTypeOfEnum(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.declaredType) { - let type = createType(TypeFlags.Enum); + const type = createType(TypeFlags.Enum); type.symbol = symbol; links.declaredType = type; } @@ -3033,9 +3035,9 @@ namespace ts { } function getDeclaredTypeOfTypeParameter(symbol: Symbol): TypeParameter { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.declaredType) { - let type = createType(TypeFlags.TypeParameter); + const type = createType(TypeFlags.TypeParameter); type.symbol = symbol; if (!(getDeclarationOfKind(symbol, SyntaxKind.TypeParameter)).constraint) { type.constraint = noConstraintType; @@ -3046,7 +3048,7 @@ namespace ts { } function getDeclaredTypeOfAlias(symbol: Symbol): Type { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (!links.declaredType) { links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)); } @@ -3076,7 +3078,7 @@ namespace ts { // A type reference is considered independent if each type argument is considered independent. function isIndependentTypeReference(node: TypeReferenceNode): boolean { if (node.typeArguments) { - for (let typeNode of node.typeArguments) { + for (const typeNode of node.typeArguments) { if (!isIndependentType(typeNode)) { return false; } @@ -3118,7 +3120,7 @@ namespace ts { if (node.kind !== SyntaxKind.Constructor && (!node.type || !isIndependentType(node.type))) { return false; } - for (let parameter of node.parameters) { + for (const parameter of node.parameters) { if (!isIndependentVariableLikeDeclaration(parameter)) { return false; } @@ -3133,7 +3135,7 @@ namespace ts { // assumed not to be free of "this" references. function isIndependentMember(symbol: Symbol): boolean { if (symbol.declarations && symbol.declarations.length === 1) { - let declaration = symbol.declarations[0]; + const declaration = symbol.declarations[0]; if (declaration) { switch (declaration.kind) { case SyntaxKind.PropertyDeclaration: @@ -3150,8 +3152,8 @@ namespace ts { } function createSymbolTable(symbols: Symbol[]): SymbolTable { - let result: SymbolTable = {}; - for (let symbol of symbols) { + const result: SymbolTable = {}; + for (const symbol of symbols) { result[symbol.name] = symbol; } return result; @@ -3160,15 +3162,15 @@ namespace ts { // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true, // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation. function createInstantiatedSymbolTable(symbols: Symbol[], mapper: TypeMapper, mappingThisOnly: boolean): SymbolTable { - let result: SymbolTable = {}; - for (let symbol of symbols) { + const result: SymbolTable = {}; + for (const symbol of symbols) { result[symbol.name] = mappingThisOnly && isIndependentMember(symbol) ? symbol : instantiateSymbol(symbol, mapper); } return result; } function addInheritedMembers(symbols: SymbolTable, baseSymbols: Symbol[]) { - for (let s of baseSymbols) { + for (const s of baseSymbols) { if (!hasProperty(symbols, s.name)) { symbols[s.name] = s; } @@ -3177,7 +3179,7 @@ namespace ts { function addInheritedSignatures(signatures: Signature[], baseSignatures: Signature[]) { if (baseSignatures) { - for (let signature of baseSignatures) { + for (const signature of baseSignatures) { signatures.push(signature); } } @@ -3185,7 +3187,7 @@ namespace ts { function resolveDeclaredMembers(type: InterfaceType): InterfaceTypeWithDeclaredMembers { if (!(type).declaredProperties) { - let symbol = type.symbol; + const symbol = type.symbol; (type).declaredProperties = getNamedMembers(symbol.members); (type).declaredCallSignatures = getSignaturesOfSymbol(symbol.members["__call"]); (type).declaredConstructSignatures = getSignaturesOfSymbol(symbol.members["__new"]); @@ -3218,14 +3220,14 @@ namespace ts { stringIndexType = instantiateType(source.declaredStringIndexType, mapper); numberIndexType = instantiateType(source.declaredNumberIndexType, mapper); } - let baseTypes = getBaseTypes(source); + const baseTypes = getBaseTypes(source); if (baseTypes.length) { if (members === source.symbol.members) { members = createSymbolTable(source.declaredProperties); } - let thisArgument = lastOrUndefined(typeArguments); - for (let baseType of baseTypes) { - let instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; + const thisArgument = lastOrUndefined(typeArguments); + for (const baseType of baseTypes) { + const instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType; addInheritedMembers(members, getPropertiesOfObjectType(instantiatedBaseType)); callSignatures = concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Call)); constructSignatures = concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, SignatureKind.Construct)); @@ -3241,16 +3243,16 @@ namespace ts { } function resolveTypeReferenceMembers(type: TypeReference): void { - let source = resolveDeclaredMembers(type.target); - let typeParameters = concatenate(source.typeParameters, [source.thisType]); - let typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? + const source = resolveDeclaredMembers(type.target); + const typeParameters = concatenate(source.typeParameters, [source.thisType]); + const typeArguments = type.typeArguments && type.typeArguments.length === typeParameters.length ? type.typeArguments : concatenate(type.typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, typeArguments); } function createSignature(declaration: SignatureDeclaration, typeParameters: TypeParameter[], parameters: Symbol[], resolvedReturnType: Type, typePredicate: TypePredicate, minArgumentCount: number, hasRestParameter: boolean, hasStringLiterals: boolean): Signature { - let sig = new Signature(checker); + const sig = new Signature(checker); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -3271,16 +3273,16 @@ namespace ts { if (!hasClassBaseType(classType)) { return [createSignature(undefined, classType.localTypeParameters, emptyArray, classType, undefined, 0, false, false)]; } - let baseConstructorType = getBaseConstructorTypeOfClass(classType); - let baseSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct); - let baseTypeNode = getBaseTypeNodeOfClass(classType); - let typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNode); - let typeArgCount = typeArguments ? typeArguments.length : 0; - let result: Signature[] = []; - for (let baseSig of baseSignatures) { - let typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; + const baseConstructorType = getBaseConstructorTypeOfClass(classType); + const baseSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct); + const baseTypeNode = getBaseTypeNodeOfClass(classType); + const typeArguments = map(baseTypeNode.typeArguments, getTypeFromTypeNode); + const typeArgCount = typeArguments ? typeArguments.length : 0; + const result: Signature[] = []; + for (const baseSig of baseSignatures) { + const typeParamCount = baseSig.typeParameters ? baseSig.typeParameters.length : 0; if (typeParamCount === typeArgCount) { - let sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); + const sig = typeParamCount ? getSignatureInstantiation(baseSig, typeArguments) : cloneSignature(baseSig); sig.typeParameters = classType.localTypeParameters; sig.resolvedReturnType = classType; result.push(sig); @@ -3290,9 +3292,9 @@ namespace ts { } function createTupleTypeMemberSymbols(memberTypes: Type[]): SymbolTable { - let members: SymbolTable = {}; + const members: SymbolTable = {}; for (let i = 0; i < memberTypes.length; i++) { - let symbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "" + i); + const symbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "" + i); symbol.type = memberTypes[i]; members[i] = symbol; } @@ -3300,16 +3302,16 @@ namespace ts { } function resolveTupleTypeMembers(type: TupleType) { - let arrayElementType = getUnionType(type.elementTypes, /*noSubtypeReduction*/ true); + const arrayElementType = getUnionType(type.elementTypes, /*noSubtypeReduction*/ true); // Make the tuple type itself the 'this' type by including an extra type argument - let arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); - let members = createTupleTypeMemberSymbols(type.elementTypes); + const arrayType = resolveStructuredTypeMembers(createTypeFromGenericGlobalType(globalArrayType, [arrayElementType, type])); + const members = createTupleTypeMemberSymbols(type.elementTypes); addInheritedMembers(members, arrayType.properties); setObjectTypeMembers(type, members, arrayType.callSignatures, arrayType.constructSignatures, arrayType.stringIndexType, arrayType.numberIndexType); } function findMatchingSignature(signatureList: Signature[], signature: Signature, partialMatch: boolean, ignoreReturnTypes: boolean): Signature { - for (let s of signatureList) { + for (const s of signatureList) { if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) { return s; } @@ -3333,7 +3335,7 @@ namespace ts { let result: Signature[] = undefined; for (let i = 0; i < signatureLists.length; i++) { // Allow matching non-generic signatures to have excess parameters and different return types - let match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreReturnTypes*/ true); + const match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreReturnTypes*/ true); if (!match) { return undefined; } @@ -3349,13 +3351,13 @@ namespace ts { // parameters and may differ in return types. When signatures differ in return types, the resulting return // type is the union of the constituent return types. function getUnionSignatures(types: Type[], kind: SignatureKind): Signature[] { - let signatureLists = map(types, t => getSignaturesOfType(t, kind)); + const signatureLists = map(types, t => getSignaturesOfType(t, kind)); let result: Signature[] = undefined; for (let i = 0; i < signatureLists.length; i++) { - for (let signature of signatureLists[i]) { + for (const signature of signatureLists[i]) { // Only process signatures with parameter lists that aren't already in the result list if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreReturnTypes*/ true)) { - let unionSignatures = findMatchingSignatures(signatureLists, signature, i); + const unionSignatures = findMatchingSignatures(signatureLists, signature, i); if (unionSignatures) { let s = signature; // Union the result types when more than one signature matches @@ -3374,9 +3376,9 @@ namespace ts { } function getUnionIndexType(types: Type[], kind: IndexKind): Type { - let indexTypes: Type[] = []; - for (let type of types) { - let indexType = getIndexTypeOfType(type, kind); + const indexTypes: Type[] = []; + for (const type of types) { + const indexType = getIndexTypeOfType(type, kind); if (!indexType) { return undefined; } @@ -3388,10 +3390,10 @@ namespace ts { function resolveUnionTypeMembers(type: UnionType) { // The members and properties collections are empty for union types. To get all properties of a union // type use getPropertiesOfType (only the language service uses this). - let callSignatures = getUnionSignatures(type.types, SignatureKind.Call); - let constructSignatures = getUnionSignatures(type.types, SignatureKind.Construct); - let stringIndexType = getUnionIndexType(type.types, IndexKind.String); - let numberIndexType = getUnionIndexType(type.types, IndexKind.Number); + const callSignatures = getUnionSignatures(type.types, SignatureKind.Call); + const constructSignatures = getUnionSignatures(type.types, SignatureKind.Construct); + const stringIndexType = getUnionIndexType(type.types, IndexKind.String); + const numberIndexType = getUnionIndexType(type.types, IndexKind.Number); setObjectTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexType, numberIndexType); } @@ -3406,7 +3408,7 @@ namespace ts { let constructSignatures: Signature[] = emptyArray; let stringIndexType: Type = undefined; let numberIndexType: Type = undefined; - for (let t of type.types) { + for (const t of type.types) { callSignatures = concatenate(callSignatures, getSignaturesOfType(t, SignatureKind.Call)); constructSignatures = concatenate(constructSignatures, getSignaturesOfType(t, SignatureKind.Construct)); stringIndexType = intersectTypes(stringIndexType, getIndexTypeOfType(t, IndexKind.String)); @@ -3416,7 +3418,7 @@ namespace ts { } function resolveAnonymousTypeMembers(type: AnonymousType) { - let symbol = type.symbol; + const symbol = type.symbol; let members: SymbolTable; let callSignatures: Signature[]; let constructSignatures: Signature[]; @@ -3449,12 +3451,12 @@ namespace ts { callSignatures = getSignaturesOfSymbol(symbol); } if (symbol.flags & SymbolFlags.Class) { - let classType = getDeclaredTypeOfClassOrInterface(symbol); + const classType = getDeclaredTypeOfClassOrInterface(symbol); constructSignatures = getSignaturesOfSymbol(symbol.members["__constructor"]); if (!constructSignatures.length) { constructSignatures = getDefaultConstructSignatures(classType); } - let baseConstructorType = getBaseConstructorTypeOfClass(classType); + const baseConstructorType = getBaseConstructorTypeOfClass(classType); if (baseConstructorType.flags & TypeFlags.ObjectType) { members = createSymbolTable(getNamedMembers(members)); addInheritedMembers(members, getPropertiesOfObjectType(baseConstructorType)); @@ -3502,9 +3504,9 @@ namespace ts { // return the symbol for that property.Otherwise return undefined. function getPropertyOfObjectType(type: Type, name: string): Symbol { if (type.flags & TypeFlags.ObjectType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); if (hasProperty(resolved.members, name)) { - let symbol = resolved.members[name]; + const symbol = resolved.members[name]; if (symbolIsValue(symbol)) { return symbol; } @@ -3513,8 +3515,8 @@ namespace ts { } function getPropertiesOfUnionOrIntersectionType(type: UnionOrIntersectionType): Symbol[] { - for (let current of type.types) { - for (let prop of getPropertiesOfType(current)) { + for (const current of type.types) { + for (const prop of getPropertiesOfType(current)) { getPropertyOfUnionOrIntersectionType(type, prop.name); } // The properties of a union type are those that are present in all constituent types, so @@ -3561,12 +3563,12 @@ namespace ts { } function createUnionOrIntersectionProperty(containingType: UnionOrIntersectionType, name: string): Symbol { - let types = containingType.types; + const types = containingType.types; let props: Symbol[]; - for (let current of types) { - let type = getApparentType(current); + for (const current of types) { + const type = getApparentType(current); if (type !== unknownType) { - let prop = getPropertyOfType(type, name); + const prop = getPropertyOfType(type, name); if (prop && !(getDeclarationFlagsFromSymbol(prop) & (NodeFlags.Private | NodeFlags.Protected))) { if (!props) { props = [prop]; @@ -3587,15 +3589,15 @@ namespace ts { if (props.length === 1) { return props[0]; } - let propTypes: Type[] = []; - let declarations: Declaration[] = []; - for (let prop of props) { + const propTypes: Type[] = []; + const declarations: Declaration[] = []; + for (const prop of props) { if (prop.declarations) { addRange(declarations, prop.declarations); } propTypes.push(getTypeOfSymbol(prop)); } - let result = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | SymbolFlags.SyntheticProperty, name); + const result = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | SymbolFlags.SyntheticProperty, name); result.containingType = containingType; result.declarations = declarations; result.type = containingType.flags & TypeFlags.Union ? getUnionType(propTypes) : getIntersectionType(propTypes); @@ -3603,11 +3605,11 @@ namespace ts { } function getPropertyOfUnionOrIntersectionType(type: UnionOrIntersectionType, name: string): Symbol { - let properties = type.resolvedProperties || (type.resolvedProperties = {}); + const properties = type.resolvedProperties || (type.resolvedProperties = {}); if (hasProperty(properties, name)) { return properties[name]; } - let property = createUnionOrIntersectionProperty(type, name); + const property = createUnionOrIntersectionProperty(type, name); if (property) { properties[name] = property; } @@ -3620,15 +3622,15 @@ namespace ts { function getPropertyOfType(type: Type, name: string): Symbol { type = getApparentType(type); if (type.flags & TypeFlags.ObjectType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); if (hasProperty(resolved.members, name)) { - let symbol = resolved.members[name]; + const symbol = resolved.members[name]; if (symbolIsValue(symbol)) { return symbol; } } if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) { - let symbol = getPropertyOfObjectType(globalFunctionType, name); + const symbol = getPropertyOfObjectType(globalFunctionType, name); if (symbol) { return symbol; } @@ -3643,7 +3645,7 @@ namespace ts { function getSignaturesOfStructuredType(type: Type, kind: SignatureKind): Signature[] { if (type.flags & TypeFlags.StructuredType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); return kind === SignatureKind.Call ? resolved.callSignatures : resolved.constructSignatures; } return emptyArray; @@ -3658,18 +3660,18 @@ namespace ts { } function typeHasConstructSignatures(type: Type): boolean { - let apparentType = getApparentType(type); + const apparentType = getApparentType(type); if (apparentType.flags & (TypeFlags.ObjectType | TypeFlags.Union)) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); return resolved.constructSignatures.length > 0; } return false; } function typeHasCallOrConstructSignatures(type: Type): boolean { - let apparentType = getApparentType(type); + const apparentType = getApparentType(type); if (apparentType.flags & TypeFlags.StructuredType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); return resolved.callSignatures.length > 0 || resolved.constructSignatures.length > 0; } return false; @@ -3677,7 +3679,7 @@ namespace ts { function getIndexTypeOfStructuredType(type: Type, kind: IndexKind): Type { if (type.flags & TypeFlags.StructuredType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); return kind === IndexKind.String ? resolved.stringIndexType : resolved.numberIndexType; } } @@ -3691,9 +3693,9 @@ namespace ts { // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual // type checking functions). function getTypeParametersFromDeclaration(typeParameterDeclarations: TypeParameterDeclaration[]): TypeParameter[] { - let result: TypeParameter[] = []; + const result: TypeParameter[] = []; forEach(typeParameterDeclarations, node => { - let tp = getDeclaredTypeOfTypeParameter(node.symbol); + const tp = getDeclaredTypeOfTypeParameter(node.symbol); if (!contains(result, tp)) { result.push(tp); } @@ -3702,8 +3704,8 @@ namespace ts { } function symbolsToArray(symbols: SymbolTable): Symbol[] { - let result: Symbol[] = []; - for (let id in symbols) { + const result: Symbol[] = []; + for (const id in symbols) { if (!isReservedMemberName(id)) { result.push(symbols[id]); } @@ -3717,9 +3719,9 @@ namespace ts { } if (node.initializer) { - let signatureDeclaration = node.parent; - let signature = getSignatureFromDeclaration(signatureDeclaration); - let parameterIndex = signatureDeclaration.parameters.indexOf(node); + const signatureDeclaration = node.parent; + const signature = getSignatureFromDeclaration(signatureDeclaration); + const parameterIndex = signatureDeclaration.parameters.indexOf(node); Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -3728,18 +3730,18 @@ namespace ts { } function getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature { - let links = getNodeLinks(declaration); + const links = getNodeLinks(declaration); if (!links.resolvedSignature) { - let classType = declaration.kind === SyntaxKind.Constructor ? + const classType = declaration.kind === SyntaxKind.Constructor ? getDeclaredTypeOfClassOrInterface(getMergedSymbol((declaration.parent).symbol)) : undefined; - let typeParameters = classType ? classType.localTypeParameters : + const typeParameters = classType ? classType.localTypeParameters : declaration.typeParameters ? getTypeParametersFromDeclaration(declaration.typeParameters) : undefined; - let parameters: Symbol[] = []; + const parameters: Symbol[] = []; let hasStringLiterals = false; let minArgumentCount = -1; for (let i = 0, n = declaration.parameters.length; i < n; i++) { - let param = declaration.parameters[i]; + const param = declaration.parameters[i]; parameters.push(param.symbol); if (param.type && param.type.kind === SyntaxKind.StringLiteral) { hasStringLiterals = true; @@ -3768,7 +3770,7 @@ namespace ts { else if (declaration.type) { returnType = getTypeFromTypeNode(declaration.type); if (declaration.type.kind === SyntaxKind.TypePredicate) { - let typePredicateNode = declaration.type; + const typePredicateNode = declaration.type; typePredicate = { parameterName: typePredicateNode.parameterName ? typePredicateNode.parameterName.text : undefined, parameterIndex: typePredicateNode.parameterName ? getTypePredicateParameterIndex(declaration.parameters, typePredicateNode.parameterName) : undefined, @@ -3780,7 +3782,7 @@ namespace ts { // TypeScript 1.0 spec (April 2014): // If only one accessor includes a type annotation, the other behaves as if it had the same type annotation. if (declaration.kind === SyntaxKind.GetAccessor && !hasDynamicName(declaration)) { - let setter = getDeclarationOfKind(declaration.symbol, SyntaxKind.SetAccessor); + const setter = getDeclarationOfKind(declaration.symbol, SyntaxKind.SetAccessor); returnType = getAnnotatedAccessorType(setter); } @@ -3797,9 +3799,9 @@ namespace ts { function getSignaturesOfSymbol(symbol: Symbol): Signature[] { if (!symbol) return emptyArray; - let result: Signature[] = []; + const result: Signature[] = []; for (let i = 0, len = symbol.declarations.length; i < len; i++) { - let node = symbol.declarations[i]; + const node = symbol.declarations[i]; switch (node.kind) { case SyntaxKind.FunctionType: case SyntaxKind.ConstructorType: @@ -3818,7 +3820,7 @@ namespace ts { // an implementation node if it has a body and the previous node is of the same kind and immediately // precedes the implementation node (i.e. has the same parent and ends where the implementation starts). if (i > 0 && (node).body) { - let previous = symbol.declarations[i - 1]; + const previous = symbol.declarations[i - 1]; if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) { break; } @@ -3847,7 +3849,7 @@ namespace ts { if (!popTypeResolution()) { type = anyType; if (compilerOptions.noImplicitAny) { - let declaration = signature.declaration; + const declaration = signature.declaration; if (declaration.name) { error(declaration.name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(declaration.name)); } @@ -3863,7 +3865,7 @@ namespace ts { function getRestTypeOfSignature(signature: Signature): Type { if (signature.hasRestParameter) { - let type = getTypeOfSymbol(lastOrUndefined(signature.parameters)); + const type = getTypeOfSymbol(lastOrUndefined(signature.parameters)); if (type.flags & TypeFlags.Reference && (type).target === globalArrayType) { return (type).typeArguments[0]; } @@ -3894,8 +3896,8 @@ namespace ts { // object type literal or interface (using the new keyword). Each way of declaring a constructor // will result in a different declaration kind. if (!signature.isolatedSignatureType) { - let isConstructor = signature.declaration.kind === SyntaxKind.Constructor || signature.declaration.kind === SyntaxKind.ConstructSignature; - let type = createObjectType(TypeFlags.Anonymous | TypeFlags.FromSignature); + const isConstructor = signature.declaration.kind === SyntaxKind.Constructor || signature.declaration.kind === SyntaxKind.ConstructSignature; + const type = createObjectType(TypeFlags.Anonymous | TypeFlags.FromSignature); type.members = emptySymbols; type.properties = emptyArray; type.callSignatures = !isConstructor ? [signature] : emptyArray; @@ -3911,13 +3913,13 @@ namespace ts { } function getIndexDeclarationOfSymbol(symbol: Symbol, kind: IndexKind): SignatureDeclaration { - let syntaxKind = kind === IndexKind.Number ? SyntaxKind.NumberKeyword : SyntaxKind.StringKeyword; - let indexSymbol = getIndexSymbol(symbol); + const syntaxKind = kind === IndexKind.Number ? SyntaxKind.NumberKeyword : SyntaxKind.StringKeyword; + const indexSymbol = getIndexSymbol(symbol); if (indexSymbol) { - for (let decl of indexSymbol.declarations) { - let node = decl; + for (const decl of indexSymbol.declarations) { + const node = decl; if (node.parameters.length === 1) { - let parameter = node.parameters[0]; + const parameter = node.parameters[0]; if (parameter && parameter.type && parameter.type.kind === syntaxKind) { return node; } @@ -3929,7 +3931,7 @@ namespace ts { } function getIndexTypeOfSymbol(symbol: Symbol, kind: IndexKind): Type { - let declaration = getIndexDeclarationOfSymbol(symbol, kind); + const declaration = getIndexDeclarationOfSymbol(symbol, kind); return declaration ? declaration.type ? getTypeFromTypeNode(declaration.type) : anyType : undefined; @@ -3938,7 +3940,7 @@ namespace ts { function getConstraintOfTypeParameter(type: TypeParameter): Type { if (!type.constraint) { if (type.target) { - let targetConstraint = getConstraintOfTypeParameter(type.target); + const targetConstraint = getConstraintOfTypeParameter(type.target); type.constraint = targetConstraint ? instantiateType(targetConstraint, type.mapper) : noConstraintType; } else { @@ -3979,17 +3981,17 @@ namespace ts { // that care about the presence of such types at arbitrary depth in a containing type. function getPropagatingFlagsOfTypes(types: Type[]): TypeFlags { let result: TypeFlags = 0; - for (let type of types) { + for (const type of types) { result |= type.flags; } return result & TypeFlags.PropagatingFlags; } function createTypeReference(target: GenericType, typeArguments: Type[]): TypeReference { - let id = getTypeListId(typeArguments); + const id = getTypeListId(typeArguments); let type = target.instantiations[id]; if (!type) { - let flags = TypeFlags.Reference | (typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0); + const flags = TypeFlags.Reference | (typeArguments ? getPropagatingFlagsOfTypes(typeArguments) : 0); type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; @@ -3998,7 +4000,7 @@ namespace ts { } function isTypeParameterReferenceIllegalInConstraint(typeReferenceNode: TypeReferenceNode | ExpressionWithTypeArguments, typeParameterSymbol: Symbol): boolean { - let links = getNodeLinks(typeReferenceNode); + const links = getNodeLinks(typeReferenceNode); if (links.isIllegalTypeReferenceInConstraint !== undefined) { return links.isIllegalTypeReferenceInConstraint; } @@ -4018,9 +4020,9 @@ namespace ts { let typeParameterSymbol: Symbol; function check(n: Node): void { if (n.kind === SyntaxKind.TypeReference && (n).typeName.kind === SyntaxKind.Identifier) { - let links = getNodeLinks(n); + const links = getNodeLinks(n); if (links.isIllegalTypeReferenceInConstraint === undefined) { - let symbol = resolveName(typeParameter, ((n).typeName).text, SymbolFlags.Type, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + const symbol = resolveName(typeParameter, ((n).typeName).text, SymbolFlags.Type, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); if (symbol && (symbol.flags & SymbolFlags.TypeParameter)) { // TypeScript 1.0 spec (April 2014): 3.4.1 // Type parameters declared in a particular type parameter list @@ -4048,8 +4050,8 @@ namespace ts { // Get type from reference to class or interface function getTypeFromClassOrInterfaceReference(node: TypeReferenceNode | ExpressionWithTypeArguments, symbol: Symbol): Type { - let type = getDeclaredTypeOfSymbol(symbol); - let typeParameters = type.localTypeParameters; + const type = getDeclaredTypeOfSymbol(symbol); + const typeParameters = type.localTypeParameters; if (typeParameters) { if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { error(node, Diagnostics.Generic_type_0_requires_1_type_argument_s, typeToString(type, /*enclosingDeclaration*/ undefined, TypeFormatFlags.WriteArrayAsGenericType), typeParameters.length); @@ -4071,16 +4073,16 @@ namespace ts { // references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the // declared type. Instantiations are cached using the type identities of the type arguments as the key. function getTypeFromTypeAliasReference(node: TypeReferenceNode | ExpressionWithTypeArguments, symbol: Symbol): Type { - let type = getDeclaredTypeOfSymbol(symbol); - let links = getSymbolLinks(symbol); - let typeParameters = links.typeParameters; + const type = getDeclaredTypeOfSymbol(symbol); + const links = getSymbolLinks(symbol); + const typeParameters = links.typeParameters; if (typeParameters) { if (!node.typeArguments || node.typeArguments.length !== typeParameters.length) { error(node, Diagnostics.Generic_type_0_requires_1_type_argument_s, symbolToString(symbol), typeParameters.length); return unknownType; } - let typeArguments = map(node.typeArguments, getTypeFromTypeNode); - let id = getTypeListId(typeArguments); + const typeArguments = map(node.typeArguments, getTypeFromTypeNode); + const id = getTypeListId(typeArguments); return links.instantiations[id] || (links.instantiations[id] = instantiateType(type, createTypeMapper(typeParameters, typeArguments))); } if (node.typeArguments) { @@ -4107,14 +4109,14 @@ namespace ts { } function getTypeFromTypeReference(node: TypeReferenceNode | ExpressionWithTypeArguments): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { // We only support expressions that are simple qualified names. For other expressions this produces undefined. - let typeNameOrExpression = node.kind === SyntaxKind.TypeReference ? (node).typeName : + const typeNameOrExpression = node.kind === SyntaxKind.TypeReference ? (node).typeName : isSupportedExpressionWithTypeArguments(node) ? (node).expression : undefined; - let symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, SymbolFlags.Type) || unknownSymbol; - let type = symbol === unknownSymbol ? unknownType : + const symbol = typeNameOrExpression && resolveEntityName(typeNameOrExpression, SymbolFlags.Type) || unknownSymbol; + const type = symbol === unknownSymbol ? unknownType : symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface) ? getTypeFromClassOrInterfaceReference(node, symbol) : symbol.flags & SymbolFlags.TypeAlias ? getTypeFromTypeAliasReference(node, symbol) : getTypeFromNonGenericTypeReference(node, symbol); @@ -4127,7 +4129,7 @@ namespace ts { } function getTypeFromTypeQueryNode(node: TypeQueryNode): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { // TypeScript 1.0 spec (April 2014): 3.6.3 // The expression is processed as an identifier expression (section 4.3) @@ -4141,8 +4143,8 @@ namespace ts { function getTypeOfGlobalSymbol(symbol: Symbol, arity: number): ObjectType { function getTypeDeclaration(symbol: Symbol): Declaration { - let declarations = symbol.declarations; - for (let declaration of declarations) { + const declarations = symbol.declarations; + for (const declaration of declarations) { switch (declaration.kind) { case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: @@ -4155,7 +4157,7 @@ namespace ts { if (!symbol) { return arity ? emptyGenericType : emptyObjectType; } - let type = getDeclaredTypeOfSymbol(symbol); + const type = getDeclaredTypeOfSymbol(symbol); if (!(type.flags & TypeFlags.ObjectType)) { error(getTypeDeclaration(symbol), Diagnostics.Global_type_0_must_be_a_class_or_interface_type, symbol.name); return arity ? emptyGenericType : emptyObjectType; @@ -4192,8 +4194,8 @@ namespace ts { * getExportedTypeFromNamespace('JSX', 'Element') returns the JSX.Element type */ function getExportedTypeFromNamespace(namespace: string, name: string): Type { - let namespaceSymbol = getGlobalSymbol(namespace, SymbolFlags.Namespace, /*diagnosticMessage*/ undefined); - let typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, SymbolFlags.Type); + const namespaceSymbol = getGlobalSymbol(namespace, SymbolFlags.Namespace, /*diagnosticMessage*/ undefined); + const typeSymbol = namespaceSymbol && getSymbol(namespaceSymbol.exports, name, SymbolFlags.Type); return typeSymbol && getDeclaredTypeOfSymbol(typeSymbol); } @@ -4205,7 +4207,7 @@ namespace ts { * Creates a TypeReference for a generic `TypedPropertyDescriptor`. */ function createTypedPropertyDescriptorType(propertyType: Type): Type { - let globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType(); + const globalTypedPropertyDescriptorType = getGlobalTypedPropertyDescriptorType(); return globalTypedPropertyDescriptorType !== emptyGenericType ? createTypeReference(globalTypedPropertyDescriptorType, [propertyType]) : emptyObjectType; @@ -4231,7 +4233,7 @@ namespace ts { } function getTypeFromArrayTypeNode(node: ArrayTypeNode): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = createArrayType(getTypeFromTypeNode(node.elementType)); } @@ -4239,18 +4241,18 @@ namespace ts { } function createTupleType(elementTypes: Type[]) { - let id = getTypeListId(elementTypes); + const id = getTypeListId(elementTypes); return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes)); } function createNewTupleType(elementTypes: Type[]) { - let type = createObjectType(TypeFlags.Tuple | getPropagatingFlagsOfTypes(elementTypes)); + const type = createObjectType(TypeFlags.Tuple | getPropagatingFlagsOfTypes(elementTypes)); type.elementTypes = elementTypes; return type; } function getTypeFromTupleTypeNode(node: TupleTypeNode): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = createTupleType(map(node.elementTypes, getTypeFromTypeNode)); } @@ -4269,7 +4271,7 @@ namespace ts { // Add the given types to the given type set. Order is preserved, duplicates are removed, // and nested types of the given kind are flattened into the set. function addTypesToSet(typeSet: Type[], types: Type[], typeSetKind: TypeFlags) { - for (let type of types) { + for (const type of types) { addTypeToSet(typeSet, type, typeSetKind); } } @@ -4294,7 +4296,7 @@ namespace ts { } function containsTypeAny(types: Type[]): boolean { - for (let type of types) { + for (const type of types) { if (isTypeAny(type)) { return true; } @@ -4323,7 +4325,7 @@ namespace ts { if (types.length === 0) { return emptyObjectType; } - let typeSet: Type[] = []; + const typeSet: Type[] = []; addTypesToSet(typeSet, types, TypeFlags.Union); if (containsTypeAny(typeSet)) { return anyType; @@ -4338,7 +4340,7 @@ namespace ts { if (typeSet.length === 1) { return typeSet[0]; } - let id = getTypeListId(typeSet); + const id = getTypeListId(typeSet); let type = unionTypes[id]; if (!type) { type = unionTypes[id] = createObjectType(TypeFlags.Union | getPropagatingFlagsOfTypes(typeSet)); @@ -4348,7 +4350,7 @@ namespace ts { } function getTypeFromUnionTypeNode(node: UnionTypeNode): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = getUnionType(map(node.types, getTypeFromTypeNode), /*noSubtypeReduction*/ true); } @@ -4364,7 +4366,7 @@ namespace ts { if (types.length === 0) { return emptyObjectType; } - let typeSet: Type[] = []; + const typeSet: Type[] = []; addTypesToSet(typeSet, types, TypeFlags.Intersection); if (containsTypeAny(typeSet)) { return anyType; @@ -4372,7 +4374,7 @@ namespace ts { if (typeSet.length === 1) { return typeSet[0]; } - let id = getTypeListId(typeSet); + const id = getTypeListId(typeSet); let type = intersectionTypes[id]; if (!type) { type = intersectionTypes[id] = createObjectType(TypeFlags.Intersection | getPropagatingFlagsOfTypes(typeSet)); @@ -4382,7 +4384,7 @@ namespace ts { } function getTypeFromIntersectionTypeNode(node: IntersectionTypeNode): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = getIntersectionType(map(node.types, getTypeFromTypeNode)); } @@ -4390,7 +4392,7 @@ namespace ts { } function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node: Node): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { // Deferred resolution of members is handled by resolveObjectTypeMembers links.resolvedType = createObjectType(TypeFlags.Anonymous, node.symbol); @@ -4403,13 +4405,13 @@ namespace ts { return stringLiteralTypes[node.text]; } - let type = stringLiteralTypes[node.text] = createType(TypeFlags.StringLiteral); + const type = stringLiteralTypes[node.text] = createType(TypeFlags.StringLiteral); type.text = getTextOfNode(node); return type; } function getTypeFromStringLiteral(node: StringLiteral): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = getStringLiteralType(node); } @@ -4417,10 +4419,11 @@ namespace ts { } function getThisType(node: TypeNode): Type { - let container = getThisContainer(node, /*includeArrowFunctions*/ false); - let parent = container && container.parent; + const container = getThisContainer(node, /*includeArrowFunctions*/ false); + const parent = container && container.parent; if (parent && (isClassLike(parent) || parent.kind === SyntaxKind.InterfaceDeclaration)) { - if (!(container.flags & NodeFlags.Static)) { + if (!(container.flags & NodeFlags.Static) && + (container.kind !== SyntaxKind.Constructor || isNodeDescendentOf(node, (container).body))) { return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType; } } @@ -4429,7 +4432,7 @@ namespace ts { } function getTypeFromThisTypeNode(node: TypeNode): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = getThisType(node); } @@ -4480,7 +4483,7 @@ namespace ts { // Callers should first ensure this by calling isTypeNode case SyntaxKind.Identifier: case SyntaxKind.QualifiedName: - let symbol = getSymbolAtLocation(node); + const symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); default: return unknownType; @@ -4489,8 +4492,8 @@ namespace ts { function instantiateList(items: T[], mapper: TypeMapper, instantiator: (item: T, mapper: TypeMapper) => T): T[] { if (items && items.length) { - let result: T[] = []; - for (let v of items) { + const result: T[] = []; + for (const v of items) { result.push(instantiator(v, mapper)); } return result; @@ -4535,7 +4538,7 @@ namespace ts { case 2: return createBinaryTypeEraser(sources[0], sources[1]); } return t => { - for (let source of sources) { + for (const source of sources) { if (t === source) { return anyType; } @@ -4545,7 +4548,7 @@ namespace ts { } function createInferenceMapper(context: InferenceContext): TypeMapper { - let mapper: TypeMapper = t => { + const mapper: TypeMapper = t => { for (let i = 0; i < context.typeParameters.length; i++) { if (t === context.typeParameters[i]) { context.inferences[i].isFixed = true; @@ -4568,7 +4571,7 @@ namespace ts { } function instantiateTypeParameter(typeParameter: TypeParameter, mapper: TypeMapper): TypeParameter { - let result = createType(TypeFlags.TypeParameter); + const result = createType(TypeFlags.TypeParameter); result.symbol = typeParameter.symbol; if (typeParameter.constraint) { result.constraint = instantiateType(typeParameter.constraint, mapper); @@ -4594,7 +4597,7 @@ namespace ts { type: instantiateType(signature.typePredicate.type, mapper) }; } - let result = createSignature(signature.declaration, freshTypeParameters, + const result = createSignature(signature.declaration, freshTypeParameters, instantiateList(signature.parameters, mapper, instantiateSymbol), instantiateType(signature.resolvedReturnType, mapper), freshTypePredicate, @@ -4606,7 +4609,7 @@ namespace ts { function instantiateSymbol(symbol: Symbol, mapper: TypeMapper): Symbol { if (symbol.flags & SymbolFlags.Instantiated) { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); // If symbol being instantiated is itself a instantiation, fetch the original target and combine the // type mappers. This ensures that original type identities are properly preserved and that aliases // always reference a non-aliases. @@ -4616,7 +4619,7 @@ namespace 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. - let result = createSymbol(SymbolFlags.Instantiated | SymbolFlags.Transient | symbol.flags, symbol.name); + const result = createSymbol(SymbolFlags.Instantiated | SymbolFlags.Transient | symbol.flags, symbol.name); result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -4630,7 +4633,7 @@ namespace ts { function instantiateAnonymousType(type: AnonymousType, mapper: TypeMapper): ObjectType { if (mapper.instantiations) { - let cachedType = mapper.instantiations[type.id]; + const cachedType = mapper.instantiations[type.id]; if (cachedType) { return cachedType; } @@ -4639,7 +4642,7 @@ namespace ts { mapper.instantiations = []; } // Mark the anonymous type as instantiated such that our infinite instantiation detection logic can recognize it - let result = createObjectType(TypeFlags.Anonymous | TypeFlags.Instantiated, type.symbol); + const result = createObjectType(TypeFlags.Anonymous | TypeFlags.Instantiated, type.symbol); result.target = type; result.mapper = mapper; mapper.instantiations[type.id] = result; @@ -4707,9 +4710,9 @@ namespace ts { function getTypeWithoutSignatures(type: Type): Type { if (type.flags & TypeFlags.ObjectType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); if (resolved.constructSignatures.length) { - let result = createObjectType(TypeFlags.Anonymous, type.symbol); + const result = createObjectType(TypeFlags.Anonymous, type.symbol); result.members = resolved.members; result.properties = resolved.properties; result.callSignatures = emptyArray; @@ -4747,8 +4750,8 @@ namespace ts { } function isSignatureAssignableTo(source: Signature, target: Signature): boolean { - let sourceType = getOrCreateTypeFromSignature(source); - let targetType = getOrCreateTypeFromSignature(target); + const sourceType = getOrCreateTypeFromSignature(source); + const targetType = getOrCreateTypeFromSignature(target); return checkTypeRelatedTo(sourceType, targetType, assignableRelation, /*errorNode*/ undefined); } @@ -4781,7 +4784,7 @@ namespace ts { Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking"); - let result = isRelatedTo(source, target, errorNode !== undefined, headMessage); + const result = isRelatedTo(source, target, errorNode !== undefined, headMessage); if (overflow) { error(errorNode, Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } @@ -4855,7 +4858,7 @@ namespace ts { } } - let saveErrorInfo = errorInfo; + const saveErrorInfo = errorInfo; // Note that the "each" checks must precede the "some" checks to produce the correct results if (source.flags & TypeFlags.Union) { @@ -4891,7 +4894,7 @@ namespace ts { constraint = emptyObjectType; } // Report constraint errors only if the constraint is not the empty object type - let reportConstraintErrors = reportErrors && constraint !== emptyObjectType; + const reportConstraintErrors = reportErrors && constraint !== emptyObjectType; if (result = isRelatedTo(constraint, target, reportConstraintErrors)) { errorInfo = saveErrorInfo; return result; @@ -4906,13 +4909,13 @@ namespace ts { } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. - let apparentType = getApparentType(source); + const apparentType = getApparentType(source); // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates // to X. Failing both of those we want to check if the aggregation of A and B's members structurally // relates to X. Thus, we include intersection types on the source side here. if (apparentType.flags & (TypeFlags.ObjectType | TypeFlags.Intersection) && target.flags & TypeFlags.ObjectType) { // Report structural errors only if we haven't reported any errors yet - let reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; + const reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; if (result = objectTypeRelatedTo(apparentType, source, target, reportStructuralErrors)) { errorInfo = saveErrorInfo; return result; @@ -4964,7 +4967,7 @@ namespace ts { } } else if (type.flags & TypeFlags.UnionOrIntersection) { - for (let t of (type).types) { + for (const t of (type).types) { if (isKnownProperty(t, name)) { return true; } @@ -4975,7 +4978,7 @@ namespace ts { function hasExcessProperties(source: FreshObjectLiteralType, target: Type, reportErrors: boolean): boolean { if (someConstituentTypeHasKind(target, TypeFlags.ObjectType)) { - for (let prop of getPropertiesOfObjectType(source)) { + for (const prop of getPropertiesOfObjectType(source)) { if (!isKnownProperty(target, prop.name)) { if (reportErrors) { // We know *exactly* where things went wrong when comparing the types. @@ -4994,9 +4997,9 @@ namespace ts { function eachTypeRelatedToSomeType(source: UnionOrIntersectionType, target: UnionOrIntersectionType): Ternary { let result = Ternary.True; - let sourceTypes = source.types; - for (let sourceType of sourceTypes) { - let related = typeRelatedToSomeType(sourceType, target, false); + const sourceTypes = source.types; + for (const sourceType of sourceTypes) { + const related = typeRelatedToSomeType(sourceType, target, false); if (!related) { return Ternary.False; } @@ -5006,9 +5009,9 @@ namespace ts { } function typeRelatedToSomeType(source: Type, target: UnionOrIntersectionType, reportErrors: boolean): Ternary { - let targetTypes = target.types; + const targetTypes = target.types; for (let i = 0, len = targetTypes.length; i < len; i++) { - let related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); + const related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); if (related) { return related; } @@ -5018,9 +5021,9 @@ namespace ts { function typeRelatedToEachType(source: Type, target: UnionOrIntersectionType, reportErrors: boolean): Ternary { let result = Ternary.True; - let targetTypes = target.types; - for (let targetType of targetTypes) { - let related = isRelatedTo(source, targetType, reportErrors); + const targetTypes = target.types; + for (const targetType of targetTypes) { + const related = isRelatedTo(source, targetType, reportErrors); if (!related) { return Ternary.False; } @@ -5030,9 +5033,9 @@ namespace ts { } function someTypeRelatedToType(source: UnionOrIntersectionType, target: Type, reportErrors: boolean): Ternary { - let sourceTypes = source.types; + const sourceTypes = source.types; for (let i = 0, len = sourceTypes.length; i < len; i++) { - let related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); + const related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1); if (related) { return related; } @@ -5042,9 +5045,9 @@ namespace ts { function eachTypeRelatedToType(source: UnionOrIntersectionType, target: Type, reportErrors: boolean): Ternary { let result = Ternary.True; - let sourceTypes = source.types; - for (let sourceType of sourceTypes) { - let related = isRelatedTo(sourceType, target, reportErrors); + const sourceTypes = source.types; + for (const sourceType of sourceTypes) { + const related = isRelatedTo(sourceType, target, reportErrors); if (!related) { return Ternary.False; } @@ -5054,14 +5057,14 @@ namespace ts { } function typeArgumentsRelatedTo(source: TypeReference, target: TypeReference, reportErrors: boolean): Ternary { - let sources = source.typeArguments || emptyArray; - let targets = target.typeArguments || emptyArray; + const sources = source.typeArguments || emptyArray; + const targets = target.typeArguments || emptyArray; if (sources.length !== targets.length && relation === identityRelation) { return Ternary.False; } let result = Ternary.True; for (let i = 0; i < targets.length; i++) { - let related = isRelatedTo(sources[i], targets[i], reportErrors); + const related = isRelatedTo(sources[i], targets[i], reportErrors); if (!related) { return Ternary.False; } @@ -5093,8 +5096,8 @@ namespace ts { if (overflow) { return Ternary.False; } - let id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; - let related = relation[id]; + const id = relation !== identityRelation || apparentSource.id < target.id ? apparentSource.id + "," + target.id : target.id + "," + apparentSource.id; + const related = relation[id]; if (related !== undefined) { // If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate // errors, we can use the cached value. Otherwise, recompute the relation @@ -5125,7 +5128,7 @@ namespace ts { maybeStack[depth] = {}; maybeStack[depth][id] = RelationComparisonResult.Succeeded; depth++; - let saveExpandingFlags = expandingFlags; + const saveExpandingFlags = expandingFlags; if (!(expandingFlags & 1) && isDeeplyNestedGeneric(apparentSource, sourceStack, depth)) expandingFlags |= 1; if (!(expandingFlags & 2) && isDeeplyNestedGeneric(target, targetStack, depth)) expandingFlags |= 2; let result: Ternary; @@ -5150,9 +5153,9 @@ namespace ts { expandingFlags = saveExpandingFlags; depth--; if (result) { - let maybeCache = maybeStack[depth]; + const maybeCache = maybeStack[depth]; // If result is definitely true, copy assumptions to global cache, else copy to next level up - let destinationCache = (result === Ternary.True || depth === 0) ? relation : maybeStack[depth - 1]; + const destinationCache = (result === Ternary.True || depth === 0) ? relation : maybeStack[depth - 1]; copyMap(maybeCache, destinationCache); } else { @@ -5168,10 +5171,10 @@ namespace ts { return propertiesIdenticalTo(source, target); } let result = Ternary.True; - let properties = getPropertiesOfObjectType(target); - let requireOptionalProperties = relation === subtypeRelation && !(source.flags & TypeFlags.ObjectLiteral); - for (let targetProp of properties) { - let sourceProp = getPropertyOfType(source, targetProp.name); + const properties = getPropertiesOfObjectType(target); + const requireOptionalProperties = relation === subtypeRelation && !(source.flags & TypeFlags.ObjectLiteral); + for (const targetProp of properties) { + const sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { @@ -5183,8 +5186,8 @@ namespace ts { } } else if (!(targetProp.flags & SymbolFlags.Prototype)) { - let sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); - let targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); + const sourcePropFlags = getDeclarationFlagsFromSymbol(sourceProp); + const targetPropFlags = getDeclarationFlagsFromSymbol(targetProp); if (sourcePropFlags & NodeFlags.Private || targetPropFlags & NodeFlags.Private) { if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { @@ -5201,9 +5204,9 @@ namespace ts { } } else if (targetPropFlags & NodeFlags.Protected) { - let sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & SymbolFlags.Class; - let sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; - let targetClass = getDeclaredTypeOfSymbol(targetProp.parent); + const sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & SymbolFlags.Class; + const sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(sourceProp.parent) : undefined; + const targetClass = getDeclaredTypeOfSymbol(targetProp.parent); if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { if (reportErrors) { reportError(Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, @@ -5219,7 +5222,7 @@ namespace ts { } return Ternary.False; } - let related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); + const related = isRelatedTo(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp), reportErrors); if (!related) { if (reportErrors) { reportError(Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp)); @@ -5251,18 +5254,18 @@ namespace ts { if (!(source.flags & TypeFlags.ObjectType && target.flags & TypeFlags.ObjectType)) { return Ternary.False; } - let sourceProperties = getPropertiesOfObjectType(source); - let targetProperties = getPropertiesOfObjectType(target); + const sourceProperties = getPropertiesOfObjectType(source); + const targetProperties = getPropertiesOfObjectType(target); if (sourceProperties.length !== targetProperties.length) { return Ternary.False; } let result = Ternary.True; - for (let sourceProp of sourceProperties) { - let targetProp = getPropertyOfObjectType(target, sourceProp.name); + for (const sourceProp of sourceProperties) { + const targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return Ternary.False; } - let related = compareProperties(sourceProp, targetProp, isRelatedTo); + const related = compareProperties(sourceProp, targetProp, isRelatedTo); if (!related) { return Ternary.False; } @@ -5278,10 +5281,10 @@ namespace ts { if (target === anyFunctionType || source === anyFunctionType) { return Ternary.True; } - let sourceSignatures = getSignaturesOfType(source, kind); - let targetSignatures = getSignaturesOfType(target, kind); + const sourceSignatures = getSignaturesOfType(source, kind); + const targetSignatures = getSignaturesOfType(target, kind); let result = Ternary.True; - let saveErrorInfo = errorInfo; + const saveErrorInfo = errorInfo; @@ -5295,8 +5298,8 @@ namespace ts { // sourceSig and targetSig are (possibly) undefined. // // Note that in an extends-clause, targetSignatures is stripped, so the check never proceeds. - let sourceSig = sourceSignatures[0]; - let targetSig = targetSignatures[0]; + const sourceSig = sourceSignatures[0]; + const targetSig = targetSignatures[0]; result &= abstractSignatureRelatedTo(source, sourceSig, target, targetSig); if (result !== Ternary.True) { @@ -5304,13 +5307,13 @@ namespace ts { } } - outer: for (let t of targetSignatures) { + outer: for (const t of targetSignatures) { if (!t.hasStringLiterals || target.flags & TypeFlags.FromSignature) { let localErrors = reportErrors; - let checkedAbstractAssignability = false; - for (let s of sourceSignatures) { + const checkedAbstractAssignability = false; + for (const s of sourceSignatures) { if (!s.hasStringLiterals || source.flags & TypeFlags.FromSignature) { - let related = signatureRelatedTo(s, t, localErrors); + const related = signatureRelatedTo(s, t, localErrors); if (related) { result &= related; errorInfo = saveErrorInfo; @@ -5328,8 +5331,8 @@ namespace ts { function abstractSignatureRelatedTo(source: Type, sourceSig: Signature, target: Type, targetSig: Signature) { if (sourceSig && targetSig) { - let sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); - let targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); + const sourceDecl = source.symbol && getClassLikeDeclarationOfSymbol(source.symbol); + const targetDecl = target.symbol && getClassLikeDeclarationOfSymbol(target.symbol); if (!sourceDecl) { // If the source object isn't itself a class declaration, it can be freely assigned, regardless @@ -5337,16 +5340,16 @@ namespace ts { return Ternary.True; } - let sourceErasedSignature = getErasedSignature(sourceSig); - let targetErasedSignature = getErasedSignature(targetSig); + const sourceErasedSignature = getErasedSignature(sourceSig); + const targetErasedSignature = getErasedSignature(targetSig); - let sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); - let targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); + const sourceReturnType = sourceErasedSignature && getReturnTypeOfSignature(sourceErasedSignature); + const targetReturnType = targetErasedSignature && getReturnTypeOfSignature(targetErasedSignature); - let sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); - let targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); - let sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & NodeFlags.Abstract; - let targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & NodeFlags.Abstract; + const sourceReturnDecl = sourceReturnType && sourceReturnType.symbol && getClassLikeDeclarationOfSymbol(sourceReturnType.symbol); + const targetReturnDecl = targetReturnType && targetReturnType.symbol && getClassLikeDeclarationOfSymbol(targetReturnType.symbol); + const sourceIsAbstract = sourceReturnDecl && sourceReturnDecl.flags & NodeFlags.Abstract; + const targetIsAbstract = targetReturnDecl && targetReturnDecl.flags & NodeFlags.Abstract; if (sourceIsAbstract && !(targetIsAbstract && targetDecl)) { // if target isn't a class-declaration type, then it can be new'd, so we forbid the assignment. @@ -5392,9 +5395,9 @@ namespace ts { target = getErasedSignature(target); let result = Ternary.True; for (let i = 0; i < checkCount; i++) { - let s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - let t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); - let saveErrorInfo = errorInfo; + const s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + const t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + const saveErrorInfo = errorInfo; let related = isRelatedTo(s, t, reportErrors); if (!related) { related = isRelatedTo(t, s, false); @@ -5412,16 +5415,16 @@ namespace ts { } if (source.typePredicate && target.typePredicate) { - let hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; + const hasDifferentParameterIndex = source.typePredicate.parameterIndex !== target.typePredicate.parameterIndex; let hasDifferentTypes: boolean; if (hasDifferentParameterIndex || (hasDifferentTypes = !isTypeIdenticalTo(source.typePredicate.type, target.typePredicate.type))) { if (reportErrors) { - let sourceParamText = source.typePredicate.parameterName; - let targetParamText = target.typePredicate.parameterName; - let sourceTypeText = typeToString(source.typePredicate.type); - let targetTypeText = typeToString(target.typePredicate.type); + const sourceParamText = source.typePredicate.parameterName; + const targetParamText = target.typePredicate.parameterName; + const sourceTypeText = typeToString(source.typePredicate.type); + const targetTypeText = typeToString(target.typePredicate.type); if (hasDifferentParameterIndex) { reportError(Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, @@ -5448,22 +5451,22 @@ namespace ts { return Ternary.False; } - let targetReturnType = getReturnTypeOfSignature(target); + const targetReturnType = getReturnTypeOfSignature(target); if (targetReturnType === voidType) return result; - let sourceReturnType = getReturnTypeOfSignature(source); + const sourceReturnType = getReturnTypeOfSignature(source); return result & isRelatedTo(sourceReturnType, targetReturnType, reportErrors); } function signaturesIdenticalTo(source: Type, target: Type, kind: SignatureKind): Ternary { - let sourceSignatures = getSignaturesOfType(source, kind); - let targetSignatures = getSignaturesOfType(target, kind); + const sourceSignatures = getSignaturesOfType(source, kind); + const targetSignatures = getSignaturesOfType(target, kind); if (sourceSignatures.length !== targetSignatures.length) { return Ternary.False; } let result = Ternary.True; for (let i = 0, len = sourceSignatures.length; i < len; ++i) { - let related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); + const related = compareSignatures(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreReturnTypes*/ false, isRelatedTo); if (!related) { return Ternary.False; } @@ -5476,21 +5479,21 @@ namespace ts { if (relation === identityRelation) { return indexTypesIdenticalTo(IndexKind.String, source, target); } - let targetType = getIndexTypeOfType(target, IndexKind.String); + const targetType = getIndexTypeOfType(target, IndexKind.String); if (targetType) { if ((targetType.flags & TypeFlags.Any) && !(originalSource.flags & TypeFlags.Primitive)) { // non-primitive assignment to any is always allowed, eg // `var x: { [index: string]: any } = { property: 12 };` return Ternary.True; } - let sourceType = getIndexTypeOfType(source, IndexKind.String); + const sourceType = getIndexTypeOfType(source, IndexKind.String); if (!sourceType) { if (reportErrors) { reportError(Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); } return Ternary.False; } - let related = isRelatedTo(sourceType, targetType, reportErrors); + const related = isRelatedTo(sourceType, targetType, reportErrors); if (!related) { if (reportErrors) { reportError(Diagnostics.Index_signatures_are_incompatible); @@ -5506,15 +5509,15 @@ namespace ts { if (relation === identityRelation) { return indexTypesIdenticalTo(IndexKind.Number, source, target); } - let targetType = getIndexTypeOfType(target, IndexKind.Number); + const targetType = getIndexTypeOfType(target, IndexKind.Number); if (targetType) { if ((targetType.flags & TypeFlags.Any) && !(originalSource.flags & TypeFlags.Primitive)) { // non-primitive assignment to any is always allowed, eg // `var x: { [index: number]: any } = { property: 12 };` return Ternary.True; } - let sourceStringType = getIndexTypeOfType(source, IndexKind.String); - let sourceNumberType = getIndexTypeOfType(source, IndexKind.Number); + const sourceStringType = getIndexTypeOfType(source, IndexKind.String); + const sourceNumberType = getIndexTypeOfType(source, IndexKind.Number); if (!(sourceStringType || sourceNumberType)) { if (reportErrors) { reportError(Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source)); @@ -5541,8 +5544,8 @@ namespace ts { } function indexTypesIdenticalTo(indexKind: IndexKind, source: Type, target: Type): Ternary { - let targetType = getIndexTypeOfType(target, indexKind); - let sourceType = getIndexTypeOfType(source, indexKind); + const targetType = getIndexTypeOfType(target, indexKind); + const sourceType = getIndexTypeOfType(source, indexKind); if (!sourceType && !targetType) { return Ternary.True; } @@ -5561,10 +5564,10 @@ namespace ts { function isDeeplyNestedGeneric(type: Type, stack: Type[], depth: number): boolean { // We track type references (created by createTypeReference) and instantiated types (created by instantiateType) if (type.flags & (TypeFlags.Reference | TypeFlags.Instantiated) && depth >= 5) { - let symbol = type.symbol; + const symbol = type.symbol; let count = 0; for (let i = 0; i < depth; i++) { - let t = stack[i]; + const t = stack[i]; if (t.flags & (TypeFlags.Reference | TypeFlags.Instantiated) && t.symbol === symbol) { count++; if (count >= 5) return true; @@ -5585,8 +5588,8 @@ namespace ts { if (sourceProp === targetProp) { return Ternary.True; } - let sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (NodeFlags.Private | NodeFlags.Protected); - let targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (NodeFlags.Private | NodeFlags.Protected); + const sourcePropAccessibility = getDeclarationFlagsFromSymbol(sourceProp) & (NodeFlags.Private | NodeFlags.Protected); + const targetPropAccessibility = getDeclarationFlagsFromSymbol(targetProp) & (NodeFlags.Private | NodeFlags.Protected); if (sourcePropAccessibility !== targetPropAccessibility) { return Ternary.False; } @@ -5603,18 +5606,31 @@ namespace ts { return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } + function isMatchingSignature(source: Signature, target: Signature, partialMatch: boolean) { + // A source signature matches a target signature if the two signatures have the same number of required, + // optional, and rest parameters. + if (source.parameters.length === target.parameters.length && + source.minArgumentCount === target.minArgumentCount && + source.hasRestParameter === target.hasRestParameter) { + return true; + } + // A source signature partially matches a target signature if the target signature has no fewer required + // parameters and no more overall parameters than the source signature (where a signature with a rest + // parameter is always considered to have more overall parameters than one without). + if (partialMatch && source.minArgumentCount <= target.minArgumentCount && ( + source.hasRestParameter && !target.hasRestParameter || + source.hasRestParameter === target.hasRestParameter && source.parameters.length >= target.parameters.length)) { + return true; + } + return false; + } + function compareSignatures(source: Signature, target: Signature, partialMatch: boolean, ignoreReturnTypes: boolean, compareTypes: (s: Type, t: Type) => Ternary): Ternary { if (source === target) { return Ternary.True; } - if (source.parameters.length !== target.parameters.length || - source.minArgumentCount !== target.minArgumentCount || - source.hasRestParameter !== target.hasRestParameter) { - if (!partialMatch || - source.parameters.length < target.parameters.length && !source.hasRestParameter || - source.minArgumentCount > target.minArgumentCount) { - return Ternary.False; - } + if (!(isMatchingSignature(source, target, partialMatch))) { + return Ternary.False; } let result = Ternary.True; if (source.typeParameters && target.typeParameters) { @@ -5622,7 +5638,7 @@ namespace ts { return Ternary.False; } for (let i = 0, len = source.typeParameters.length; i < len; ++i) { - let related = compareTypes(source.typeParameters[i], target.typeParameters[i]); + const related = compareTypes(source.typeParameters[i], target.typeParameters[i]); if (!related) { return Ternary.False; } @@ -5636,11 +5652,11 @@ namespace ts { // M and N (the signatures) are instantiated using type Any as the type argument for all type parameters declared by M and N source = getErasedSignature(source); target = getErasedSignature(target); - let targetLen = target.parameters.length; + const targetLen = target.parameters.length; for (let i = 0; i < targetLen; i++) { - let s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); - let t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfSymbol(target.parameters[i]); - let related = compareTypes(s, t); + const s = isRestParameterIndex(source, i) ? getRestTypeOfSignature(source) : getTypeOfSymbol(source.parameters[i]); + const t = isRestParameterIndex(target, i) ? getRestTypeOfSignature(target) : getTypeOfSymbol(target.parameters[i]); + const related = compareTypes(s, t); if (!related) { return Ternary.False; } @@ -5657,7 +5673,7 @@ namespace ts { } function isSupertypeOfEach(candidate: Type, types: Type[]): boolean { - for (let type of types) { + for (const type of types) { if (candidate !== type && !isTypeSubtypeOf(type, candidate)) return false; } return true; @@ -5749,13 +5765,13 @@ namespace ts { } function getWidenedTypeOfObjectLiteral(type: Type): Type { - let properties = getPropertiesOfObjectType(type); - let members: SymbolTable = {}; + const properties = getPropertiesOfObjectType(type); + const members: SymbolTable = {}; forEach(properties, p => { - let propType = getTypeOfSymbol(p); - let widenedType = getWidenedType(propType); + const propType = getTypeOfSymbol(p); + const widenedType = getWidenedType(propType); if (propType !== widenedType) { - let symbol = createSymbol(p.flags | SymbolFlags.Transient, p.name); + const symbol = createSymbol(p.flags | SymbolFlags.Transient, p.name); symbol.declarations = p.declarations; symbol.parent = p.parent; symbol.type = widenedType; @@ -5807,7 +5823,7 @@ namespace ts { function reportWideningErrorsInType(type: Type): boolean { let errorReported = false; if (type.flags & TypeFlags.Union) { - for (let t of (type).types) { + for (const t of (type).types) { if (reportWideningErrorsInType(t)) { errorReported = true; } @@ -5817,15 +5833,15 @@ namespace ts { return reportWideningErrorsInType((type).typeArguments[0]); } if (isTupleType(type)) { - for (let t of type.elementTypes) { + for (const t of type.elementTypes) { if (reportWideningErrorsInType(t)) { errorReported = true; } } } if (type.flags & TypeFlags.ObjectLiteral) { - for (let p of getPropertiesOfObjectType(type)) { - let t = getTypeOfSymbol(p); + for (const p of getPropertiesOfObjectType(type)) { + const t = getTypeOfSymbol(p); if (t.flags & TypeFlags.ContainsUndefinedOrNull) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); @@ -5838,7 +5854,7 @@ namespace ts { } function reportImplicitAnyError(declaration: Declaration, type: Type) { - let typeAsString = typeToString(getWidenedType(type)); + const typeAsString = typeToString(getWidenedType(type)); let diagnostic: DiagnosticMessage; switch (declaration.kind) { case SyntaxKind.PropertyDeclaration: @@ -5899,15 +5915,15 @@ namespace ts { count = sourceMax < targetMax ? sourceMax : targetMax; } for (let i = 0; i < count; i++) { - let s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); - let t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); + const s = i < sourceMax ? getTypeOfSymbol(source.parameters[i]) : getRestTypeOfSignature(source); + const t = i < targetMax ? getTypeOfSymbol(target.parameters[i]) : getRestTypeOfSignature(target); callback(s, t); } } function createInferenceContext(typeParameters: TypeParameter[], inferUnionTypes: boolean): InferenceContext { - let inferences: TypeInferences[] = []; - for (let unused of typeParameters) { + const inferences: TypeInferences[] = []; + for (const unused of typeParameters) { inferences.push({ primary: undefined, secondary: undefined, isFixed: false }); @@ -5948,10 +5964,10 @@ namespace ts { return; } - let typeParameters = context.typeParameters; + const typeParameters = context.typeParameters; for (let i = 0; i < typeParameters.length; i++) { if (target === typeParameters[i]) { - let inferences = context.inferences[i]; + const inferences = context.inferences[i]; if (!inferences.isFixed) { // Any inferences that are made to a type parameter in a union type are inferior // to inferences made to a flat (non-union) type. This is because if we infer to @@ -5959,7 +5975,7 @@ namespace ts { // the correct constituent on the target side could be string[]). Therefore, we put // such inferior inferences into a secondary bucket, and only use them if the primary // bucket is empty. - let candidates = inferiority ? + const candidates = inferiority ? inferences.secondary || (inferences.secondary = []) : inferences.primary || (inferences.primary = []); if (!contains(candidates, source)) { @@ -5972,27 +5988,27 @@ namespace ts { } else if (source.flags & TypeFlags.Reference && target.flags & TypeFlags.Reference && (source).target === (target).target) { // If source and target are references to the same generic type, infer from type arguments - let sourceTypes = (source).typeArguments || emptyArray; - let targetTypes = (target).typeArguments || emptyArray; - let count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; + const sourceTypes = (source).typeArguments || emptyArray; + const targetTypes = (target).typeArguments || emptyArray; + const count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length; for (let i = 0; i < count; i++) { inferFromTypes(sourceTypes[i], targetTypes[i]); } } else if (source.flags & TypeFlags.Tuple && target.flags & TypeFlags.Tuple && (source).elementTypes.length === (target).elementTypes.length) { // If source and target are tuples of the same size, infer from element types - let sourceTypes = (source).elementTypes; - let targetTypes = (target).elementTypes; + const sourceTypes = (source).elementTypes; + const targetTypes = (target).elementTypes; for (let i = 0; i < sourceTypes.length; i++) { inferFromTypes(sourceTypes[i], targetTypes[i]); } } else if (target.flags & TypeFlags.UnionOrIntersection) { - let targetTypes = (target).types; + const targetTypes = (target).types; let typeParameterCount = 0; let typeParameter: TypeParameter; // First infer to each type in union or intersection that isn't a type parameter - for (let t of targetTypes) { + for (const t of targetTypes) { if (t.flags & TypeFlags.TypeParameter && contains(context.typeParameters, t)) { typeParameter = t; typeParameterCount++; @@ -6013,8 +6029,8 @@ namespace ts { } else if (source.flags & TypeFlags.UnionOrIntersection) { // Source is a union or intersection type, infer from each consituent type - let sourceTypes = (source).types; - for (let sourceType of sourceTypes) { + const sourceTypes = (source).types; + for (const sourceType of sourceTypes) { inferFromTypes(sourceType, target); } } @@ -6049,9 +6065,9 @@ namespace ts { } function inferFromProperties(source: Type, target: Type) { - let properties = getPropertiesOfObjectType(target); - for (let targetProp of properties) { - let sourceProp = getPropertyOfObjectType(source, targetProp.name); + const properties = getPropertiesOfObjectType(target); + for (const targetProp of properties) { + const sourceProp = getPropertyOfObjectType(source, targetProp.name); if (sourceProp) { inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp)); } @@ -6059,11 +6075,11 @@ namespace ts { } function inferFromSignatures(source: Type, target: Type, kind: SignatureKind) { - let sourceSignatures = getSignaturesOfType(source, kind); - let targetSignatures = getSignaturesOfType(target, kind); - let sourceLen = sourceSignatures.length; - let targetLen = targetSignatures.length; - let len = sourceLen < targetLen ? sourceLen : targetLen; + const sourceSignatures = getSignaturesOfType(source, kind); + const targetSignatures = getSignaturesOfType(target, kind); + const sourceLen = sourceSignatures.length; + const targetLen = targetSignatures.length; + const len = sourceLen < targetLen ? sourceLen : targetLen; for (let i = 0; i < len; i++) { inferFromSignature(getErasedSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i])); } @@ -6085,9 +6101,9 @@ namespace ts { } function inferFromIndexTypes(source: Type, target: Type, sourceKind: IndexKind, targetKind: IndexKind) { - let targetIndexType = getIndexTypeOfType(target, targetKind); + const targetIndexType = getIndexTypeOfType(target, targetKind); if (targetIndexType) { - let sourceIndexType = getIndexTypeOfType(source, sourceKind); + const sourceIndexType = getIndexTypeOfType(source, sourceKind); if (sourceIndexType) { inferFromTypes(sourceIndexType, targetIndexType); } @@ -6096,7 +6112,7 @@ namespace ts { } function getInferenceCandidates(context: InferenceContext, index: number): Type[] { - let inferences = context.inferences[index]; + const inferences = context.inferences[index]; return inferences.primary || inferences.secondary || emptyArray; } @@ -6104,10 +6120,10 @@ namespace ts { let inferredType = context.inferredTypes[index]; let inferenceSucceeded: boolean; if (!inferredType) { - let inferences = getInferenceCandidates(context, index); + const inferences = getInferenceCandidates(context, index); if (inferences.length) { // Infer widened union or supertype, or the unknown type for no common supertype - let unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); + const unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences); inferredType = unionOrSuperType ? getWidenedType(unionOrSuperType) : unknownType; inferenceSucceeded = !!unionOrSuperType; } @@ -6122,7 +6138,7 @@ namespace ts { // Only do the constraint check if inference succeeded (to prevent cascading errors) if (inferenceSucceeded) { - let constraint = getConstraintOfTypeParameter(context.typeParameters[index]); + const constraint = getConstraintOfTypeParameter(context.typeParameters[index]); inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType; } else if (context.failedTypeParameterIndex === undefined || context.failedTypeParameterIndex > index) { @@ -6151,7 +6167,7 @@ namespace ts { // EXPRESSION TYPE CHECKING function getResolvedSymbol(node: Identifier): Symbol { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedSymbol) { links.resolvedSymbol = (!nodeIsMissing(node) && resolveName(node, node.text, SymbolFlags.Value | SymbolFlags.ExportValue, Diagnostics.Cannot_find_name_0, node)) || unknownSymbol; } @@ -6181,10 +6197,10 @@ namespace ts { // or not of the given type kind (when isOfTypeKind is false) function removeTypesFromUnionType(type: Type, typeKind: TypeFlags, isOfTypeKind: boolean, allowEmptyUnionResult: boolean): Type { if (type.flags & TypeFlags.Union) { - let types = (type).types; + const types = (type).types; if (forEach(types, t => !!(t.flags & typeKind) === isOfTypeKind)) { // Above we checked if we have anything to remove, now use the opposite test to do the removal - let narrowedType = getUnionType(filter(types, t => !(t.flags & typeKind) === isOfTypeKind)); + const narrowedType = getUnionType(filter(types, t => !(t.flags & typeKind) === isOfTypeKind)); if (allowEmptyUnionResult || narrowedType !== emptyObjectType) { return narrowedType; } @@ -6204,9 +6220,9 @@ namespace ts { // Check if a given variable is assigned within a given syntax node function isVariableAssignedWithin(symbol: Symbol, node: Node): boolean { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (links.assignmentChecks) { - let cachedResult = links.assignmentChecks[symbol.id]; + const cachedResult = links.assignmentChecks[symbol.id]; if (cachedResult !== undefined) { return cachedResult; } @@ -6300,7 +6316,7 @@ namespace ts { if (node && symbol.flags & SymbolFlags.Variable) { if (isTypeAny(type) || type.flags & (TypeFlags.ObjectType | TypeFlags.Union | TypeFlags.TypeParameter)) { loop: while (node.parent) { - let child = node; + const child = node; node = node.parent; let narrowedType = type; switch (node.kind) { @@ -6356,12 +6372,12 @@ namespace ts { if (expr.left.kind !== SyntaxKind.TypeOfExpression || expr.right.kind !== SyntaxKind.StringLiteral) { return type; } - let left = expr.left; - let right = expr.right; + const left = expr.left; + const right = expr.right; if (left.expression.kind !== SyntaxKind.Identifier || getResolvedSymbol(left.expression) !== symbol) { return type; } - let typeInfo = primitiveTypeInfo[right.text]; + const typeInfo = primitiveTypeInfo[right.text]; if (expr.operatorToken.kind === SyntaxKind.ExclamationEqualsEqualsToken) { assumeTrue = !assumeTrue; } @@ -6425,16 +6441,16 @@ namespace ts { return type; } // Check that right operand is a function type with a prototype property - let rightType = checkExpression(expr.right); + const rightType = checkExpression(expr.right); if (!isTypeSubtypeOf(rightType, globalFunctionType)) { return type; } let targetType: Type; - let prototypeProperty = getPropertyOfType(rightType, "prototype"); + const prototypeProperty = getPropertyOfType(rightType, "prototype"); if (prototypeProperty) { // Target type is type of the prototype property - let prototypePropertyType = getTypeOfSymbol(prototypeProperty); + const prototypePropertyType = getTypeOfSymbol(prototypeProperty); if (!isTypeAny(prototypePropertyType)) { targetType = prototypePropertyType; } @@ -6465,7 +6481,7 @@ namespace ts { // If the current type is a union type, remove all constituents that aren't assignable to target. If that produces // 0 candidates, fall back to the assignability check if (originalType.flags & TypeFlags.Union) { - let assignableConstituents = filter((originalType).types, t => isTypeAssignableTo(t, narrowedTypeCandidate)); + const assignableConstituents = filter((originalType).types, t => isTypeAssignableTo(t, narrowedTypeCandidate)); if (assignableConstituents.length) { return getUnionType(assignableConstituents); } @@ -6483,7 +6499,7 @@ namespace ts { if (type.flags & TypeFlags.Any) { return type; } - let signature = getResolvedSignature(expr); + const signature = getResolvedSignature(expr); if (signature.typePredicate && expr.arguments[signature.typePredicate.parameterIndex] && @@ -6509,7 +6525,7 @@ namespace ts { case SyntaxKind.ParenthesizedExpression: return narrowType(type, (expr).expression, assumeTrue); case SyntaxKind.BinaryExpression: - let operator = (expr).operatorToken.kind; + const operator = (expr).operatorToken.kind; if (operator === SyntaxKind.EqualsEqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) { return narrowTypeByEquality(type, expr, assumeTrue); } @@ -6534,7 +6550,7 @@ namespace ts { } function checkIdentifier(node: Identifier): Type { - let symbol = getResolvedSymbol(node); + const symbol = getResolvedSymbol(node); // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. // Although in down-level emit of arrow function, we emit it using function expression which means that @@ -6543,7 +6559,7 @@ namespace ts { // To avoid that we will give an error to users if they use arguments objects in arrow function so that they // can explicitly bound arguments objects if (symbol === argumentsSymbol) { - let container = getContainingFunction(node); + const container = getContainingFunction(node); if (container.kind === SyntaxKind.ArrowFunction) { if (languageVersion < ScriptTarget.ES6) { error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression); @@ -6611,7 +6627,7 @@ namespace ts { } } - let inFunction = isInsideFunction(node.parent, container); + const inFunction = isInsideFunction(node.parent, container); let current = container; while (current && !nodeStartsNewLexicalEnvironment(current)) { @@ -6630,7 +6646,7 @@ namespace ts { function captureLexicalThis(node: Node, container: Node): void { getNodeLinks(node).flags |= NodeCheckFlags.LexicalThis; if (container.kind === SyntaxKind.PropertyDeclaration || container.kind === SyntaxKind.Constructor) { - let classNode = container.parent; + const classNode = container.parent; getNodeLinks(classNode).flags |= NodeCheckFlags.CaptureThis; } else { @@ -6684,7 +6700,7 @@ namespace ts { } if (isClassLike(container.parent)) { - let symbol = getSymbolOfNode(container.parent); + const symbol = getSymbolOfNode(container.parent); return container.flags & NodeFlags.Static ? getTypeOfSymbol(symbol) : (getDeclaredTypeOfSymbol(symbol)).thisType; } return anyType; @@ -6700,10 +6716,10 @@ namespace ts { } function checkSuperExpression(node: Node): Type { - let isCallExpression = node.parent.kind === SyntaxKind.CallExpression && (node.parent).expression === node; - let classDeclaration = getContainingClass(node); - let classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); - let baseClassType = classType && getBaseTypes(classType)[0]; + const isCallExpression = node.parent.kind === SyntaxKind.CallExpression && (node.parent).expression === node; + const classDeclaration = getContainingClass(node); + const classType = classDeclaration && getDeclaredTypeOfSymbol(getSymbolOfNode(classDeclaration)); + const baseClassType = classType && getBaseTypes(classType)[0]; let container = getSuperContainer(node, /*includeFunctions*/ true); let needToCaptureLexicalThis = false; @@ -6716,7 +6732,7 @@ namespace ts { } } - let canUseSuperExpression = isLegalUsageOfSuperExpression(container); + const canUseSuperExpression = isLegalUsageOfSuperExpression(container); let nodeCheckFlag: NodeCheckFlags = 0; // always set NodeCheckFlags for 'super' expression node @@ -6811,15 +6827,15 @@ namespace ts { // Return contextual type of parameter or undefined if no contextual type is available function getContextuallyTypedParameterType(parameter: ParameterDeclaration): Type { - let func = parameter.parent; + const func = parameter.parent; if (isFunctionExpressionOrArrowFunction(func) || isObjectLiteralMethod(func)) { if (isContextSensitive(func)) { - let contextualSignature = getContextualSignature(func); + const contextualSignature = getContextualSignature(func); if (contextualSignature) { - let funcHasRestParameters = hasRestParameter(func); - let len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - let indexOfParameter = indexOf(func.parameters, parameter); + const funcHasRestParameters = hasRestParameter(func); + const len = func.parameters.length - (funcHasRestParameters ? 1 : 0); + const indexOfParameter = indexOf(func.parameters, parameter); if (indexOfParameter < len) { return getTypeAtPosition(contextualSignature, indexOfParameter); } @@ -6842,13 +6858,13 @@ namespace ts { // of the parameter. Otherwise, in a variable or parameter declaration with a binding pattern name, the contextual // type of an initializer expression is the type implied by the binding pattern. function getContextualTypeForInitializerExpression(node: Expression): Type { - let declaration = node.parent; + const declaration = node.parent; if (node === declaration.initializer) { if (declaration.type) { return getTypeFromTypeNode(declaration.type); } if (declaration.kind === SyntaxKind.Parameter) { - let type = getContextuallyTypedParameterType(declaration); + const type = getContextuallyTypedParameterType(declaration); if (type) { return type; } @@ -6861,7 +6877,7 @@ namespace ts { } function getContextualTypeForReturnExpression(node: Expression): Type { - let func = getContainingFunction(node); + const func = getContainingFunction(node); if (func && !func.asteriskToken) { return getContextualReturnType(func); } @@ -6870,9 +6886,9 @@ namespace ts { } function getContextualTypeForYieldOperand(node: YieldExpression): Type { - let func = getContainingFunction(node); + const func = getContainingFunction(node); if (func) { - let contextualReturnType = getContextualReturnType(func); + const contextualReturnType = getContextualReturnType(func); if (contextualReturnType) { return node.asteriskToken ? contextualReturnType @@ -6906,7 +6922,7 @@ namespace ts { // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature // and that call signature is non-generic, return statements are contextually typed by the return type of the signature - let signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); + const signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl); if (signature) { return getReturnTypeOfSignature(signature); } @@ -6916,10 +6932,10 @@ namespace ts { // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget: CallLikeExpression, arg: Expression): Type { - let args = getEffectiveCallArguments(callTarget); - let argIndex = indexOf(args, arg); + const args = getEffectiveCallArguments(callTarget); + const argIndex = indexOf(args, arg); if (argIndex >= 0) { - let signature = getResolvedSignature(callTarget); + const signature = getResolvedSignature(callTarget); return getTypeAtPosition(signature, argIndex); } return undefined; @@ -6934,8 +6950,8 @@ namespace ts { } function getContextualTypeForBinaryOperand(node: Expression): Type { - let binaryExpression = node.parent; - let operator = binaryExpression.operatorToken.kind; + const binaryExpression = node.parent; + const operator = binaryExpression.operatorToken.kind; if (operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment) { // In an assignment expression, the right operand is contextually typed by the type of the left operand. if (node === binaryExpression.right) { @@ -6961,11 +6977,11 @@ namespace ts { if (!(type.flags & TypeFlags.Union)) { return mapper(type); } - let types = (type).types; + const types = (type).types; let mappedType: Type; let mappedTypes: Type[]; - for (let current of types) { - let t = mapper(current); + for (const current of types) { + const t = mapper(current); if (t) { if (!mappedType) { mappedType = t; @@ -6983,7 +6999,7 @@ namespace ts { function getTypeOfPropertyOfContextualType(type: Type, name: string) { return applyToContextualType(type, t => { - let prop = t.flags & TypeFlags.StructuredType ? getPropertyOfType(t, name) : undefined; + const prop = t.flags & TypeFlags.StructuredType ? getPropertyOfType(t, name) : undefined; return prop ? getTypeOfSymbol(prop) : undefined; }); } @@ -7016,15 +7032,15 @@ namespace ts { } function getContextualTypeForObjectLiteralElement(element: ObjectLiteralElement) { - let objectLiteral = element.parent; - let type = getContextualType(objectLiteral); + const objectLiteral = element.parent; + const type = getContextualType(objectLiteral); if (type) { if (!hasDynamicName(element)) { // For a (non-symbol) computed property, there is no reason to look up the name // in the type. It will just be "__computed", which does not appear in any // SymbolTable. - let symbolName = getSymbolOfNode(element).name; - let propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + const symbolName = getSymbolOfNode(element).name; + const propertyType = getTypeOfPropertyOfContextualType(type, symbolName); if (propertyType) { return propertyType; } @@ -7042,10 +7058,10 @@ namespace ts { // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated // type of T. function getContextualTypeForElementExpression(node: Expression): Type { - let arrayLiteral = node.parent; - let type = getContextualType(arrayLiteral); + const arrayLiteral = node.parent; + const type = getContextualType(arrayLiteral); if (type) { - let index = indexOf(arrayLiteral.elements, node); + const index = indexOf(arrayLiteral.elements, node); return getTypeOfPropertyOfContextualType(type, "" + index) || getIndexTypeOfContextualType(type, IndexKind.Number) || (languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(type, /*errorNode*/ undefined) : undefined); @@ -7055,15 +7071,15 @@ namespace ts { // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type. function getContextualTypeForConditionalOperand(node: Expression): Type { - let conditional = node.parent; + const conditional = node.parent; return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined; } function getContextualTypeForJsxExpression(expr: JsxExpression | JsxSpreadAttribute): Type { // Contextual type only applies to JSX expressions that are in attribute assignments (not in 'Children' positions) if (expr.parent.kind === SyntaxKind.JsxAttribute) { - let attrib = expr.parent; - let attrsType = getJsxElementAttributesType(attrib.parent); + const attrib = expr.parent; + const attrsType = getJsxElementAttributesType(attrib.parent); if (!attrsType || isTypeAny(attrsType)) { return undefined; } @@ -7082,7 +7098,7 @@ namespace ts { // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily // be "pushed" onto a node using the contextualType property. function getContextualType(node: Expression): Type { - let type = getContextualTypeWorker(node); + const type = getContextualTypeWorker(node); return type && getApparentType(type); } @@ -7094,7 +7110,7 @@ namespace ts { if (node.contextualType) { return node.contextualType; } - let parent = node.parent; + const parent = node.parent; switch (parent.kind) { case SyntaxKind.VariableDeclaration: case SyntaxKind.Parameter: @@ -7136,9 +7152,9 @@ namespace ts { // If the given type is an object or union type, if that type has a single signature, and if // that signature is non-generic, return the signature. Otherwise return undefined. function getNonGenericSignature(type: Type): Signature { - let signatures = getSignaturesOfStructuredType(type, SignatureKind.Call); + const signatures = getSignaturesOfStructuredType(type, SignatureKind.Call); if (signatures.length === 1) { - let signature = signatures[0]; + const signature = signatures[0]; if (!signature.typeParameters) { return signature; } @@ -7163,7 +7179,7 @@ namespace ts { // union type of return types from these signatures function getContextualSignature(node: FunctionExpression | MethodDeclaration): Signature { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); - let type = isObjectLiteralMethod(node) + const type = isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node) : getContextualType(node); if (!type) { @@ -7173,9 +7189,9 @@ namespace ts { return getNonGenericSignature(type); } let signatureList: Signature[]; - let types = (type).types; - for (let current of types) { - let signature = getNonGenericSignature(current); + const types = (type).types; + for (const current of types) { + const signature = getNonGenericSignature(current); if (signature) { if (!signatureList) { // This signature will contribute to contextual union signature @@ -7226,7 +7242,7 @@ namespace ts { // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'. function isAssignmentTarget(node: Node): boolean { - let parent = node.parent; + const parent = node.parent; if (parent.kind === SyntaxKind.BinaryExpression && (parent).operatorToken.kind === SyntaxKind.EqualsToken && (parent).left === node) { return true; } @@ -7246,7 +7262,7 @@ namespace ts { // with this type. It is neither affected by it, nor does it propagate it to its operand. // So the fact that contextualMapper is passed is not important, because the operand of a spread // element is not contextually typed. - let arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); + const arrayOrIterableType = checkExpressionCached(node.expression, contextualMapper); return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false); } @@ -7256,11 +7272,11 @@ namespace ts { } function checkArrayLiteral(node: ArrayLiteralExpression, contextualMapper?: TypeMapper): Type { - let elements = node.elements; + const elements = node.elements; let hasSpreadElement = false; - let elementTypes: Type[] = []; - let inDestructuringPattern = isAssignmentTarget(node); - for (let e of elements) { + const elementTypes: Type[] = []; + const inDestructuringPattern = isAssignmentTarget(node); + for (const e of elements) { if (inDestructuringPattern && e.kind === SyntaxKind.SpreadElementExpression) { // Given the following situation: // var c: {}; @@ -7274,15 +7290,15 @@ namespace ts { // get the contextual element type from it. So we do something similar to // getContextualTypeForElementExpression, which will crucially not error // if there is no index type / iterated type. - let restArrayType = checkExpression((e).expression, contextualMapper); - let restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) || + const restArrayType = checkExpression((e).expression, contextualMapper); + const restElementType = getIndexTypeOfType(restArrayType, IndexKind.Number) || (languageVersion >= ScriptTarget.ES6 ? getElementTypeOfIterable(restArrayType, /*errorNode*/ undefined) : undefined); if (restElementType) { elementTypes.push(restElementType); } } else { - let type = checkExpression(e, contextualMapper); + const type = checkExpression(e, contextualMapper); elementTypes.push(type); } hasSpreadElement = hasSpreadElement || e.kind === SyntaxKind.SpreadElementExpression; @@ -7291,19 +7307,19 @@ namespace ts { // If array literal is actually a destructuring pattern, mark it as an implied type. We do this such // that we get the same behavior for "var [x, y] = []" and "[x, y] = []". if (inDestructuringPattern && elementTypes.length) { - let type = createNewTupleType(elementTypes); + const type = createNewTupleType(elementTypes); type.pattern = node; return type; } - let contextualType = getContextualType(node); + const contextualType = getContextualType(node); if (contextualType && contextualTypeIsTupleLikeType(contextualType)) { - let pattern = contextualType.pattern; + const pattern = contextualType.pattern; // If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting // tuple type with the corresponding binding or assignment element types to make the lengths equal. if (pattern && (pattern.kind === SyntaxKind.ArrayBindingPattern || pattern.kind === SyntaxKind.ArrayLiteralExpression)) { - let patternElements = (pattern).elements; + const patternElements = (pattern).elements; for (let i = elementTypes.length; i < patternElements.length; i++) { - let patternElement = patternElements[i]; + const patternElement = patternElements[i]; if (hasDefaultValue(patternElement)) { elementTypes.push((contextualType).elementTypes[i]); } @@ -7363,7 +7379,7 @@ namespace ts { } function checkComputedPropertyName(node: ComputedPropertyName): Type { - let links = getNodeLinks(node.expression); + const links = getNodeLinks(node.expression); if (!links.resolvedType) { links.resolvedType = checkExpression(node.expression); @@ -7381,18 +7397,18 @@ namespace ts { } function checkObjectLiteral(node: ObjectLiteralExpression, contextualMapper?: TypeMapper): Type { - let inDestructuringPattern = isAssignmentTarget(node); + const inDestructuringPattern = isAssignmentTarget(node); // Grammar checking checkGrammarObjectLiteralExpression(node, inDestructuringPattern); - let propertiesTable: SymbolTable = {}; - let propertiesArray: Symbol[] = []; - let contextualType = getContextualType(node); - let contextualTypeHasPattern = contextualType && contextualType.pattern && + const propertiesTable: SymbolTable = {}; + const propertiesArray: Symbol[] = []; + const contextualType = getContextualType(node); + const contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === SyntaxKind.ObjectBindingPattern || contextualType.pattern.kind === SyntaxKind.ObjectLiteralExpression); let typeFlags: TypeFlags = 0; - for (let memberDecl of node.properties) { + for (const memberDecl of node.properties) { let member = memberDecl.symbol; if (memberDecl.kind === SyntaxKind.PropertyAssignment || memberDecl.kind === SyntaxKind.ShorthandPropertyAssignment || @@ -7409,7 +7425,7 @@ namespace ts { type = checkExpression((memberDecl).name, contextualMapper); } typeFlags |= type.flags; - let prop = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.name); + const prop = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.name); if (inDestructuringPattern) { // If object literal is an assignment pattern and if the assignment pattern specifies a default value // for the property, make the property optional. @@ -7423,7 +7439,7 @@ namespace ts { else if (contextualTypeHasPattern) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. - let impliedProp = getPropertyOfType(contextualType, member.name); + const impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & SymbolFlags.Optional; } @@ -7461,7 +7477,7 @@ namespace ts { // If object literal is contextually typed by the implied type of a binding pattern, augment the result // type with those properties for which the binding pattern specifies a default value. if (contextualTypeHasPattern) { - for (let prop of getPropertiesOfType(contextualType)) { + for (const prop of getPropertiesOfType(contextualType)) { if (!hasProperty(propertiesTable, prop.name)) { if (!(prop.flags & SymbolFlags.Optional)) { error(prop.valueDeclaration || (prop).bindingElement, @@ -7473,10 +7489,10 @@ namespace ts { } } - let stringIndexType = getIndexType(IndexKind.String); - let numberIndexType = getIndexType(IndexKind.Number); - let result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); - let freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshObjectLiteral; + const stringIndexType = getIndexType(IndexKind.String); + const numberIndexType = getIndexType(IndexKind.Number); + const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); + const freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshObjectLiteral; result.flags |= TypeFlags.ObjectLiteral | TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag | (typeFlags & TypeFlags.PropagatingFlags); if (inDestructuringPattern) { result.pattern = node; @@ -7485,21 +7501,21 @@ namespace ts { function getIndexType(kind: IndexKind) { if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { - let propTypes: Type[] = []; + const propTypes: Type[] = []; for (let i = 0; i < propertiesArray.length; i++) { - let propertyDecl = node.properties[i]; + const propertyDecl = node.properties[i]; if (kind === IndexKind.String || isNumericName(propertyDecl.name)) { // Do not call getSymbolOfNode(propertyDecl), as that will get the // original symbol for the node. We actually want to get the symbol // created by checkObjectLiteral, since that will be appropriately // contextually typed and resolved. - let type = getTypeOfSymbol(propertiesArray[i]); + const type = getTypeOfSymbol(propertiesArray[i]); if (!contains(propTypes, type)) { propTypes.push(type); } } } - let result = propTypes.length ? getUnionType(propTypes) : undefinedType; + const result = propTypes.length ? getUnionType(propTypes) : undefinedType; typeFlags |= result.flags; return result; } @@ -7539,7 +7555,7 @@ namespace ts { } // Check children - for (let child of node.children) { + for (const child of node.children) { switch (child.kind) { case SyntaxKind.JsxExpression: checkJsxExpression(child); @@ -7585,11 +7601,11 @@ namespace ts { error(node.parent, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, getJsxElementPropertiesName()); } else if (elementAttributesType && !isTypeAny(elementAttributesType)) { - let correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); + const correspondingPropSymbol = getPropertyOfType(elementAttributesType, node.name.text); correspondingPropType = correspondingPropSymbol && getTypeOfSymbol(correspondingPropSymbol); if (isUnhyphenatedJsxName(node.name.text)) { // Maybe there's a string indexer? - let indexerType = getIndexTypeOfType(elementAttributesType, IndexKind.String); + const indexerType = getIndexTypeOfType(elementAttributesType, IndexKind.String); if (indexerType) { correspondingPropType = indexerType; } @@ -7621,15 +7637,15 @@ namespace ts { } function checkJsxSpreadAttribute(node: JsxSpreadAttribute, elementAttributesType: Type, nameTable: Map) { - let type = checkExpression(node.expression); - let props = getPropertiesOfType(type); - for (let prop of props) { + const type = checkExpression(node.expression); + const props = getPropertiesOfType(type); + for (const prop of props) { // Is there a corresponding property in the element attributes type? Skip checking of properties // that have already been assigned to, as these are not actually pushed into the resulting type if (!nameTable[prop.name]) { - let targetPropSym = getPropertyOfType(elementAttributesType, prop.name); + const targetPropSym = getPropertyOfType(elementAttributesType, prop.name); if (targetPropSym) { - let msg = chainDiagnosticMessages(undefined, Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property, prop.name); + const msg = chainDiagnosticMessages(undefined, Diagnostics.Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property, prop.name); checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(targetPropSym), node, undefined, msg); } @@ -7654,8 +7670,8 @@ namespace ts { /// type or factory function. /// Otherwise, returns unknownSymbol. function getJsxElementTagSymbol(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { - let flags: JsxFlags = JsxFlags.UnknownElement; - let links = getNodeLinks(node); + const flags: JsxFlags = JsxFlags.UnknownElement; + const links = getNodeLinks(node); if (!links.resolvedSymbol) { if (isJsxIntrinsicIdentifier(node.tagName)) { links.resolvedSymbol = lookupIntrinsicTag(node); @@ -7667,17 +7683,17 @@ namespace ts { return links.resolvedSymbol; function lookupIntrinsicTag(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { - let intrinsicElementsType = getJsxIntrinsicElementsType(); + const intrinsicElementsType = getJsxIntrinsicElementsType(); if (intrinsicElementsType !== unknownType) { // Property case - let intrinsicProp = getPropertyOfType(intrinsicElementsType, (node.tagName).text); + const intrinsicProp = getPropertyOfType(intrinsicElementsType, (node.tagName).text); if (intrinsicProp) { links.jsxFlags |= JsxFlags.IntrinsicNamedElement; return intrinsicProp; } // Intrinsic string indexer case - let indexSignatureType = getIndexTypeOfType(intrinsicElementsType, IndexKind.String); + const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, IndexKind.String); if (indexSignatureType) { links.jsxFlags |= JsxFlags.IntrinsicIndexedElement; return intrinsicElementsType.symbol; @@ -7695,7 +7711,7 @@ namespace ts { } function lookupClassTag(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { - let valueSymbol: Symbol = resolveJsxTagName(node); + const valueSymbol: Symbol = resolveJsxTagName(node); // Look up the value in the current scope if (valueSymbol && valueSymbol !== unknownSymbol) { @@ -7710,8 +7726,8 @@ namespace ts { function resolveJsxTagName(node: JsxOpeningLikeElement | JsxClosingElement): Symbol { if (node.tagName.kind === SyntaxKind.Identifier) { - let tag = node.tagName; - let sym = getResolvedSymbol(tag); + const tag = node.tagName; + const sym = getResolvedSymbol(tag); return sym.exportSymbol || sym; } else { @@ -7730,13 +7746,13 @@ namespace ts { // line shouldn't be hit. Debug.assert(!!(getNodeLinks(node).jsxFlags & JsxFlags.ClassElement), "Should not call getJsxElementInstanceType on non-class Element"); - let classSymbol = getJsxElementTagSymbol(node); + const classSymbol = getJsxElementTagSymbol(node); if (classSymbol === unknownSymbol) { // Couldn't find the class instance type. Error has already been issued return anyType; } - let valueType = getTypeOfSymbol(classSymbol); + const valueType = getTypeOfSymbol(classSymbol); if (isTypeAny(valueType)) { // Short-circuit if the class tag is using an element type 'any' return anyType; @@ -7755,10 +7771,10 @@ namespace ts { } } - let returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); + const returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); // Issue an error if this return type isn't assignable to JSX.ElementClass - let elemClassType = getJsxGlobalElementClassType(); + const elemClassType = getJsxGlobalElementClassType(); if (elemClassType) { checkTypeRelatedTo(returnType, elemClassType, assignableRelation, node, Diagnostics.JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements); } @@ -7773,13 +7789,13 @@ namespace ts { /// non-instrinsic elements' attributes type is the element instance type) function getJsxElementPropertiesName() { // JSX - let jsxNamespace = getGlobalSymbol(JsxNames.JSX, SymbolFlags.Namespace, /*diagnosticMessage*/undefined); + const jsxNamespace = getGlobalSymbol(JsxNames.JSX, SymbolFlags.Namespace, /*diagnosticMessage*/undefined); // JSX.ElementAttributesProperty [symbol] - let attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, SymbolFlags.Type); + const attribsPropTypeSym = jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementAttributesPropertyNameContainer, SymbolFlags.Type); // JSX.ElementAttributesProperty [type] - let attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); + const attribPropType = attribsPropTypeSym && getDeclaredTypeOfSymbol(attribsPropTypeSym); // The properites of JSX.ElementAttributesProperty - let attribProperties = attribPropType && getPropertiesOfType(attribPropType); + const attribProperties = attribPropType && getPropertiesOfType(attribPropType); if (attribProperties) { // Element Attributes has zero properties, so the element attributes type will be the class instance type @@ -7808,18 +7824,18 @@ namespace ts { * us which attributes are valid on a given element. */ function getJsxElementAttributesType(node: JsxOpeningLikeElement): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedJsxType) { - let sym = getJsxElementTagSymbol(node); + const sym = getJsxElementTagSymbol(node); if (links.jsxFlags & JsxFlags.ClassElement) { - let elemInstanceType = getJsxElementInstanceType(node); + const elemInstanceType = getJsxElementInstanceType(node); if (isTypeAny(elemInstanceType)) { return links.resolvedJsxType = elemInstanceType; } - let propsName = getJsxElementPropertiesName(); + const propsName = getJsxElementPropertiesName(); if (propsName === undefined) { // There is no type ElementAttributesProperty, return 'any' return links.resolvedJsxType = anyType; @@ -7829,7 +7845,7 @@ namespace ts { return links.resolvedJsxType = elemInstanceType; } else { - let attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); + const attributesType = getTypeOfPropertyOfType(elemInstanceType, propsName); if (!attributesType) { // There is no property named 'props' on this instance type @@ -7868,12 +7884,11 @@ namespace ts { * that have no matching element attributes type property. */ function getJsxAttributePropertySymbol(attrib: JsxAttribute): Symbol { - let attributesType = getJsxElementAttributesType(attrib.parent); - let prop = getPropertyOfType(attributesType, attrib.name.text); + const attributesType = getJsxElementAttributesType(attrib.parent); + const prop = getPropertyOfType(attributesType, attrib.name.text); return prop || unknownSymbol; } - let jsxElementClassType: Type = undefined; function getJsxGlobalElementClassType(): Type { if (!jsxElementClassType) { jsxElementClassType = getExportedTypeFromNamespace(JsxNames.JSX, JsxNames.ElementClass); @@ -7883,7 +7898,7 @@ namespace ts { /// Returns all the properties of the Jsx.IntrinsicElements interface function getJsxIntrinsicTagNames(): Symbol[] { - let intrinsics = getJsxIntrinsicElementsType(); + const intrinsics = getJsxIntrinsicElementsType(); return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray; } @@ -7908,15 +7923,15 @@ namespace ts { // be marked as 'used' so we don't incorrectly elide its import. And if there // is no 'React' symbol in scope, we should issue an error. if (compilerOptions.jsx === JsxEmit.React) { - let reactSym = resolveName(node.tagName, "React", SymbolFlags.Value, Diagnostics.Cannot_find_name_0, "React"); + const reactSym = resolveName(node.tagName, "React", SymbolFlags.Value, Diagnostics.Cannot_find_name_0, "React"); if (reactSym) { getSymbolLinks(reactSym).referenced = true; } } - let targetAttributesType = getJsxElementAttributesType(node); + const targetAttributesType = getJsxElementAttributesType(node); - let nameTable: Map = {}; + const nameTable: Map = {}; // Process this array in right-to-left order so we know which // attributes (mostly from spreads) are being overwritten and // thus should have their types ignored @@ -7927,7 +7942,7 @@ namespace ts { } else { Debug.assert(node.attributes[i].kind === SyntaxKind.JsxSpreadAttribute); - let spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); + const spreadType = checkJsxSpreadAttribute((node.attributes[i]), targetAttributesType, nameTable); if (isTypeAny(spreadType)) { sawSpreadedAny = true; } @@ -7937,7 +7952,7 @@ namespace ts { // Check that all required properties have been provided. If an 'any' // was spreaded in, though, assume that it provided all required properties if (targetAttributesType && !sawSpreadedAny) { - let targetProperties = getPropertiesOfType(targetAttributesType); + const targetProperties = getPropertiesOfType(targetAttributesType); for (let i = 0; i < targetProperties.length; i++) { if (!(targetProperties[i].flags & SymbolFlags.Optional) && nameTable[targetProperties[i].name] === undefined) { @@ -7976,11 +7991,11 @@ namespace ts { * @param prop The symbol for the right hand side of the property access. */ function checkClassPropertyAccess(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, type: Type, prop: Symbol): boolean { - let flags = getDeclarationFlagsFromSymbol(prop); - let declaringClass = getDeclaredTypeOfSymbol(prop.parent); + const flags = getDeclarationFlagsFromSymbol(prop); + const declaringClass = getDeclaredTypeOfSymbol(prop.parent); if (left.kind === SyntaxKind.SuperKeyword) { - let errorNode = node.kind === SyntaxKind.PropertyAccessExpression ? + const errorNode = node.kind === SyntaxKind.PropertyAccessExpression ? (node).name : (node).right; @@ -8017,9 +8032,9 @@ namespace ts { // Property is known to be private or protected at this point // Get the declaring and enclosing class instance types - let enclosingClassDeclaration = getContainingClass(node); + const enclosingClassDeclaration = getContainingClass(node); - let enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; + const enclosingClass = enclosingClassDeclaration ? getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingClassDeclaration)) : undefined; // Private property is accessible if declaring and enclosing class are the same if (flags & NodeFlags.Private) { @@ -8068,17 +8083,17 @@ namespace ts { } function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, right: Identifier) { - let type = checkExpression(left); + const type = checkExpression(left); if (isTypeAny(type)) { return type; } - let apparentType = getApparentType(getWidenedType(type)); + const apparentType = getApparentType(getWidenedType(type)); if (apparentType === unknownType) { // handle cases when type is Type parameter with invalid constraint return unknownType; } - let prop = getPropertyOfType(apparentType, right.text); + const prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text) { error(right, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(right), typeToString(type.flags & TypeFlags.ThisType ? apparentType : type)); @@ -8095,13 +8110,13 @@ namespace ts { } function isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean { - let left = node.kind === SyntaxKind.PropertyAccessExpression + const left = node.kind === SyntaxKind.PropertyAccessExpression ? (node).expression : (node).left; - let type = checkExpression(left); + const type = checkExpression(left); if (type !== unknownType && !isTypeAny(type)) { - let prop = getPropertyOfType(getWidenedType(type), propertyName); + const prop = getPropertyOfType(getWidenedType(type), propertyName); if (prop && prop.parent && prop.parent.flags & SymbolFlags.Class) { return checkClassPropertyAccess(node, left, type, prop); } @@ -8112,28 +8127,28 @@ namespace ts { function checkIndexedAccess(node: ElementAccessExpression): Type { // Grammar checking if (!node.argumentExpression) { - let sourceFile = getSourceFile(node); + const sourceFile = getSourceFile(node); if (node.parent.kind === SyntaxKind.NewExpression && (node.parent).expression === node) { - let start = skipTrivia(sourceFile.text, node.expression.end); - let end = node.end; + const start = skipTrivia(sourceFile.text, node.expression.end); + const end = node.end; grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead); } else { - let start = node.end - "]".length; - let end = node.end; + const start = node.end - "]".length; + const end = node.end; grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.Expression_expected); } } // Obtain base constraint such that we can bail out if the constraint is an unknown type - let objectType = getApparentType(checkExpression(node.expression)); - let indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; + const objectType = getApparentType(checkExpression(node.expression)); + const indexType = node.argumentExpression ? checkExpression(node.argumentExpression) : unknownType; if (objectType === unknownType) { return unknownType; } - let isConstEnum = isConstEnumObjectType(objectType); + const isConstEnum = isConstEnumObjectType(objectType); if (isConstEnum && (!node.argumentExpression || node.argumentExpression.kind !== SyntaxKind.StringLiteral)) { error(node.argumentExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); @@ -8151,9 +8166,9 @@ namespace ts { // See if we can index as a property. if (node.argumentExpression) { - let name = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + const name = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); if (name !== undefined) { - let prop = getPropertyOfType(objectType, name); + const prop = getPropertyOfType(objectType, name); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); @@ -8170,14 +8185,14 @@ namespace ts { // Try to use a number indexer. if (isTypeAnyOrAllConstituentTypesHaveKind(indexType, TypeFlags.NumberLike)) { - let numberIndexType = getIndexTypeOfType(objectType, IndexKind.Number); + const numberIndexType = getIndexTypeOfType(objectType, IndexKind.Number); if (numberIndexType) { return numberIndexType; } } // Try to use string indexing. - let stringIndexType = getIndexTypeOfType(objectType, IndexKind.String); + const stringIndexType = getIndexTypeOfType(objectType, IndexKind.String); if (stringIndexType) { return stringIndexType; } @@ -8208,13 +8223,13 @@ namespace ts { return (indexArgumentExpression).text; } if (indexArgumentExpression.kind === SyntaxKind.ElementAccessExpression || indexArgumentExpression.kind === SyntaxKind.PropertyAccessExpression) { - let value = getConstantValue(indexArgumentExpression); + const value = getConstantValue(indexArgumentExpression); if (value !== undefined) { return value.toString(); } } if (checkThatExpressionIsProperSymbolReference(indexArgumentExpression, indexArgumentType, /*reportError*/ false)) { - let rightHandSideName = ((indexArgumentExpression).name).text; + const rightHandSideName = ((indexArgumentExpression).name).text; return getPropertyNameForKnownSymbolName(rightHandSideName); } @@ -8248,13 +8263,13 @@ namespace ts { // The name is Symbol., so make sure Symbol actually resolves to the // global Symbol object - let leftHandSide = (expression).expression; - let leftHandSideSymbol = getResolvedSymbol(leftHandSide); + const leftHandSide = (expression).expression; + const leftHandSideSymbol = getResolvedSymbol(leftHandSide); if (!leftHandSideSymbol) { return false; } - let globalESSymbol = getGlobalESSymbolConstructorSymbol(); + const globalESSymbol = getGlobalESSymbolConstructorSymbol(); if (!globalESSymbol) { // Already errored when we tried to look up the symbol return false; @@ -8293,7 +8308,7 @@ namespace ts { // so order how inherited signatures are processed is still preserved. // interface A { (x: string): void } // interface B extends A { (x: 'foo'): string } - // let b: B; + // const b: B; // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void] function reorderCandidates(signatures: Signature[], result: Signature[]): void { let lastParent: Node; @@ -8303,9 +8318,9 @@ namespace ts { let specializedIndex = -1; let spliceIndex: number; Debug.assert(!result.length); - for (let signature of signatures) { - let symbol = signature.declaration && getSymbolOfNode(signature.declaration); - let parent = signature.declaration && signature.declaration.parent; + for (const signature of signatures) { + const symbol = signature.declaration && getSymbolOfNode(signature.declaration); + const parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { if (lastParent && parent === lastParent) { index++; @@ -8343,7 +8358,7 @@ namespace ts { function getSpreadArgumentIndex(args: Expression[]): number { for (let i = 0; i < args.length; i++) { - let arg = args[i]; + const arg = args[i]; if (arg && arg.kind === SyntaxKind.SpreadElementExpression) { return i; } @@ -8359,7 +8374,7 @@ namespace ts { let spreadArgIndex = -1; if (node.kind === SyntaxKind.TaggedTemplateExpression) { - let tagExpression = node; + const tagExpression = node; // Even if the call is incomplete, we'll have a missing expression as our last argument, // so we can say the count is just the arg list length @@ -8369,8 +8384,8 @@ namespace ts { if (tagExpression.template.kind === SyntaxKind.TemplateExpression) { // If a tagged template expression lacks a tail literal, the call is incomplete. // Specifically, a template only can end in a TemplateTail or a Missing literal. - let templateExpression = tagExpression.template; - let lastSpan = lastOrUndefined(templateExpression.templateSpans); + const templateExpression = tagExpression.template; + const lastSpan = lastOrUndefined(templateExpression.templateSpans); Debug.assert(lastSpan !== undefined); // we should always have at least one span. callIsIncomplete = nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated; } @@ -8378,7 +8393,7 @@ namespace ts { // If the template didn't end in a backtick, or its beginning occurred right prior to EOF, // then this might actually turn out to be a TemplateHead in the future; // so we consider the call to be incomplete. - let templateLiteral = tagExpression.template; + const templateLiteral = tagExpression.template; Debug.assert(templateLiteral.kind === SyntaxKind.NoSubstitutionTemplateLiteral); callIsIncomplete = !!templateLiteral.isUnterminated; } @@ -8389,7 +8404,7 @@ namespace ts { adjustedArgCount = getEffectiveArgumentCount(node, /*args*/ undefined, signature); } else { - let callExpression = node; + const callExpression = node; if (!callExpression.arguments) { // This only happens when we have something of the form: 'new C' Debug.assert(callExpression.kind === SyntaxKind.NewExpression); @@ -8409,7 +8424,7 @@ namespace ts { // If the user supplied type arguments, but the number of type arguments does not match // the declared number of type parameters, the call has an incorrect arity. - let hasRightNumberOfTypeArgs = !typeArguments || + const hasRightNumberOfTypeArgs = !typeArguments || (signature.typeParameters && typeArguments.length === signature.typeParameters.length); if (!hasRightNumberOfTypeArgs) { return false; @@ -8427,14 +8442,14 @@ namespace ts { } // If the call is incomplete, we should skip the lower bound check. - let hasEnoughArguments = adjustedArgCount >= signature.minArgumentCount; + const hasEnoughArguments = adjustedArgCount >= signature.minArgumentCount; return callIsIncomplete || hasEnoughArguments; } // If type has a single call signature and no other members, return that signature. Otherwise, return undefined. function getSingleCallSignature(type: Type): Signature { if (type.flags & TypeFlags.ObjectType) { - let resolved = resolveStructuredTypeMembers(type); + const resolved = resolveStructuredTypeMembers(type); if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 && resolved.properties.length === 0 && !resolved.stringIndexType && !resolved.numberIndexType) { return resolved.callSignatures[0]; @@ -8445,7 +8460,7 @@ namespace ts { // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec) function instantiateSignatureInContextOf(signature: Signature, contextualSignature: Signature, contextualMapper: TypeMapper): Signature { - let context = createInferenceContext(signature.typeParameters, /*inferUnionTypes*/ true); + const context = createInferenceContext(signature.typeParameters, /*inferUnionTypes*/ true); forEachMatchingParameterType(contextualSignature, signature, (source, target) => { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context, instantiateType(source, contextualMapper), target); @@ -8454,8 +8469,8 @@ namespace ts { } function inferTypeArguments(node: CallLikeExpression, signature: Signature, args: Expression[], excludeArgument: boolean[], context: InferenceContext): void { - let typeParameters = signature.typeParameters; - let inferenceMapper = createInferenceMapper(context); + const typeParameters = signature.typeParameters; + const inferenceMapper = createInferenceMapper(context); // Clear out all the inference results from the last time inferTypeArguments was called on this context for (let i = 0; i < typeParameters.length; i++) { @@ -8481,12 +8496,12 @@ namespace ts { // We perform two passes over the arguments. In the first pass we infer from all arguments, but use // wildcards for all context sensitive function expressions. - let argCount = getEffectiveArgumentCount(node, args, signature); + const argCount = getEffectiveArgumentCount(node, args, signature); for (let i = 0; i < argCount; i++) { - let arg = getEffectiveArgument(node, args, i); + const arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. if (arg === undefined || arg.kind !== SyntaxKind.OmittedExpression) { - let paramType = getTypeAtPosition(signature, i); + const paramType = getTypeAtPosition(signature, i); let argType = getEffectiveArgumentType(node, i, arg); // If the effective argument type is 'undefined', there is no synthetic type @@ -8494,7 +8509,7 @@ namespace ts { if (argType === undefined) { // For context sensitive arguments we pass the identityMapper, which is a signal to treat all // context sensitive function expressions as wildcards - let mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; + const mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; argType = checkExpressionWithContextualType(arg, paramType, mapper); } @@ -8511,8 +8526,8 @@ namespace ts { for (let i = 0; i < argCount; i++) { // No need to check for omitted args and template expressions, their exlusion value is always undefined if (excludeArgument[i] === false) { - let arg = args[i]; - let paramType = getTypeAtPosition(signature, i); + const arg = args[i]; + const paramType = getTypeAtPosition(signature, i); inferTypes(context, checkExpressionWithContextualType(arg, paramType, inferenceMapper), paramType); } } @@ -8522,15 +8537,15 @@ namespace ts { } function checkTypeArguments(signature: Signature, typeArguments: TypeNode[], typeArgumentResultTypes: Type[], reportErrors: boolean, headMessage?: DiagnosticMessage): boolean { - let typeParameters = signature.typeParameters; + const typeParameters = signature.typeParameters; let typeArgumentsAreAssignable = true; for (let i = 0; i < typeParameters.length; i++) { - let typeArgNode = typeArguments[i]; - let typeArgument = getTypeFromTypeNode(typeArgNode); + const typeArgNode = typeArguments[i]; + const typeArgument = getTypeFromTypeNode(typeArgNode); // Do not push on this array! It has a preallocated length typeArgumentResultTypes[i] = typeArgument; if (typeArgumentsAreAssignable /* so far */) { - let constraint = getConstraintOfTypeParameter(typeParameters[i]); + const constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { let errorInfo: DiagnosticMessageChain; let typeArgumentHeadMessage = Diagnostics.Type_0_does_not_satisfy_the_constraint_1; @@ -8553,13 +8568,13 @@ namespace ts { } function checkApplicableSignature(node: CallLikeExpression, args: Expression[], signature: Signature, relation: Map, excludeArgument: boolean[], reportErrors: boolean) { - let argCount = getEffectiveArgumentCount(node, args, signature); + const argCount = getEffectiveArgumentCount(node, args, signature); for (let i = 0; i < argCount; i++) { - let arg = getEffectiveArgument(node, args, i); + const arg = getEffectiveArgument(node, args, i); // If the effective argument is 'undefined', then it is an argument that is present but is synthetic. if (arg === undefined || arg.kind !== SyntaxKind.OmittedExpression) { // Check spread elements against rest type (from arity check we know spread argument corresponds to a rest parameter) - let paramType = getTypeAtPosition(signature, i); + const paramType = getTypeAtPosition(signature, i); let argType = getEffectiveArgumentType(node, i, arg); // If the effective argument type is 'undefined', there is no synthetic type @@ -8571,8 +8586,8 @@ namespace ts { } // Use argument expression as error location when reporting errors - let errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; - let headMessage = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; + const errorNode = reportErrors ? getEffectiveArgumentErrorNode(node, i, arg) : undefined; + const headMessage = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1; if (!checkTypeRelatedTo(argType, paramType, relation, errorNode, headMessage)) { return false; } @@ -8594,7 +8609,7 @@ namespace ts { function getEffectiveCallArguments(node: CallLikeExpression): Expression[] { let args: Expression[]; if (node.kind === SyntaxKind.TaggedTemplateExpression) { - let template = (node).template; + const template = (node).template; args = [undefined]; if (template.kind === SyntaxKind.TemplateExpression) { forEach((template).templateSpans, span => { @@ -8686,7 +8701,7 @@ namespace ts { if (node.kind === SyntaxKind.ClassDeclaration) { // For a class decorator, the `target` is the type of the class (e.g. the // "static" or "constructor" side of the class) - let classSymbol = getSymbolOfNode(node); + const classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } @@ -8695,7 +8710,7 @@ namespace ts { // parameter's containing method. node = node.parent; if (node.kind === SyntaxKind.Constructor) { - let classSymbol = getSymbolOfNode(node); + const classSymbol = getSymbolOfNode(node); return getTypeOfSymbol(classSymbol); } } @@ -8756,7 +8771,7 @@ namespace ts { // string literal type if the member name is an identifier, number, or string; // otherwise, if the member name is a computed property name it will // be either string or symbol. - let element = node; + const element = node; switch (element.name.kind) { case SyntaxKind.Identifier: case SyntaxKind.NumericLiteral: @@ -8764,7 +8779,7 @@ namespace ts { return getStringLiteralType(element.name); case SyntaxKind.ComputedPropertyName: - let nameType = checkComputedPropertyName(element.name); + const nameType = checkComputedPropertyName(element.name); if (allConstituentTypesHaveKind(nameType, TypeFlags.ESSymbol)) { return nameType; } @@ -8812,7 +8827,7 @@ namespace ts { node.kind === SyntaxKind.SetAccessor) { // The `descriptor` for a method decorator will be a `TypedPropertyDescriptor` // for the type of the member. - let propertyType = getTypeOfNode(node); + const propertyType = getTypeOfNode(node); return createTypedPropertyDescriptorType(propertyType); } @@ -8888,8 +8903,8 @@ namespace ts { } function resolveCall(node: CallLikeExpression, signatures: Signature[], candidatesOutArray: Signature[], headMessage?: DiagnosticMessage): Signature { - let isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; - let isDecorator = node.kind === SyntaxKind.Decorator; + const isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression; + const isDecorator = node.kind === SyntaxKind.Decorator; let typeArguments: TypeNode[]; @@ -8902,7 +8917,7 @@ namespace ts { } } - let candidates = candidatesOutArray || []; + const candidates = candidatesOutArray || []; // reorderCandidates fills up the candidates array directly reorderCandidates(signatures, candidates); if (!candidates.length) { @@ -8910,7 +8925,7 @@ namespace ts { return resolveErrorCall(node); } - let args = getEffectiveCallArguments(node); + const args = getEffectiveCallArguments(node); // The following applies to any value of 'excludeArgument[i]': // - true: the argument at 'i' is susceptible to a one-time permanent contextual typing. @@ -9008,8 +9023,8 @@ namespace ts { } else { Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0); - let failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; - let inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); + const failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex]; + const inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex); let diagnosticChainHead = chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly, @@ -9055,14 +9070,14 @@ namespace ts { } function chooseOverload(candidates: Signature[], relation: Map) { - for (let originalCandidate of candidates) { + for (const originalCandidate of candidates) { if (!hasCorrectArity(node, args, originalCandidate)) { continue; } let candidate: Signature; let typeArgumentsAreValid: boolean; - let inferenceContext = originalCandidate.typeParameters + const inferenceContext = originalCandidate.typeParameters ? createInferenceContext(originalCandidate.typeParameters, /*inferUnionTypes*/ false) : undefined; @@ -9087,7 +9102,7 @@ namespace ts { if (!checkApplicableSignature(node, args, candidate, relation, excludeArgument, /*reportErrors*/ false)) { break; } - let index = excludeArgument ? indexOf(excludeArgument, true) : -1; + const index = excludeArgument ? indexOf(excludeArgument, true) : -1; if (index < 0) { return candidate; } @@ -9100,7 +9115,7 @@ namespace ts { // report an error based on the arguments. If there was an issue with type // arguments, then we can only report an error based on the type arguments. if (originalCandidate.typeParameters) { - let instantiatedCandidate = candidate; + const instantiatedCandidate = candidate; if (typeArgumentsAreValid) { candidateForArgumentError = instantiatedCandidate; } @@ -9124,19 +9139,19 @@ namespace ts { function resolveCallExpression(node: CallExpression, candidatesOutArray: Signature[]): Signature { if (node.expression.kind === SyntaxKind.SuperKeyword) { - let superType = checkSuperExpression(node.expression); + const superType = checkSuperExpression(node.expression); if (superType !== unknownType) { // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated // with the type arguments specified in the extends clause. - let baseTypeNode = getClassExtendsHeritageClauseElement(getContainingClass(node)); - let baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); + const baseTypeNode = getClassExtendsHeritageClauseElement(getContainingClass(node)); + const baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments); return resolveCall(node, baseConstructors, candidatesOutArray); } return resolveUntypedCall(node); } - let funcType = checkExpression(node.expression); - let apparentType = getApparentType(funcType); + const funcType = checkExpression(node.expression); + const apparentType = getApparentType(funcType); if (apparentType === unknownType) { // Another error has already been reported @@ -9147,9 +9162,9 @@ namespace ts { // but we are not including call signatures that may have been added to the Object or // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. - let callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); + const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); - let constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); + const constructSignatures = getSignaturesOfType(apparentType, SignatureKind.Construct); // TS 1.0 spec: 4.12 // If FuncExpr is of type Any, or of an object type that has no call or construct signatures // but is a subtype of the Function interface, the call is an untyped function call. In an @@ -9182,7 +9197,7 @@ namespace ts { function resolveNewExpression(node: NewExpression, candidatesOutArray: Signature[]): Signature { if (node.arguments && languageVersion < ScriptTarget.ES5) { - let spreadIndex = getSpreadArgumentIndex(node.arguments); + const spreadIndex = getSpreadArgumentIndex(node.arguments); if (spreadIndex >= 0) { error(node.arguments[spreadIndex], Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher); } @@ -9205,7 +9220,7 @@ namespace ts { // Note, only class declarations can be declared abstract. // In the case of a merged class-module or class-interface declaration, // only the class declaration node will have the Abstract flag set. - let valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); + const valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol); if (valueDecl && valueDecl.flags & NodeFlags.Abstract) { error(node, Diagnostics.Cannot_create_an_instance_of_the_abstract_class_0, declarationNameToString(valueDecl.name)); return resolveErrorCall(node); @@ -9225,7 +9240,7 @@ namespace ts { // but we are not including construct signatures that may have been added to the Object or // Function interface, since they have none by default. This is a bit of a leap of faith // that the user will not add any. - let constructSignatures = getSignaturesOfType(expressionType, SignatureKind.Construct); + const constructSignatures = getSignaturesOfType(expressionType, SignatureKind.Construct); if (constructSignatures.length) { return resolveCall(node, constructSignatures, candidatesOutArray); } @@ -9234,9 +9249,9 @@ namespace ts { // one or more call signatures, the expression is processed as a function call. A compile-time // error occurs if the result of the function call is not Void. The type of the result of the // operation is Any. - let callSignatures = getSignaturesOfType(expressionType, SignatureKind.Call); + const callSignatures = getSignaturesOfType(expressionType, SignatureKind.Call); if (callSignatures.length) { - let signature = resolveCall(node, callSignatures, candidatesOutArray); + const signature = resolveCall(node, callSignatures, candidatesOutArray); if (getReturnTypeOfSignature(signature) !== voidType) { error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword); } @@ -9248,15 +9263,15 @@ namespace ts { } function resolveTaggedTemplateExpression(node: TaggedTemplateExpression, candidatesOutArray: Signature[]): Signature { - let tagType = checkExpression(node.tag); - let apparentType = getApparentType(tagType); + const tagType = checkExpression(node.tag); + const apparentType = getApparentType(tagType); if (apparentType === unknownType) { // Another error has already been reported return resolveErrorCall(node); } - let callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); + const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); if (isTypeAny(tagType) || (!callSignatures.length && !(tagType.flags & TypeFlags.Union) && isTypeAssignableTo(tagType, globalFunctionType))) { return resolveUntypedCall(node); @@ -9296,18 +9311,18 @@ namespace ts { * Resolves a decorator as if it were a call expression. */ function resolveDecorator(node: Decorator, candidatesOutArray: Signature[]): Signature { - let funcType = checkExpression(node.expression); - let apparentType = getApparentType(funcType); + const funcType = checkExpression(node.expression); + const apparentType = getApparentType(funcType); if (apparentType === unknownType) { return resolveErrorCall(node); } - let callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); + const callSignatures = getSignaturesOfType(apparentType, SignatureKind.Call); if (funcType === anyType || (!callSignatures.length && !(funcType.flags & TypeFlags.Union) && isTypeAssignableTo(funcType, globalFunctionType))) { return resolveUntypedCall(node); } - let headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + const headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); if (!callSignatures.length) { let errorInfo: DiagnosticMessageChain; errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature); @@ -9322,7 +9337,7 @@ namespace ts { // candidatesOutArray is passed by signature help in the language service, and collectCandidates // must fill it up with the appropriate candidate signatures function getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature { - let links = getNodeLinks(node); + const links = getNodeLinks(node); // If getResolvedSignature has already been called, we will have cached the resolvedSignature. // However, it is possible that either candidatesOutArray was not passed in the first time, // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work @@ -9358,12 +9373,12 @@ namespace ts { // Grammar checking; stop grammar-checking if checkGrammarTypeArguments return true checkGrammarTypeArguments(node, node.typeArguments) || checkGrammarArguments(node, node.arguments); - let signature = getResolvedSignature(node); + const signature = getResolvedSignature(node); if (node.expression.kind === SyntaxKind.SuperKeyword) { return voidType; } if (node.kind === SyntaxKind.NewExpression) { - let declaration = signature.declaration; + const declaration = signature.declaration; if (declaration && declaration.kind !== SyntaxKind.Constructor && @@ -9385,10 +9400,10 @@ namespace ts { } function checkAssertion(node: AssertionExpression) { - let exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); - let targetType = getTypeFromTypeNode(node.type); + const exprType = getRegularTypeOfObjectLiteral(checkExpression(node.expression)); + const targetType = getTypeFromTypeNode(node.type); if (produceDiagnostics && targetType !== unknownType) { - let widenedType = getWidenedType(exprType); + const widenedType = getWidenedType(exprType); if (!(isTypeAssignableTo(targetType, widenedType))) { checkTypeAssignableTo(exprType, targetType, node, Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other); } @@ -9403,15 +9418,15 @@ namespace ts { } function assignContextualParameterTypes(signature: Signature, context: Signature, mapper: TypeMapper) { - let len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + const len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); for (let i = 0; i < len; i++) { - let parameter = signature.parameters[i]; - let contextualParameterType = getTypeAtPosition(context, i); + const parameter = signature.parameters[i]; + const contextualParameterType = getTypeAtPosition(context, i); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); } if (signature.hasRestParameter && isRestParameterIndex(context, signature.parameters.length - 1)) { - let parameter = lastOrUndefined(signature.parameters); - let contextualParameterType = getTypeOfSymbol(lastOrUndefined(context.parameters)); + const parameter = lastOrUndefined(signature.parameters); + const contextualParameterType = getTypeOfSymbol(lastOrUndefined(context.parameters)); assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType, mapper); } } @@ -9420,7 +9435,7 @@ namespace ts { // the destructured type into the contained binding elements. function assignBindingElementTypes(node: VariableLikeDeclaration) { if (isBindingPattern(node.name)) { - for (let element of (node.name).elements) { + for (const element of (node.name).elements) { if (element.kind !== SyntaxKind.OmittedExpression) { if (element.name.kind === SyntaxKind.Identifier) { getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element); @@ -9432,7 +9447,7 @@ namespace ts { } function assignTypeToParameterAndFixTypeParameters(parameter: Symbol, contextualType: Type, mapper: TypeMapper) { - let links = getSymbolLinks(parameter); + const links = getSymbolLinks(parameter); if (!links.type) { links.type = instantiateType(contextualType, mapper); assignBindingElementTypes(parameter.valueDeclaration); @@ -9473,7 +9488,7 @@ namespace ts { function createPromiseType(promisedType: Type): Type { // creates a `Promise` type where `T` is the promisedType argument - let globalPromiseType = getGlobalPromiseType(); + const globalPromiseType = getGlobalPromiseType(); if (globalPromiseType !== emptyGenericType) { // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type promisedType = getAwaitedType(promisedType); @@ -9484,12 +9499,12 @@ namespace ts { } function getReturnTypeFromBody(func: FunctionLikeDeclaration, contextualMapper?: TypeMapper): Type { - let contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + const contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); if (!func.body) { return unknownType; } - let isAsync = isAsyncFunctionLike(func); + const isAsync = isAsyncFunctionLike(func); let type: Type; if (func.body.kind !== SyntaxKind.Block) { type = checkExpressionCached(func.body, contextualMapper); @@ -9503,11 +9518,11 @@ namespace ts { } else { let types: Type[]; - let funcIsGenerator = !!func.asteriskToken; + const funcIsGenerator = !!func.asteriskToken; if (funcIsGenerator) { types = checkAndAggregateYieldOperandTypes(func.body, contextualMapper); if (types.length === 0) { - let iterableIteratorAny = createIterableIteratorType(anyType); + const iterableIteratorAny = createIterableIteratorType(anyType); if (compilerOptions.noImplicitAny) { error(func.asteriskToken, Diagnostics.Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type, typeToString(iterableIteratorAny)); @@ -9520,7 +9535,7 @@ namespace ts { if (types.length === 0) { if (isAsync) { // For an async function, the return type will not be void, but rather a Promise for void. - let promiseType = createPromiseType(voidType); + const promiseType = createPromiseType(voidType); if (promiseType === emptyObjectType) { error(func, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); return unknownType; @@ -9555,12 +9570,12 @@ namespace ts { reportErrorsFromWidening(func, type); } - let widenedType = getWidenedType(type); + const widenedType = getWidenedType(type); if (isAsync) { // From within an async function you can return either a non-promise value or a promise. Any // Promise/A+ compatible implementation will always assimilate any foreign promise, so the // return type of the body is awaited type of the body, wrapped in a native Promise type. - let promiseType = createPromiseType(widenedType); + const promiseType = createPromiseType(widenedType); if (promiseType === emptyObjectType) { error(func, Diagnostics.An_async_function_or_method_must_have_a_valid_awaitable_return_type); return unknownType; @@ -9574,10 +9589,10 @@ namespace ts { } function checkAndAggregateYieldOperandTypes(body: Block, contextualMapper?: TypeMapper): Type[] { - let aggregatedTypes: Type[] = []; + const aggregatedTypes: Type[] = []; forEachYieldExpression(body, yieldExpression => { - let expr = yieldExpression.expression; + const expr = yieldExpression.expression; if (expr) { let type = checkExpressionCached(expr, contextualMapper); @@ -9596,10 +9611,10 @@ namespace ts { } function checkAndAggregateReturnExpressionTypes(body: Block, contextualMapper?: TypeMapper, isAsync?: boolean): Type[] { - let aggregatedTypes: Type[] = []; + const aggregatedTypes: Type[] = []; forEachReturnStatement(body, returnStatement => { - let expr = returnStatement.expression; + const expr = returnStatement.expression; if (expr) { let type = checkExpressionCached(expr, contextualMapper); if (isAsync) { @@ -9619,21 +9634,11 @@ namespace ts { return aggregatedTypes; } - function bodyContainsAReturnStatement(funcBody: Block) { - return forEachReturnStatement(funcBody, returnStatement => { - return true; - }); - } - - function bodyContainsSingleThrowStatement(body: Block) { - return (body.statements.length === 1) && (body.statements[0].kind === SyntaxKind.ThrowStatement); - } - // TypeScript Specification 1.0 (6.3) - July 2014 // An explicitly typed function whose return type isn't the Void or the Any type // must have at least one return statement somewhere in its body. // An exception to this rule is if the function implementation consists of a single 'throw' statement. - function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func: FunctionLikeDeclaration, returnType: Type): void { + function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func: FunctionLikeDeclaration, returnType: Type): void { if (!produceDiagnostics) { return; } @@ -9644,33 +9649,27 @@ namespace ts { } // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check. - if (nodeIsMissing(func.body) || func.body.kind !== SyntaxKind.Block) { + // also if HasImplicitReturnValue flags is not set this means that all codepaths in function body end with return of throw + if (nodeIsMissing(func.body) || func.body.kind !== SyntaxKind.Block || !(func.flags & NodeFlags.HasImplicitReturn)) { return; } - let bodyBlock = func.body; - - // Ensure the body has at least one return expression. - if (bodyContainsAReturnStatement(bodyBlock)) { - return; + if (func.flags & NodeFlags.HasExplicitReturn) { + if (compilerOptions.noImplicitReturns) { + error(func.type, Diagnostics.Not_all_code_paths_return_a_value); + } } - - // If there are no return expressions, then we need to check if - // the function body consists solely of a throw statement; - // this is to make an exception for unimplemented functions. - if (bodyContainsSingleThrowStatement(bodyBlock)) { - return; + else { + // This function does not conform to the specification. + error(func.type, Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value); } - - // This function does not conform to the specification. - error(func.type, Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value_or_consist_of_a_single_throw_statement); } function checkFunctionExpressionOrObjectLiteralMethod(node: FunctionExpression | MethodDeclaration, contextualMapper?: TypeMapper): Type { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); // Grammar checking - let hasGrammarError = checkGrammarFunctionLikeDeclaration(node); + const hasGrammarError = checkGrammarFunctionLikeDeclaration(node); if (!hasGrammarError && node.kind === SyntaxKind.FunctionExpression) { checkGrammarForGenerator(node); } @@ -9680,34 +9679,34 @@ namespace ts { return anyFunctionType; } - let isAsync = isAsyncFunctionLike(node); + const isAsync = isAsyncFunctionLike(node); if (isAsync) { emitAwaiter = true; } - let links = getNodeLinks(node); - let type = getTypeOfSymbol(node.symbol); - let contextSensitive = isContextSensitive(node); - let mightFixTypeParameters = contextSensitive && isInferentialContext(contextualMapper); + const links = getNodeLinks(node); + const type = getTypeOfSymbol(node.symbol); + const contextSensitive = isContextSensitive(node); + const mightFixTypeParameters = contextSensitive && isInferentialContext(contextualMapper); // Check if function expression is contextually typed and assign parameter types if so. // See the comment in assignTypeToParameterAndFixTypeParameters to understand why we need to // check mightFixTypeParameters. if (mightFixTypeParameters || !(links.flags & NodeCheckFlags.ContextChecked)) { - let contextualSignature = getContextualSignature(node); + const contextualSignature = getContextualSignature(node); // If a type check is started at a function expression that is an argument of a function call, obtaining the // contextual type may recursively get back to here during overload resolution of the call. If so, we will have // already assigned contextual types. - let contextChecked = !!(links.flags & NodeCheckFlags.ContextChecked); + const contextChecked = !!(links.flags & NodeCheckFlags.ContextChecked); if (mightFixTypeParameters || !contextChecked) { links.flags |= NodeCheckFlags.ContextChecked; if (contextualSignature) { - let signature = getSignaturesOfType(type, SignatureKind.Call)[0]; + const signature = getSignaturesOfType(type, SignatureKind.Call)[0]; if (contextSensitive) { assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); } if (mightFixTypeParameters || !node.type && !signature.resolvedReturnType) { - let returnType = getReturnTypeFromBody(node, contextualMapper); + const returnType = getReturnTypeFromBody(node, contextualMapper); if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; } @@ -9731,19 +9730,19 @@ namespace ts { function checkFunctionExpressionOrObjectLiteralMethodBody(node: FunctionExpression | MethodDeclaration) { Debug.assert(node.kind !== SyntaxKind.MethodDeclaration || isObjectLiteralMethod(node)); - let isAsync = isAsyncFunctionLike(node); + const isAsync = isAsyncFunctionLike(node); if (isAsync) { emitAwaiter = true; } - let returnType = node.type && getTypeFromTypeNode(node.type); + const returnType = node.type && getTypeFromTypeNode(node.type); let promisedType: Type; if (returnType && isAsync) { promisedType = checkAsyncFunctionReturnType(node); } if (returnType && !node.asteriskToken) { - checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); } if (node.body) { @@ -9765,10 +9764,10 @@ namespace ts { // should not be checking assignability of a promise to the return type. Instead, we need to // check assignability of the awaited type of the expression body against the promised type of // its return type annotation. - let exprType = checkExpression(node.body); + const exprType = checkExpression(node.body); if (returnType) { if (isAsync) { - let awaitedType = checkAwaitedType(exprType, node.body, Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); + const awaitedType = checkAwaitedType(exprType, node.body, Diagnostics.Expression_body_for_async_arrow_function_does_not_have_a_valid_callable_then_member); checkTypeAssignableTo(awaitedType, promisedType, node.body); } else { @@ -9791,7 +9790,7 @@ namespace ts { function checkReferenceExpression(n: Node, invalidReferenceMessage: DiagnosticMessage, constantVariableMessage: DiagnosticMessage): boolean { function findSymbol(n: Node): Symbol { - let symbol = getNodeLinks(n).resolvedSymbol; + const symbol = getNodeLinks(n).resolvedSymbol; // Because we got the symbol from the resolvedSymbol property, it might be of kind // SymbolFlags.ExportValue. In this case it is necessary to get the actual export // symbol, which will have the correct flags set on it. @@ -9807,14 +9806,14 @@ namespace ts { // All other expression constructs described in this chapter are classified as values. switch (n.kind) { case SyntaxKind.Identifier: { - let symbol = findSymbol(n); + const symbol = findSymbol(n); // TypeScript 1.0 spec (April 2014): 4.3 // An identifier expression that references a variable or parameter is classified as a reference. // An identifier expression that references any other kind of entity is classified as a value(and therefore cannot be the target of an assignment). return !symbol || symbol === unknownSymbol || symbol === argumentsSymbol || (symbol.flags & SymbolFlags.Variable) !== 0; } case SyntaxKind.PropertyAccessExpression: { - let symbol = findSymbol(n); + const symbol = findSymbol(n); // TypeScript 1.0 spec (April 2014): 4.10 // A property access expression is always classified as a reference. // NOTE (not in spec): assignment to enum members should not be allowed @@ -9834,15 +9833,15 @@ namespace ts { switch (n.kind) { case SyntaxKind.Identifier: case SyntaxKind.PropertyAccessExpression: { - let symbol = findSymbol(n); + const symbol = findSymbol(n); return symbol && (symbol.flags & SymbolFlags.Variable) !== 0 && (getDeclarationFlagsFromSymbol(symbol) & NodeFlags.Const) !== 0; } case SyntaxKind.ElementAccessExpression: { - let index = (n).argumentExpression; - let symbol = findSymbol((n).expression); + const index = (n).argumentExpression; + const symbol = findSymbol((n).expression); if (symbol && index && index.kind === SyntaxKind.StringLiteral) { - let name = (index).text; - let prop = getPropertyOfType(getTypeOfSymbol(symbol), name); + const name = (index).text; + const prop = getPropertyOfType(getTypeOfSymbol(symbol), name); return prop && (prop.flags & SymbolFlags.Variable) !== 0 && (getDeclarationFlagsFromSymbol(prop) & NodeFlags.Const) !== 0; } return false; @@ -9894,12 +9893,12 @@ namespace ts { } } - let operandType = checkExpression(node.expression); + const operandType = checkExpression(node.expression); return checkAwaitedType(operandType, node); } function checkPrefixUnaryExpression(node: PrefixUnaryExpression): Type { - let operandType = checkExpression(node.operand); + const operandType = checkExpression(node.operand); switch (node.operator) { case SyntaxKind.PlusToken: case SyntaxKind.MinusToken: @@ -9912,7 +9911,7 @@ namespace ts { return booleanType; case SyntaxKind.PlusPlusToken: case SyntaxKind.MinusMinusToken: - let ok = checkArithmeticOperandType(node.operand, operandType, Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + const ok = checkArithmeticOperandType(node.operand, operandType, Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, @@ -9925,8 +9924,8 @@ namespace ts { } function checkPostfixUnaryExpression(node: PostfixUnaryExpression): Type { - let operandType = checkExpression(node.operand); - let ok = checkArithmeticOperandType(node.operand, operandType, Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); + const operandType = checkExpression(node.operand); + const ok = checkArithmeticOperandType(node.operand, operandType, Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_or_an_enum_type); if (ok) { // run check only if former checks succeeded to avoid reporting cascading errors checkReferenceExpression(node.operand, @@ -9943,8 +9942,8 @@ namespace ts { return true; } if (type.flags & TypeFlags.UnionOrIntersection) { - let types = (type).types; - for (let current of types) { + const types = (type).types; + for (const current of types) { if (current.flags & kind) { return true; } @@ -9960,8 +9959,8 @@ namespace ts { return true; } if (type.flags & TypeFlags.UnionOrIntersection) { - let types = (type).types; - for (let current of types) { + const types = (type).types; + for (const current of types) { if (!(current.flags & kind)) { return false; } @@ -10010,12 +10009,12 @@ namespace ts { } function checkObjectLiteralAssignment(node: ObjectLiteralExpression, sourceType: Type, contextualMapper?: TypeMapper): Type { - let properties = node.properties; - for (let p of properties) { + const properties = node.properties; + for (const p of properties) { if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) { // TODO(andersh): Computed property support - let name = (p).name; - let type = isTypeAny(sourceType) + const name = (p).name; + const type = isTypeAny(sourceType) ? sourceType : getTypeOfPropertyOfType(sourceType, name.text) || isNumericLiteralName(name.text) && getIndexTypeOfType(sourceType, IndexKind.Number) || @@ -10043,14 +10042,14 @@ namespace ts { // This elementType will be used if the specific property corresponding to this index is not // present (aka the tuple element property). This call also checks that the parentType is in // fact an iterable or array (depending on target language). - let elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false) || unknownType; - let elements = node.elements; + const elementType = checkIteratedTypeOrElementType(sourceType, node, /*allowStringInput*/ false) || unknownType; + const elements = node.elements; for (let i = 0; i < elements.length; i++) { - let e = elements[i]; + const e = elements[i]; if (e.kind !== SyntaxKind.OmittedExpression) { if (e.kind !== SyntaxKind.SpreadElementExpression) { - let propName = "" + i; - let type = isTypeAny(sourceType) + const propName = "" + i; + const type = isTypeAny(sourceType) ? sourceType : isTupleLikeType(sourceType) ? getTypeOfPropertyOfType(sourceType, propName) @@ -10072,7 +10071,7 @@ namespace ts { error(e, Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } else { - let restExpression = (e).expression; + const restExpression = (e).expression; if (restExpression.kind === SyntaxKind.BinaryExpression && (restExpression).operatorToken.kind === SyntaxKind.EqualsToken) { error((restExpression).operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer); } @@ -10113,7 +10112,7 @@ namespace ts { } function checkReferenceAssignment(target: Expression, sourceType: Type, contextualMapper?: TypeMapper): Type { - let targetType = checkExpression(target, contextualMapper); + const targetType = checkExpression(target, contextualMapper); if (checkReferenceExpression(target, Diagnostics.Invalid_left_hand_side_of_assignment_expression, Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant)) { checkTypeAssignableTo(sourceType, targetType, target, /*headMessage*/ undefined); } @@ -10125,7 +10124,7 @@ namespace ts { } function checkBinaryLikeExpression(left: Expression, operatorToken: Node, right: Expression, contextualMapper?: TypeMapper, errorNode?: Node) { - let operator = operatorToken.kind; + const operator = operatorToken.kind; if (operator === SyntaxKind.EqualsToken && (left.kind === SyntaxKind.ObjectLiteralExpression || left.kind === SyntaxKind.ArrayLiteralExpression)) { return checkDestructuringAssignment(left, checkExpression(right, contextualMapper), contextualMapper); } @@ -10173,8 +10172,8 @@ namespace ts { } else { // otherwise just check each operand separately and report errors as normal - let leftOk = checkArithmeticOperandType(left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); - let rightOk = checkArithmeticOperandType(right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + const leftOk = checkArithmeticOperandType(left, leftType, Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); + const rightOk = checkArithmeticOperandType(right, rightType, Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_or_an_enum_type); if (leftOk && rightOk) { checkAssignmentOperator(numberType); } @@ -10256,7 +10255,7 @@ namespace ts { // Return true if there was no error, false if there was an error. function checkForDisallowedESSymbolOperand(operator: SyntaxKind): boolean { - let offendingSymbolOperand = + const offendingSymbolOperand = someConstituentTypeHasKind(leftType, TypeFlags.ESSymbol) ? left : someConstituentTypeHasKind(rightType, TypeFlags.ESSymbol) ? right : undefined; @@ -10292,7 +10291,7 @@ namespace ts { // requires VarExpr to be classified as a reference // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1) // and the type of the non - compound operation to be assignable to the type of VarExpr. - let ok = checkReferenceExpression(left, Diagnostics.Invalid_left_hand_side_of_assignment_expression, Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); + const ok = checkReferenceExpression(left, Diagnostics.Invalid_left_hand_side_of_assignment_expression, Diagnostics.Left_hand_side_of_assignment_expression_cannot_be_a_constant); // Use default messages if (ok) { // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported @@ -10337,13 +10336,13 @@ namespace ts { } if (node.expression) { - let func = getContainingFunction(node); + const func = getContainingFunction(node); // If the user's code is syntactically correct, the func should always have a star. After all, // we are in a yield context. if (func && func.asteriskToken) { - let expressionType = checkExpressionCached(node.expression, /*contextualMapper*/ undefined); + const expressionType = checkExpressionCached(node.expression, /*contextualMapper*/ undefined); let expressionElementType: Type; - let nodeIsYieldStar = !!node.asteriskToken; + const nodeIsYieldStar = !!node.asteriskToken; if (nodeIsYieldStar) { expressionElementType = checkElementTypeOfIterable(expressionType, node.expression); } @@ -10351,7 +10350,7 @@ namespace ts { // has no explicit return type because the return type is directly computed // from the yield expressions. if (func.type) { - let signatureElementType = getElementTypeOfIterableIterator(getTypeFromTypeNode(func.type)) || anyType; + const signatureElementType = getElementTypeOfIterableIterator(getTypeFromTypeNode(func.type)) || anyType; if (nodeIsYieldStar) { checkTypeAssignableTo(expressionElementType, signatureElementType, node.expression, /*headMessage*/ undefined); } @@ -10368,8 +10367,8 @@ namespace ts { function checkConditionalExpression(node: ConditionalExpression, contextualMapper?: TypeMapper): Type { checkExpression(node.condition); - let type1 = checkExpression(node.whenTrue, contextualMapper); - let type2 = checkExpression(node.whenFalse, contextualMapper); + const type1 = checkExpression(node.whenTrue, contextualMapper); + const type2 = checkExpression(node.whenFalse, contextualMapper); return getUnionType([type1, type2]); } @@ -10387,15 +10386,15 @@ namespace ts { } function checkExpressionWithContextualType(node: Expression, contextualType: Type, contextualMapper?: TypeMapper): Type { - let saveContextualType = node.contextualType; + const saveContextualType = node.contextualType; node.contextualType = contextualType; - let result = checkExpression(node, contextualMapper); + const result = checkExpression(node, contextualMapper); node.contextualType = saveContextualType; return result; } function checkExpressionCached(node: Expression, contextualMapper?: TypeMapper): Type { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.resolvedType) { links.resolvedType = checkExpression(node, contextualMapper); } @@ -10424,17 +10423,17 @@ namespace ts { checkComputedPropertyName(node.name); } - let uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); + const uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } function instantiateTypeWithSingleGenericCallSignature(node: Expression | MethodDeclaration, type: Type, contextualMapper?: TypeMapper) { if (isInferentialContext(contextualMapper)) { - let signature = getSingleCallSignature(type); + const signature = getSingleCallSignature(type); if (signature && signature.typeParameters) { - let contextualType = getContextualType(node); + const contextualType = getContextualType(node); if (contextualType) { - let contextualSignature = getSingleCallSignature(contextualType); + const contextualSignature = getSingleCallSignature(contextualType); if (contextualSignature && !contextualSignature.typeParameters) { return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, contextualMapper)); } @@ -10458,7 +10457,7 @@ namespace ts { type = checkQualifiedName(node); } else { - let uninstantiatedType = checkExpressionWorker(node, contextualMapper); + const uninstantiatedType = checkExpressionWorker(node, contextualMapper); type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } @@ -10467,7 +10466,7 @@ namespace ts { // - 'left' in property access // - 'object' in indexed access // - target in rhs of import statement - let ok = + const ok = (node.parent.kind === SyntaxKind.PropertyAccessExpression && (node.parent).expression === node) || (node.parent.kind === SyntaxKind.ElementAccessExpression && (node.parent).expression === node) || ((node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName) && isInRightSideOfImportOrExportAssignment(node)); @@ -10621,7 +10620,7 @@ namespace ts { function getTypePredicateParameterIndex(parameterList: NodeArray, parameter: Identifier): number { if (parameterList) { for (let i = 0; i < parameterList.length; i++) { - let param = parameterList[i]; + const param = parameterList[i]; if (param.name.kind === SyntaxKind.Identifier && (param.name).text === parameter.text) { @@ -10664,8 +10663,8 @@ namespace ts { if (node.type) { if (node.type.kind === SyntaxKind.TypePredicate) { - let typePredicate = getSignatureFromDeclaration(node).typePredicate; - let typePredicateNode = node.type; + const typePredicate = getSignatureFromDeclaration(node).typePredicate; + const typePredicateNode = node.type; if (isInLegalTypePredicatePosition(typePredicateNode)) { if (typePredicate.parameterIndex >= 0) { if (node.parameters[typePredicate.parameterIndex].dotDotDotToken) { @@ -10688,7 +10687,7 @@ namespace ts { param.name.kind === SyntaxKind.ArrayBindingPattern) { (function checkBindingPattern(pattern: BindingPattern) { - for (let element of pattern.elements) { + for (const element of pattern.elements) { if (element.name.kind === SyntaxKind.Identifier && (element.name).text === typePredicate.parameterName) { @@ -10739,13 +10738,13 @@ namespace ts { if (node.type) { if (languageVersion >= ScriptTarget.ES6 && isSyntacticallyValidGenerator(node)) { - let returnType = getTypeFromTypeNode(node.type); + const returnType = getTypeFromTypeNode(node.type); if (returnType === voidType) { error(node.type, Diagnostics.A_generator_cannot_have_a_void_type_annotation); } else { - let generatorElementType = getElementTypeOfIterableIterator(returnType) || anyType; - let iterableIteratorInstantiation = createIterableIteratorType(generatorElementType); + const generatorElementType = getElementTypeOfIterableIterator(returnType) || anyType; + const iterableIteratorInstantiation = createIterableIteratorType(generatorElementType); // Naively, one could check that IterableIterator is assignable to the return type annotation. // However, that would not catch the error in the following case. @@ -10764,7 +10763,7 @@ namespace ts { function checkTypeForDuplicateIndexSignatures(node: Node) { if (node.kind === SyntaxKind.InterfaceDeclaration) { - let nodeSymbol = getSymbolOfNode(node); + const nodeSymbol = getSymbolOfNode(node); // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration // to prevent this run check only for the first declaration of a given kind if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) { @@ -10775,12 +10774,12 @@ namespace ts { // TypeScript 1.0 spec (April 2014) // 3.7.4: An object type can contain at most one string index signature and one numeric index signature. // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration - let indexSymbol = getIndexSymbol(getSymbolOfNode(node)); + const indexSymbol = getIndexSymbol(getSymbolOfNode(node)); if (indexSymbol) { let seenNumericIndexer = false; let seenStringIndexer = false; - for (let decl of indexSymbol.declarations) { - let declaration = decl; + for (const decl of indexSymbol.declarations) { + const declaration = decl; if (declaration.parameters.length === 1 && declaration.parameters[0].type) { switch (declaration.parameters[0].type.kind) { case SyntaxKind.StringKeyword: @@ -10834,8 +10833,8 @@ namespace ts { checkSourceElement(node.body); - let symbol = getSymbolOfNode(node); - let firstDeclaration = getDeclarationOfKind(symbol, node.kind); + const symbol = getSymbolOfNode(node); + const firstDeclaration = getDeclarationOfKind(symbol, node.kind); // Only type check the symbol once if (node === firstDeclaration) { @@ -10890,11 +10889,11 @@ namespace ts { // TS 1.0 spec (April 2014): 8.3.2 // 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. - let containingClassDecl = node.parent; + const containingClassDecl = node.parent; if (getClassExtendsHeritageClauseElement(containingClassDecl)) { - let containingClassSymbol = getSymbolOfNode(containingClassDecl); - let containingClassInstanceType = getDeclaredTypeOfSymbol(containingClassSymbol); - let baseConstructorType = getBaseConstructorTypeOfClass(containingClassInstanceType); + const containingClassSymbol = getSymbolOfNode(containingClassDecl); + const containingClassInstanceType = getDeclaredTypeOfSymbol(containingClassSymbol); + const baseConstructorType = getBaseConstructorTypeOfClass(containingClassInstanceType); if (containsSuperCall(node.body)) { if (baseConstructorType === nullType) { @@ -10906,16 +10905,16 @@ namespace ts { // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. - let superCallShouldBeFirst = + const superCallShouldBeFirst = forEach((node.parent).members, isInstancePropertyWithInitializer) || forEach(node.parameters, p => p.flags & (NodeFlags.Public | NodeFlags.Private | NodeFlags.Protected)); // Skip past any prologue directives to find the first statement // to ensure that it was a super call. if (superCallShouldBeFirst) { - let statements = (node.body).statements; + const statements = (node.body).statements; let superCallStatement: ExpressionStatement; - for (let statement of statements) { + for (const statement of statements) { if (statement.kind === SyntaxKind.ExpressionStatement && isSuperCallExpression((statement).expression)) { superCallStatement = statement; break; @@ -10945,23 +10944,30 @@ namespace ts { checkGrammarFunctionLikeDeclaration(node) || checkGrammarAccessor(node) || checkGrammarComputedPropertyName(node.name); if (node.kind === SyntaxKind.GetAccessor) { - if (!isInAmbientContext(node) && nodeIsPresent(node.body) && !(bodyContainsAReturnStatement(node.body) || bodyContainsSingleThrowStatement(node.body))) { - error(node.name, Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); + if (!isInAmbientContext(node) && nodeIsPresent(node.body) && (node.flags & NodeFlags.HasImplicitReturn)) { + if (node.flags & NodeFlags.HasExplicitReturn) { + if (compilerOptions.noImplicitReturns) { + error(node.name, Diagnostics.Not_all_code_paths_return_a_value); + } + } + else { + error(node.name, Diagnostics.A_get_accessor_must_return_a_value); + } } } if (!hasDynamicName(node)) { // TypeScript 1.0 spec (April 2014): 8.4.3 // Accessors for the same member name must specify the same accessibility. - let otherKind = node.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; - let otherAccessor = getDeclarationOfKind(node.symbol, otherKind); + const otherKind = node.kind === SyntaxKind.GetAccessor ? SyntaxKind.SetAccessor : SyntaxKind.GetAccessor; + const otherAccessor = getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { if (((node.flags & NodeFlags.AccessibilityModifier) !== (otherAccessor.flags & NodeFlags.AccessibilityModifier))) { error(node.name, Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility); } - let currentAccessorType = getAnnotatedAccessorType(node); - let otherAccessorType = getAnnotatedAccessorType(otherAccessor); + const currentAccessorType = getAnnotatedAccessorType(node); + const otherAccessorType = getAnnotatedAccessorType(otherAccessor); // TypeScript 1.0 spec (April 2014): 4.5 // If both accessors include type annotations, the specified types must be identical. if (currentAccessorType && otherAccessorType) { @@ -10984,9 +10990,9 @@ namespace ts { function checkTypeArgumentConstraints(typeParameters: TypeParameter[], typeArguments: TypeNode[]): boolean { let result = true; for (let i = 0; i < typeParameters.length; i++) { - let constraint = getConstraintOfTypeParameter(typeParameters[i]); + const constraint = getConstraintOfTypeParameter(typeParameters[i]); if (constraint) { - let typeArgument = typeArguments[i]; + const typeArgument = typeArguments[i]; result = result && checkTypeAssignableTo(getTypeFromTypeNode(typeArgument), constraint, typeArgument, Diagnostics.Type_0_does_not_satisfy_the_constraint_1); } } @@ -10995,13 +11001,13 @@ namespace ts { function checkTypeReferenceNode(node: TypeReferenceNode | ExpressionWithTypeArguments) { checkGrammarTypeArguments(node, node.typeArguments); - let type = getTypeFromTypeReference(node); + const type = getTypeFromTypeReference(node); if (type !== unknownType && node.typeArguments) { // Do type argument local checks only if referenced type is successfully resolved forEach(node.typeArguments, checkSourceElement); if (produceDiagnostics) { - let symbol = getNodeLinks(node).resolvedSymbol; - let typeParameters = symbol.flags & SymbolFlags.TypeAlias ? getSymbolLinks(symbol).typeParameters : (type).target.localTypeParameters; + const symbol = getNodeLinks(node).resolvedSymbol; + const typeParameters = symbol.flags & SymbolFlags.TypeAlias ? getSymbolLinks(symbol).typeParameters : (type).target.localTypeParameters; checkTypeArgumentConstraints(typeParameters, node.typeArguments); } } @@ -11014,7 +11020,7 @@ namespace ts { function checkTypeLiteral(node: TypeLiteralNode) { forEach(node.members, checkSourceElement); if (produceDiagnostics) { - let type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); + const type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node); checkIndexConstraints(type); checkTypeForDuplicateIndexSignatures(node); } @@ -11026,7 +11032,7 @@ namespace ts { function checkTupleType(node: TupleTypeNode) { // Grammar checking - let hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); + const hasErrorFromDisallowedTrailingComma = checkGrammarForDisallowedTrailingComma(node.elementTypes); if (!hasErrorFromDisallowedTrailingComma && node.elementTypes.length === 0) { grammarErrorOnNode(node, Diagnostics.A_tuple_type_element_list_cannot_be_empty); } @@ -11046,7 +11052,7 @@ namespace ts { if (!produceDiagnostics) { return; } - let signature = getSignatureFromDeclaration(signatureDeclarationNode); + const signature = getSignatureFromDeclaration(signatureDeclarationNode); if (!signature.hasStringLiterals) { return; } @@ -11066,16 +11072,16 @@ namespace ts { // Use declaring type to obtain full list of signatures. if (!signatureDeclarationNode.name && signatureDeclarationNode.parent && signatureDeclarationNode.parent.kind === SyntaxKind.InterfaceDeclaration) { Debug.assert(signatureDeclarationNode.kind === SyntaxKind.CallSignature || signatureDeclarationNode.kind === SyntaxKind.ConstructSignature); - let signatureKind = signatureDeclarationNode.kind === SyntaxKind.CallSignature ? SignatureKind.Call : SignatureKind.Construct; - let containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); - let containingType = getDeclaredTypeOfSymbol(containingSymbol); + const signatureKind = signatureDeclarationNode.kind === SyntaxKind.CallSignature ? SignatureKind.Call : SignatureKind.Construct; + const containingSymbol = getSymbolOfNode(signatureDeclarationNode.parent); + const containingType = getDeclaredTypeOfSymbol(containingSymbol); signaturesToCheck = getSignaturesOfType(containingType, signatureKind); } else { signaturesToCheck = getSignaturesOfSymbol(getSymbolOfNode(signatureDeclarationNode)); } - for (let otherSignature of signaturesToCheck) { + for (const otherSignature of signaturesToCheck) { if (!otherSignature.hasStringLiterals && isSignatureAssignableTo(signature, otherSignature)) { return; } @@ -11114,19 +11120,19 @@ namespace ts { // The caveat is that if some overloads are defined in lib.d.ts, we don't want to // report the errors on those. To achieve this, we will say that the implementation is // the canonical signature only if it is in the same container as the first overload - let implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; + const implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent; return implementationSharesContainerWithFirstOverload ? implementation : overloads[0]; } function checkFlagAgreementBetweenOverloads(overloads: Declaration[], implementation: FunctionLikeDeclaration, flagsToCheck: NodeFlags, someOverloadFlags: NodeFlags, allOverloadFlags: NodeFlags): void { // Error if some overloads have a flag that is not shared by all overloads. To find the // deviations, we XOR someOverloadFlags with allOverloadFlags - let someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; + const someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags; if (someButNotAllOverloadFlags !== 0) { - let canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); + const canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck); forEach(overloads, o => { - let deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; + const deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags; if (deviation & NodeFlags.Export) { error(o.name, Diagnostics.Overload_signatures_must_all_be_exported_or_not_exported); } @@ -11145,9 +11151,9 @@ namespace ts { function checkQuestionTokenAgreementBetweenOverloads(overloads: Declaration[], implementation: FunctionLikeDeclaration, someHaveQuestionToken: boolean, allHaveQuestionToken: boolean): void { if (someHaveQuestionToken !== allHaveQuestionToken) { - let canonicalHasQuestionToken = hasQuestionToken(getCanonicalOverload(overloads, implementation)); + const canonicalHasQuestionToken = hasQuestionToken(getCanonicalOverload(overloads, implementation)); forEach(overloads, o => { - let deviation = hasQuestionToken(o) !== canonicalHasQuestionToken; + const deviation = hasQuestionToken(o) !== canonicalHasQuestionToken; if (deviation) { error(o.name, Diagnostics.Overload_signatures_must_all_be_optional_or_required); } @@ -11155,7 +11161,7 @@ namespace ts { } } - let flagsToCheck: NodeFlags = NodeFlags.Export | NodeFlags.Ambient | NodeFlags.Private | NodeFlags.Protected | NodeFlags.Abstract; + const flagsToCheck: NodeFlags = NodeFlags.Export | NodeFlags.Ambient | NodeFlags.Private | NodeFlags.Protected | NodeFlags.Abstract; let someNodeFlags: NodeFlags = 0; let allNodeFlags = flagsToCheck; let someHaveQuestionToken = false; @@ -11165,8 +11171,8 @@ namespace ts { let lastSeenNonAmbientDeclaration: FunctionLikeDeclaration; let previousDeclaration: FunctionLikeDeclaration; - let declarations = symbol.declarations; - let isConstructor = (symbol.flags & SymbolFlags.Constructor) !== 0; + const declarations = symbol.declarations; + const isConstructor = (symbol.flags & SymbolFlags.Constructor) !== 0; function reportImplementationExpectedError(node: FunctionLikeDeclaration): void { if (node.name && nodeIsMissing(node.name)) { @@ -11174,7 +11180,7 @@ namespace ts { } let seen = false; - let subsequentNode = forEachChild(node.parent, c => { + const subsequentNode = forEachChild(node.parent, c => { if (seen) { return c; } @@ -11184,13 +11190,13 @@ namespace ts { }); if (subsequentNode) { if (subsequentNode.kind === node.kind) { - let errorNode: Node = (subsequentNode).name || subsequentNode; + const errorNode: Node = (subsequentNode).name || subsequentNode; // TODO(jfreeman): These are methods, so handle computed name case if (node.name && (subsequentNode).name && (node.name).text === ((subsequentNode).name).text) { // the only situation when this is possible (same kind\same name but different symbol) - mixed static and instance class members Debug.assert(node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature); Debug.assert((node.flags & NodeFlags.Static) !== (subsequentNode.flags & NodeFlags.Static)); - let diagnostic = node.flags & NodeFlags.Static ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static; + const diagnostic = node.flags & NodeFlags.Static ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static; error(errorNode, diagnostic); return; } @@ -11200,7 +11206,7 @@ namespace ts { } } } - let errorNode: Node = node.name || node; + const errorNode: Node = node.name || node; if (isConstructor) { error(errorNode, Diagnostics.Constructor_implementation_is_missing); } @@ -11218,13 +11224,13 @@ namespace ts { // when checking exported function declarations across modules check only duplicate implementations // names and consistency of modifiers are verified when we check local symbol - let isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & SymbolFlags.Module; + const isExportSymbolInsideModule = symbol.parent && symbol.parent.flags & SymbolFlags.Module; let duplicateFunctionDeclaration = false; let multipleConstructorImplementation = false; - for (let current of declarations) { - let node = current; - let inAmbientContext = isInAmbientContext(node); - let inAmbientContextOrInterface = node.parent.kind === SyntaxKind.InterfaceDeclaration || node.parent.kind === SyntaxKind.TypeLiteral || inAmbientContext; + for (const current of declarations) { + const node = current; + const inAmbientContext = isInAmbientContext(node); + const inAmbientContextOrInterface = node.parent.kind === SyntaxKind.InterfaceDeclaration || node.parent.kind === SyntaxKind.TypeLiteral || inAmbientContext; if (inAmbientContextOrInterface) { // check if declarations are consecutive only if they are non-ambient // 1. ambient declarations can be interleaved @@ -11237,7 +11243,7 @@ namespace ts { } if (node.kind === SyntaxKind.FunctionDeclaration || node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature || node.kind === SyntaxKind.Constructor) { - let currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); + const currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck); someNodeFlags |= currentNodeFlags; allNodeFlags &= currentNodeFlags; someHaveQuestionToken = someHaveQuestionToken || hasQuestionToken(node); @@ -11295,8 +11301,8 @@ namespace ts { checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken); if (bodyDeclaration) { - let signatures = getSignaturesOfSymbol(symbol); - let bodySignature = getSignatureFromDeclaration(bodyDeclaration); + const signatures = getSignaturesOfSymbol(symbol); + const bodySignature = getSignatureFromDeclaration(bodyDeclaration); // If the implementation signature has string literals, we will have reported an error in // checkSpecializedSignatureDeclaration if (!bodySignature.hasStringLiterals) { @@ -11314,7 +11320,7 @@ namespace ts { // function g(x: string, y: string) { } // // The implementation is completely unrelated to the specialized signature, yet we do not check this. - for (let signature of signatures) { + for (const signature of signatures) { if (!signature.hasStringLiterals && !isSignatureAssignableTo(bodySignature, signature)) { error(signature.declaration, Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -11352,9 +11358,9 @@ namespace ts { let exportedDeclarationSpaces = SymbolFlags.None; let nonExportedDeclarationSpaces = SymbolFlags.None; let defaultExportedDeclarationSpaces = SymbolFlags.None; - for (let d of symbol.declarations) { - let declarationSpaces = getDeclarationSpaces(d); - let effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, NodeFlags.Export | NodeFlags.Default); + for (const d of symbol.declarations) { + const declarationSpaces = getDeclarationSpaces(d); + const effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, NodeFlags.Export | NodeFlags.Default); if (effectiveDeclarationFlags & NodeFlags.Export) { if (effectiveDeclarationFlags & NodeFlags.Default) { @@ -11370,15 +11376,15 @@ namespace ts { } // Spaces for anyting not declared a 'default export'. - let nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + const nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; - let commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; - let commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; + const commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + const commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { // declaration spaces for exported and non-exported declarations intersect - for (let d of symbol.declarations) { - let declarationSpaces = getDeclarationSpaces(d); + for (const d of symbol.declarations) { + const declarationSpaces = getDeclarationSpaces(d); // Only error on the declarations that conributed to the intersecting spaces. if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { @@ -11403,7 +11409,7 @@ namespace ts { return SymbolFlags.ExportType | SymbolFlags.ExportValue; case SyntaxKind.ImportEqualsDeclaration: let result: SymbolFlags = 0; - let target = resolveAlias(getSymbolOfNode(d)); + const target = resolveAlias(getSymbolOfNode(d)); forEach(target.declarations, d => { result |= getDeclarationSpaces(d); }); return result; default: @@ -11453,32 +11459,32 @@ namespace ts { return (promise).typeArguments[0]; } - let globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); + const globalPromiseLikeType = getInstantiatedGlobalPromiseLikeType(); if (globalPromiseLikeType === emptyObjectType || !isTypeAssignableTo(promise, globalPromiseLikeType)) { return undefined; } - let thenFunction = getTypeOfPropertyOfType(promise, "then"); + const thenFunction = getTypeOfPropertyOfType(promise, "then"); if (thenFunction && (thenFunction.flags & TypeFlags.Any)) { return undefined; } - let thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, SignatureKind.Call) : emptyArray; + const thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, SignatureKind.Call) : emptyArray; if (thenSignatures.length === 0) { return undefined; } - let onfulfilledParameterType = getUnionType(map(thenSignatures, getTypeOfFirstParameterOfSignature)); + const onfulfilledParameterType = getUnionType(map(thenSignatures, getTypeOfFirstParameterOfSignature)); if (onfulfilledParameterType.flags & TypeFlags.Any) { return undefined; } - let onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, SignatureKind.Call); + const onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, SignatureKind.Call); if (onfulfilledParameterSignatures.length === 0) { return undefined; } - let valueParameterType = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); + const valueParameterType = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature)); return valueParameterType; } @@ -11502,15 +11508,15 @@ namespace ts { function checkAwaitedTypeWorker(type: Type): Type { if (type.flags & TypeFlags.Union) { - let types: Type[] = []; - for (let constituentType of (type).types) { + const types: Type[] = []; + for (const constituentType of (type).types) { types.push(checkAwaitedTypeWorker(constituentType)); } return getUnionType(types); } else { - let promisedType = getPromisedType(type); + const promisedType = getPromisedType(type); if (promisedType === undefined) { // The type was not a PromiseLike, so it could not be unwrapped any further. // As long as the type does not have a callable "then" property, it is @@ -11577,7 +11583,7 @@ namespace ts { // Keep track of the type we're about to unwrap to avoid bad recursive promise types. // See the comments above for more information. awaitedTypeStack.push(type.id); - let awaitedType = checkAwaitedTypeWorker(promisedType); + const awaitedType = checkAwaitedTypeWorker(promisedType); awaitedTypeStack.pop(); return awaitedType; } @@ -11599,7 +11605,7 @@ namespace ts { * callable `then` signature. */ function checkAsyncFunctionReturnType(node: FunctionLikeDeclaration): Type { - let globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); + const globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(); if (globalPromiseConstructorLikeType === emptyObjectType) { // If we couldn't resolve the global PromiseConstructorLike type we cannot verify // compatibility with __awaiter. @@ -11633,16 +11639,16 @@ namespace ts { // When we get the type of the `Promise` symbol here, we get the type of the static // side of the `Promise` class, which would be `{ new (...): Promise }`. - let promiseType = getTypeFromTypeNode(node.type); + const promiseType = getTypeFromTypeNode(node.type); if (promiseType === unknownType && compilerOptions.isolatedModules) { // If we are compiling with isolatedModules, we may not be able to resolve the // type as a value. As such, we will just return unknownType; return unknownType; } - let promiseConstructor = getNodeLinks(node.type).resolvedSymbol; + const promiseConstructor = getNodeLinks(node.type).resolvedSymbol; if (!promiseConstructor || !symbolIsValue(promiseConstructor)) { - let typeName = promiseConstructor + const typeName = promiseConstructor ? symbolToString(promiseConstructor) : typeToString(promiseType); error(node, Diagnostics.Type_0_is_not_a_valid_async_function_return_type, typeName); @@ -11650,15 +11656,15 @@ namespace ts { } // Validate the promise constructor type. - let promiseConstructorType = getTypeOfSymbol(promiseConstructor); + const promiseConstructorType = getTypeOfSymbol(promiseConstructor); if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, node, Diagnostics.Type_0_is_not_a_valid_async_function_return_type)) { return unknownType; } // Verify there is no local declaration that could collide with the promise constructor. - let promiseName = getEntityNameFromTypeNode(node.type); - let root = getFirstIdentifier(promiseName); - let rootSymbol = getSymbol(node.locals, root.text, SymbolFlags.Value); + const promiseName = getEntityNameFromTypeNode(node.type); + const root = getFirstIdentifier(promiseName); + const rootSymbol = getSymbol(node.locals, root.text, SymbolFlags.Value); if (rootSymbol) { error(rootSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, root.text, @@ -11672,19 +11678,19 @@ namespace ts { /** Check a decorator */ function checkDecorator(node: Decorator): void { - let signature = getResolvedSignature(node); - let returnType = getReturnTypeOfSignature(signature); + const signature = getResolvedSignature(node); + const returnType = getReturnTypeOfSignature(signature); if (returnType.flags & TypeFlags.Any) { return; } let expectedReturnType: Type; - let headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); + const headMessage = getDiagnosticHeadMessageForDecoratorResolution(node); let errorInfo: DiagnosticMessageChain; switch (node.parent.kind) { case SyntaxKind.ClassDeclaration: - let classSymbol = getSymbolOfNode(node.parent); - let classConstructorType = getTypeOfSymbol(classSymbol); + const classSymbol = getSymbolOfNode(node.parent); + const classConstructorType = getTypeOfSymbol(classSymbol); expectedReturnType = getUnionType([classConstructorType, voidType]); break; @@ -11706,8 +11712,8 @@ namespace ts { case SyntaxKind.MethodDeclaration: case SyntaxKind.GetAccessor: case SyntaxKind.SetAccessor: - let methodType = getTypeOfNode(node.parent); - let descriptorType = createTypedPropertyDescriptorType(methodType); + const methodType = getTypeOfNode(node.parent); + const descriptorType = createTypedPropertyDescriptorType(methodType); expectedReturnType = getUnionType([descriptorType, voidType]); break; } @@ -11726,13 +11732,13 @@ namespace ts { // as if it were an expression so that we can emit the type in a value position when we // serialize the type metadata. if (node && node.kind === SyntaxKind.TypeReference) { - let root = getFirstIdentifier((node).typeName); - let meaning = root.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; + const root = getFirstIdentifier((node).typeName); + const meaning = root.parent.kind === SyntaxKind.TypeReference ? SymbolFlags.Type : SymbolFlags.Namespace; // Resolve type so we know which symbol is referenced - let rootSymbol = resolveName(root, root.text, meaning | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); + const rootSymbol = resolveName(root, root.text, meaning | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); // Resolved symbol is alias if (rootSymbol && rootSymbol.flags & SymbolFlags.Alias) { - let aliasTarget = resolveAlias(rootSymbol); + const aliasTarget = resolveAlias(rootSymbol); // If alias has value symbol - mark alias as referenced if (aliasTarget.flags & SymbolFlags.Value && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))) { markAliasSymbolAsReferenced(rootSymbol); @@ -11768,7 +11774,7 @@ namespace ts { /** Checks the type annotation of the parameters of a function/method or the constructor of a class as expressions */ function checkParameterTypeAnnotationsAsExpressions(node: FunctionLikeDeclaration) { // ensure all type annotations with a value declaration are checked as an expression - for (let parameter of node.parameters) { + for (const parameter of node.parameters) { checkTypeAnnotationAsExpression(parameter); } } @@ -11793,7 +11799,7 @@ namespace ts { // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator. switch (node.kind) { case SyntaxKind.ClassDeclaration: - let constructor = getFirstConstructorWithBody(node); + const constructor = getFirstConstructorWithBody(node); if (constructor) { checkParameterTypeAnnotationsAsExpressions(constructor); } @@ -11833,7 +11839,7 @@ namespace ts { function checkFunctionLikeDeclaration(node: FunctionLikeDeclaration): void { checkDecorators(node); checkSignatureDeclaration(node); - let isAsync = isAsyncFunctionLike(node); + const isAsync = isAsyncFunctionLike(node); if (isAsync) { emitAwaiter = true; } @@ -11851,10 +11857,10 @@ namespace ts { // first we want to check the local symbol that contain this declaration // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode - let symbol = getSymbolOfNode(node); - let localSymbol = node.localSymbol || symbol; + const symbol = getSymbolOfNode(node); + const localSymbol = node.localSymbol || symbol; - let firstDeclaration = forEach(symbol.declarations, + const firstDeclaration = forEach(symbol.declarations, // Get first non javascript function declaration declaration => declaration.kind === node.kind && !isJavaScript(getSourceFile(declaration).fileName) ? declaration : undefined); @@ -11875,13 +11881,13 @@ namespace ts { checkSourceElement(node.body); if (node.type && !isAccessor(node.kind) && !node.asteriskToken) { - let returnType = getTypeFromTypeNode(node.type); + const returnType = getTypeFromTypeNode(node.type); let promisedType: Type; if (isAsync) { promisedType = checkAsyncFunctionReturnType(node); } - checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(node, isAsync ? promisedType : returnType); + checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, isAsync ? promisedType : returnType); } if (produceDiagnostics && !node.type) { @@ -11945,7 +11951,7 @@ namespace ts { return false; } - let root = getRootDeclaration(node); + const root = getRootDeclaration(node); if (root.kind === SyntaxKind.Parameter && nodeIsMissing((root.parent).body)) { // just an overload - no codegen impact return false; @@ -11965,7 +11971,7 @@ namespace ts { let current = node; while (current) { if (getNodeCheckFlags(current) & NodeCheckFlags.CaptureThis) { - let isDeclaration = node.kind !== SyntaxKind.Identifier; + const isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { error((node).name, Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference); } @@ -11984,14 +11990,14 @@ namespace ts { } // bubble up and find containing type - let enclosingClass = getContainingClass(node); + const enclosingClass = getContainingClass(node); // if containing type was not found or it is ambient - exit (no codegen) if (!enclosingClass || isInAmbientContext(enclosingClass)) { return; } if (getClassExtendsHeritageClauseElement(enclosingClass)) { - let isDeclaration = node.kind !== SyntaxKind.Identifier; + const isDeclaration = node.kind !== SyntaxKind.Identifier; if (isDeclaration) { error(node, Diagnostics.Duplicate_identifier_super_Compiler_uses_super_to_capture_base_class_reference); } @@ -12012,7 +12018,7 @@ namespace ts { } // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent - let parent = getDeclarationContainer(node); + const parent = getDeclarationContainer(node); if (parent.kind === SyntaxKind.SourceFile && isExternalModule(parent)) { // If the declaration happens to be in external module, report error that require and exports are reserved keywords error(name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, @@ -12035,15 +12041,15 @@ namespace ts { // A non-initialized declaration is a no-op as the block declaration will resolve before the var // declaration. the problem is if the declaration has an initializer. this will act as a write to the // block declared value. this is fine for let, but not const. - // Only consider declarations with initializers, uninitialized let declarations will not + // Only consider declarations with initializers, uninitialized const declarations will not // step on a let/const variable. - // Do not consider let and const declarations, as duplicate block-scoped declarations + // Do not consider const and const declarations, as duplicate block-scoped declarations // are handled by the binder. - // We are only looking for let declarations that step on let\const declarations from a + // We are only looking for const declarations that step on let\const declarations from a // different scope. e.g.: // { // const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration - // let x = 0; // symbol for this declaration will be 'symbol' + // const x = 0; // symbol for this declaration will be 'symbol' // } // skip block-scoped variables and parameters @@ -12058,22 +12064,22 @@ namespace ts { return; } - let symbol = getSymbolOfNode(node); + const symbol = getSymbolOfNode(node); if (symbol.flags & SymbolFlags.FunctionScopedVariable) { - let localDeclarationSymbol = resolveName(node, (node.name).text, SymbolFlags.Variable, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); + const localDeclarationSymbol = resolveName(node, (node.name).text, SymbolFlags.Variable, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & SymbolFlags.BlockScopedVariable) { if (getDeclarationFlagsFromSymbol(localDeclarationSymbol) & NodeFlags.BlockScoped) { - let varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, SyntaxKind.VariableDeclarationList); - let container = + const varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, SyntaxKind.VariableDeclarationList); + const container = varDeclList.parent.kind === SyntaxKind.VariableStatement && varDeclList.parent.parent ? varDeclList.parent.parent : undefined; // names of block-scoped and function scoped variables can collide only // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting) - let namesShareScope = + const namesShareScope = container && (container.kind === SyntaxKind.Block && isFunctionLike(container.parent) || container.kind === SyntaxKind.ModuleBlock || @@ -12085,7 +12091,7 @@ namespace ts { // otherwise if variable has an initializer - show error that initialization will fail // since LHS will be block scoped name instead of function scoped if (!namesShareScope) { - let name = symbolToString(localDeclarationSymbol); + const name = symbolToString(localDeclarationSymbol); error(node, Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name); } } @@ -12099,12 +12105,12 @@ namespace ts { return; } - let func = getContainingFunction(node); + const func = getContainingFunction(node); visit(node.initializer); function visit(n: Node) { if (n.kind === SyntaxKind.Identifier) { - let referencedSymbol = getNodeLinks(n).resolvedSymbol; + const referencedSymbol = getNodeLinks(n).resolvedSymbol; // check FunctionLikeDeclaration.locals (stores parameters\function local variable) // if it contains entry with a specified name and if this entry matches the resolved symbol if (referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol(func.locals, referencedSymbol.name, SymbolFlags.Value) === referencedSymbol) { @@ -12159,8 +12165,8 @@ namespace ts { } return; } - let symbol = getSymbolOfNode(node); - let type = getTypeOfVariableOrParameterOrProperty(symbol); + const symbol = getSymbolOfNode(node); + const type = getTypeOfVariableOrParameterOrProperty(symbol); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer if (node.initializer) { @@ -12171,7 +12177,7 @@ namespace ts { else { // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node - let declarationType = getWidenedTypeForVariableLikeDeclaration(node); + const declarationType = getWidenedTypeForVariableLikeDeclaration(node); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -12293,8 +12299,8 @@ namespace ts { checkForInOrForOfVariableDeclaration(node); } else { - let varExpr = node.initializer; - let iteratedType = checkRightHandSideOfForOf(node.expression); + const varExpr = node.initializer; + const iteratedType = checkRightHandSideOfForOf(node.expression); // There may be a destructuring assignment on the left side if (varExpr.kind === SyntaxKind.ArrayLiteralExpression || varExpr.kind === SyntaxKind.ObjectLiteralExpression) { @@ -12304,7 +12310,7 @@ namespace ts { checkDestructuringAssignment(varExpr, iteratedType || unknownType); } else { - let leftType = checkExpression(varExpr); + const leftType = checkExpression(varExpr); checkReferenceExpression(varExpr, /*invalidReferenceMessage*/ Diagnostics.Invalid_left_hand_side_in_for_of_statement, /*constantVariableMessage*/ Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_be_a_previously_defined_constant); @@ -12331,7 +12337,7 @@ namespace ts { // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, // and Expr must be an expression of type Any, an object type, or a type parameter type. if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { - let variable = (node.initializer).declarations[0]; + const variable = (node.initializer).declarations[0]; if (variable && isBindingPattern(variable.name)) { error(variable.name, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } @@ -12343,8 +12349,8 @@ namespace ts { // for (Var in Expr) Statement // Var must be an expression classified as a reference of type Any or the String primitive type, // and Expr must be an expression of type Any, an object type, or a type parameter type. - let varExpr = node.initializer; - let leftType = checkExpression(varExpr); + const varExpr = node.initializer; + const leftType = checkExpression(varExpr); if (varExpr.kind === SyntaxKind.ArrayLiteralExpression || varExpr.kind === SyntaxKind.ObjectLiteralExpression) { error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern); } @@ -12357,7 +12363,7 @@ namespace ts { } } - let rightType = checkExpression(node.expression); + const rightType = checkExpression(node.expression); // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved // in this case error about missing name is already reported - do not report extra one if (!isTypeAnyOrAllConstituentTypesHaveKind(rightType, TypeFlags.ObjectType | TypeFlags.TypeParameter)) { @@ -12368,16 +12374,16 @@ namespace ts { } function checkForInOrForOfVariableDeclaration(iterationStatement: ForInStatement | ForOfStatement): void { - let variableDeclarationList = iterationStatement.initializer; + const variableDeclarationList = iterationStatement.initializer; // checkGrammarForInOrForOfStatement will check that there is exactly one declaration. if (variableDeclarationList.declarations.length >= 1) { - let decl = variableDeclarationList.declarations[0]; + const decl = variableDeclarationList.declarations[0]; checkVariableDeclaration(decl); } } function checkRightHandSideOfForOf(rhsExpression: Expression): Type { - let expressionType = getTypeOfExpression(rhsExpression); + const expressionType = getTypeOfExpression(rhsExpression); return checkIteratedTypeOrElementType(expressionType, rhsExpression, /*allowStringInput*/ true); } @@ -12395,7 +12401,7 @@ namespace ts { } if (isArrayLikeType(inputType)) { - let indexType = getIndexTypeOfType(inputType, IndexKind.Number); + const indexType = getIndexTypeOfType(inputType, IndexKind.Number); if (indexType) { return indexType; } @@ -12409,7 +12415,7 @@ namespace ts { * When errorNode is undefined, it means we should not report any errors. */ function checkElementTypeOfIterable(iterable: Type, errorNode: Node): Type { - let elementType = getElementTypeOfIterable(iterable, errorNode); + const elementType = getElementTypeOfIterable(iterable, errorNode); // Now even though we have extracted the iteratedType, we will have to validate that the type // passed in is actually an Iterable. if (errorNode && elementType) { @@ -12445,7 +12451,7 @@ namespace ts { return undefined; } - let typeAsIterable = type; + const typeAsIterable = type; if (!typeAsIterable.iterableElementType) { // As an optimization, if the type is instantiated directly using the globalIterableType (Iterable), // then just grab its type argument. @@ -12453,12 +12459,12 @@ namespace ts { typeAsIterable.iterableElementType = (type).typeArguments[0]; } else { - let iteratorFunction = getTypeOfPropertyOfType(type, getPropertyNameForKnownSymbolName("iterator")); + const iteratorFunction = getTypeOfPropertyOfType(type, getPropertyNameForKnownSymbolName("iterator")); if (isTypeAny(iteratorFunction)) { return undefined; } - let iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, SignatureKind.Call) : emptyArray; + const iteratorFunctionSignatures = iteratorFunction ? getSignaturesOfType(iteratorFunction, SignatureKind.Call) : emptyArray; if (iteratorFunctionSignatures.length === 0) { if (errorNode) { error(errorNode, Diagnostics.Type_must_have_a_Symbol_iterator_method_that_returns_an_iterator); @@ -12491,7 +12497,7 @@ namespace ts { return undefined; } - let typeAsIterator = type; + const typeAsIterator = type; if (!typeAsIterator.iteratorElementType) { // As an optimization, if the type is instantiated directly using the globalIteratorType (Iterator), // then just grab its type argument. @@ -12499,12 +12505,12 @@ namespace ts { typeAsIterator.iteratorElementType = (type).typeArguments[0]; } else { - let iteratorNextFunction = getTypeOfPropertyOfType(type, "next"); + const iteratorNextFunction = getTypeOfPropertyOfType(type, "next"); if (isTypeAny(iteratorNextFunction)) { return undefined; } - let iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, SignatureKind.Call) : emptyArray; + const iteratorNextFunctionSignatures = iteratorNextFunction ? getSignaturesOfType(iteratorNextFunction, SignatureKind.Call) : emptyArray; if (iteratorNextFunctionSignatures.length === 0) { if (errorNode) { error(errorNode, Diagnostics.An_iterator_must_have_a_next_method); @@ -12512,12 +12518,12 @@ namespace ts { return undefined; } - let iteratorNextResult = getUnionType(map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); + const iteratorNextResult = getUnionType(map(iteratorNextFunctionSignatures, getReturnTypeOfSignature)); if (isTypeAny(iteratorNextResult)) { return undefined; } - let iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); + const iteratorNextValue = getTypeOfPropertyOfType(iteratorNextResult, "value"); if (!iteratorNextValue) { if (errorNode) { error(errorNode, Diagnostics.The_type_returned_by_the_next_method_of_an_iterator_must_have_a_value_property); @@ -12569,8 +12575,8 @@ namespace ts { // After we remove all types that are StringLike, we will know if there was a string constituent // based on whether the remaining type is the same as the initial type. - let arrayType = removeTypesFromUnionType(arrayOrStringType, TypeFlags.StringLike, /*isTypeOfKind*/ true, /*allowEmptyUnionResult*/ true); - let hasStringConstituent = arrayOrStringType !== arrayType; + const arrayType = removeTypesFromUnionType(arrayOrStringType, TypeFlags.StringLike, /*isTypeOfKind*/ true, /*allowEmptyUnionResult*/ true); + const hasStringConstituent = arrayOrStringType !== arrayType; let reportedError = false; if (hasStringConstituent) { @@ -12592,7 +12598,7 @@ namespace ts { // if the input type is number | string, we want to say that number is not an array type. // But if the input was just number, we want to say that number is not an array type // or a string type. - let diagnostic = hasStringConstituent + const diagnostic = hasStringConstituent ? Diagnostics.Type_0_is_not_an_array_type : Diagnostics.Type_0_is_not_an_array_type_or_a_string_type; error(errorNode, diagnostic, typeToString(arrayType)); @@ -12600,7 +12606,7 @@ namespace ts { return hasStringConstituent ? stringType : unknownType; } - let arrayElementType = getIndexTypeOfType(arrayType, IndexKind.Number) || unknownType; + const arrayElementType = getIndexTypeOfType(arrayType, IndexKind.Number) || unknownType; if (hasStringConstituent) { // This is just an optimization for the case where arrayOrStringType is string | string[] if (arrayElementType.flags & TypeFlags.StringLike) { @@ -12627,18 +12633,18 @@ namespace ts { function checkReturnStatement(node: ReturnStatement) { // Grammar checking if (!checkGrammarStatementInAmbientContext(node)) { - let functionBlock = getContainingFunction(node); + const functionBlock = getContainingFunction(node); if (!functionBlock) { grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_can_only_be_used_within_a_function_body); } } if (node.expression) { - let func = getContainingFunction(node); + const func = getContainingFunction(node); if (func) { - let signature = getSignatureFromDeclaration(func); - let returnType = getReturnTypeOfSignature(signature); - let exprType = checkExpressionCached(node.expression); + const signature = getSignatureFromDeclaration(func); + const returnType = getReturnTypeOfSignature(signature); + const exprType = checkExpressionCached(node.expression); if (func.asteriskToken) { // A generator does not need its return expressions checked against its return type. @@ -12658,8 +12664,8 @@ namespace ts { } else if (func.type || isGetAccessorWithAnnotatatedSetAccessor(func) || signature.typePredicate) { if (isAsyncFunctionLike(func)) { - let promisedType = getPromisedType(returnType); - let awaitedType = checkAwaitedType(exprType, node.expression, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); + const promisedType = getPromisedType(returnType); + const awaitedType = checkAwaitedType(exprType, node.expression, Diagnostics.Return_expression_in_async_function_does_not_have_a_valid_callable_then_member); if (promisedType) { // If the function has a return type, but promisedType is // undefined, an error will be reported in checkAsyncFunctionReturnType @@ -12694,7 +12700,7 @@ namespace ts { let firstDefaultClause: CaseOrDefaultClause; let hasDuplicateDefaultClause = false; - let expressionType = checkExpression(node.expression); + const expressionType = checkExpression(node.expression); forEach(node.caseBlock.clauses, clause => { // Grammar check for duplicate default clauses, skip if we already report duplicate default clause if (clause.kind === SyntaxKind.DefaultClause && !hasDuplicateDefaultClause) { @@ -12702,19 +12708,19 @@ namespace ts { firstDefaultClause = clause; } else { - let sourceFile = getSourceFileOfNode(node); - let start = skipTrivia(sourceFile.text, clause.pos); - let end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; + const sourceFile = getSourceFileOfNode(node); + const start = skipTrivia(sourceFile.text, clause.pos); + const end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } if (produceDiagnostics && clause.kind === SyntaxKind.CaseClause) { - let caseClause = clause; + const caseClause = clause; // TypeScript 1.0 spec (April 2014):5.9 // In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from the type of the 'switch' expression. - let caseType = checkExpression(caseClause.expression); + const caseType = checkExpression(caseClause.expression); if (!isTypeAssignableTo(expressionType, caseType)) { // check 'expressionType isAssignableTo caseType' failed, try the reversed check and report errors if it fails checkTypeAssignableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined); @@ -12733,7 +12739,7 @@ namespace ts { break; } if (current.kind === SyntaxKind.LabeledStatement && (current).label.text === node.label.text) { - let sourceFile = getSourceFileOfNode(node); + const sourceFile = getSourceFileOfNode(node); grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNodeFromSourceText(sourceFile.text, node.label)); break; } @@ -12763,7 +12769,7 @@ namespace ts { checkGrammarStatementInAmbientContext(node); checkBlock(node.tryBlock); - let catchClause = node.catchClause; + const catchClause = node.catchClause; if (catchClause) { // Grammar checking if (catchClause.variableDeclaration) { @@ -12777,10 +12783,10 @@ namespace ts { grammarErrorOnFirstToken(catchClause.variableDeclaration.initializer, Diagnostics.Catch_clause_variable_cannot_have_an_initializer); } else { - let identifierName = (catchClause.variableDeclaration.name).text; - let locals = catchClause.block.locals; + const identifierName = (catchClause.variableDeclaration.name).text; + const locals = catchClause.block.locals; if (locals && hasProperty(locals, identifierName)) { - let localSymbol = locals[identifierName]; + const localSymbol = locals[identifierName]; if (localSymbol && (localSymbol.flags & SymbolFlags.BlockScopedVariable) !== 0) { grammarErrorOnNode(localSymbol.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, identifierName); } @@ -12797,27 +12803,27 @@ namespace ts { } function checkIndexConstraints(type: Type) { - let declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.Number); - let declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.String); + const declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.Number); + const declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, IndexKind.String); - let stringIndexType = getIndexTypeOfType(type, IndexKind.String); - let numberIndexType = getIndexTypeOfType(type, IndexKind.Number); + const stringIndexType = getIndexTypeOfType(type, IndexKind.String); + const numberIndexType = getIndexTypeOfType(type, IndexKind.Number); if (stringIndexType || numberIndexType) { forEach(getPropertiesOfObjectType(type), prop => { - let propType = getTypeOfSymbol(prop); + const propType = getTypeOfSymbol(prop); checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, IndexKind.String); checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, IndexKind.Number); }); if (type.flags & TypeFlags.Class && isClassLike(type.symbol.valueDeclaration)) { - let classDeclaration = type.symbol.valueDeclaration; - for (let member of classDeclaration.members) { + const classDeclaration = type.symbol.valueDeclaration; + for (const member of classDeclaration.members) { // Only process instance properties with computed names here. // Static properties cannot be in conflict with indexers, // and properties with literal names were already checked. if (!(member.flags & NodeFlags.Static) && hasDynamicName(member)) { - let propType = getTypeOfSymbol(member.symbol); + const propType = getTypeOfSymbol(member.symbol); checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, IndexKind.String); checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, IndexKind.Number); } @@ -12830,7 +12836,7 @@ namespace ts { errorNode = declaredNumberIndexer || declaredStringIndexer; // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer if (!errorNode && (type.flags & TypeFlags.Interface)) { - let someBaseTypeHasBothIndexers = forEach(getBaseTypes(type), base => getIndexTypeOfType(base, IndexKind.String) && getIndexTypeOfType(base, IndexKind.Number)); + const someBaseTypeHasBothIndexers = forEach(getBaseTypes(type), base => getIndexTypeOfType(base, IndexKind.String) && getIndexTypeOfType(base, IndexKind.Number)); errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0]; } } @@ -12870,12 +12876,12 @@ namespace ts { // for interfaces property and indexer might be inherited from different bases // check if any base class already has both property and indexer. // check should be performed only if 'type' is the first type that brings property\indexer together - let someBaseClassHasBothPropertyAndIndexer = forEach(getBaseTypes(containingType), base => getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind)); + const someBaseClassHasBothPropertyAndIndexer = forEach(getBaseTypes(containingType), base => getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind)); errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; } if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { - let errorMessage = + const errorMessage = indexKind === IndexKind.String ? Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 : Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; @@ -12902,7 +12908,7 @@ namespace ts { function checkTypeParameters(typeParameterDeclarations: TypeParameterDeclaration[]) { if (typeParameterDeclarations) { for (let i = 0, n = typeParameterDeclarations.length; i < n; i++) { - let node = typeParameterDeclarations[i]; + const node = typeParameterDeclarations[i]; checkTypeParameter(node); if (produceDiagnostics) { @@ -12940,22 +12946,22 @@ namespace ts { } checkTypeParameters(node.typeParameters); checkExportsOnMergedDeclarations(node); - let symbol = getSymbolOfNode(node); - let type = getDeclaredTypeOfSymbol(symbol); - let typeWithThis = getTypeWithThisArgument(type); - let staticType = getTypeOfSymbol(symbol); + const symbol = getSymbolOfNode(node); + const type = getDeclaredTypeOfSymbol(symbol); + const typeWithThis = getTypeWithThisArgument(type); + const staticType = getTypeOfSymbol(symbol); - let baseTypeNode = getClassExtendsHeritageClauseElement(node); + const baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { emitExtends = emitExtends || !isInAmbientContext(node); - let baseTypes = getBaseTypes(type); + const baseTypes = getBaseTypes(type); if (baseTypes.length && produceDiagnostics) { - let baseType = baseTypes[0]; - let staticBaseType = getBaseConstructorTypeOfClass(type); + const baseType = baseTypes[0]; + const staticBaseType = getBaseConstructorTypeOfClass(type); checkSourceElement(baseTypeNode.expression); if (baseTypeNode.typeArguments) { forEach(baseTypeNode.typeArguments, checkSourceElement); - for (let constructor of getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments)) { + for (const constructor of getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments)) { if (!checkTypeArgumentConstraints(constructor.typeParameters, baseTypeNode.typeArguments)) { break; } @@ -12970,7 +12976,7 @@ namespace ts { // that all instantiated base constructor signatures return the same type. We can simply compare the type // references (as opposed to checking the structure of the types) because elsewhere we have already checked // that the base type is a class or interface type (and not, for example, an anonymous object type). - let constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); + const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments); if (forEach(constructors, sig => getReturnTypeOfSignature(sig) !== baseType)) { error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type); } @@ -12979,17 +12985,17 @@ namespace ts { } } - let implementedTypeNodes = getClassImplementsHeritageClauseElements(node); + const implementedTypeNodes = getClassImplementsHeritageClauseElements(node); if (implementedTypeNodes) { - for (let typeRefNode of implementedTypeNodes) { + for (const typeRefNode of implementedTypeNodes) { if (!isSupportedExpressionWithTypeArguments(typeRefNode)) { error(typeRefNode.expression, Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments); } checkTypeReferenceNode(typeRefNode); if (produceDiagnostics) { - let t = getTypeFromTypeNode(typeRefNode); + const t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { - let declaredType = (t.flags & TypeFlags.Reference) ? (t).target : t; + const declaredType = (t.flags & TypeFlags.Reference) ? (t).target : t; if (declaredType.flags & (TypeFlags.Class | TypeFlags.Interface)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, Diagnostics.Class_0_incorrectly_implements_interface_1); } @@ -13034,16 +13040,16 @@ namespace ts { // derived class instance member variables and accessors, but not by other kinds of members. // NOTE: assignability is checked in checkClassDeclaration - let baseProperties = getPropertiesOfObjectType(baseType); - for (let baseProperty of baseProperties) { - let base = getTargetSymbol(baseProperty); + const baseProperties = getPropertiesOfObjectType(baseType); + for (const baseProperty of baseProperties) { + const base = getTargetSymbol(baseProperty); if (base.flags & SymbolFlags.Prototype) { continue; } - let derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); - let baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); + const derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); + const baseDeclarationFlags = getDeclarationFlagsFromSymbol(base); Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration."); @@ -13054,7 +13060,7 @@ namespace ts { if (derived === base) { // derived class inherits base without override/redeclaration - let derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); + const derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol); // It is an error to inherit an abstract member without implementing it or being declared abstract. // If there is no declaration for the derived class (as in the case of class expressions), @@ -13072,7 +13078,7 @@ namespace ts { } else { // derived overrides base. - let derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); + const derivedDeclarationFlags = getDeclarationFlagsFromSymbol(derived); if ((baseDeclarationFlags & NodeFlags.Private) || (derivedDeclarationFlags & NodeFlags.Private)) { // either base or derived property is private - not override, skip it continue; @@ -13129,8 +13135,8 @@ namespace ts { // When a generic interface has multiple declarations, all declarations must have identical type parameter // lists, i.e. identical type parameter names with identical constraints in identical order. for (let i = 0, len = list1.length; i < len; i++) { - let tp1 = list1[i]; - let tp2 = list2[i]; + const tp1 = list1[i]; + const tp2 = list2[i]; if (tp1.name.text !== tp2.name.text) { return false; } @@ -13148,29 +13154,29 @@ namespace ts { } function checkInheritedPropertiesAreIdentical(type: InterfaceType, typeNode: Node): boolean { - let baseTypes = getBaseTypes(type); + const baseTypes = getBaseTypes(type); if (baseTypes.length < 2) { return true; } - let seen: Map<{ prop: Symbol; containingType: Type }> = {}; + const seen: Map<{ prop: Symbol; containingType: Type }> = {}; forEach(resolveDeclaredMembers(type).declaredProperties, p => { seen[p.name] = { prop: p, containingType: type }; }); let ok = true; - for (let base of baseTypes) { - let properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); - for (let prop of properties) { + for (const base of baseTypes) { + const properties = getPropertiesOfObjectType(getTypeWithThisArgument(base, type.thisType)); + for (const prop of properties) { if (!hasProperty(seen, prop.name)) { seen[prop.name] = { prop: prop, containingType: base }; } else { - let existing = seen[prop.name]; - let isInheritedProperty = existing.containingType !== type; + const existing = seen[prop.name]; + const isInheritedProperty = existing.containingType !== type; if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) { ok = false; - let typeName1 = typeToString(existing.containingType); - let typeName2 = typeToString(base); + const typeName1 = typeToString(existing.containingType); + const typeName2 = typeToString(base); let errorInfo = chainDiagnosticMessages(undefined, Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2); errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2); @@ -13192,8 +13198,8 @@ namespace ts { checkTypeNameIsReserved(node.name, Diagnostics.Interface_name_cannot_be_0); checkExportsOnMergedDeclarations(node); - let symbol = getSymbolOfNode(node); - let firstInterfaceDecl = getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); + const symbol = getSymbolOfNode(node); + const firstInterfaceDecl = getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration); if (symbol.declarations.length > 1) { if (node !== firstInterfaceDecl && !areTypeParametersIdentical(firstInterfaceDecl.typeParameters, node.typeParameters)) { error(node.name, Diagnostics.All_declarations_of_an_interface_must_have_identical_type_parameters); @@ -13202,11 +13208,11 @@ namespace ts { // Only check this symbol once if (node === firstInterfaceDecl) { - let type = getDeclaredTypeOfSymbol(symbol); - let typeWithThis = getTypeWithThisArgument(type); + const type = getDeclaredTypeOfSymbol(symbol); + const typeWithThis = getTypeWithThisArgument(type); // run subsequent checks only if first set succeeded if (checkInheritedPropertiesAreIdentical(type, node.name)) { - for (let baseType of getBaseTypes(type)) { + for (const baseType of getBaseTypes(type)) { checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, Diagnostics.Interface_0_incorrectly_extends_interface_1); } checkIndexConstraints(type); @@ -13236,14 +13242,14 @@ namespace ts { } function computeEnumMemberValues(node: EnumDeclaration) { - let nodeLinks = getNodeLinks(node); + const nodeLinks = getNodeLinks(node); if (!(nodeLinks.flags & NodeCheckFlags.EnumValuesComputed)) { - let enumSymbol = getSymbolOfNode(node); - let enumType = getDeclaredTypeOfSymbol(enumSymbol); + const enumSymbol = getSymbolOfNode(node); + const enumType = getDeclaredTypeOfSymbol(enumSymbol); let autoValue = 0; // set to undefined when enum member is non-constant - let ambient = isInAmbientContext(node); - let enumIsConst = isConst(node); + const ambient = isInAmbientContext(node); + const enumIsConst = isConst(node); for (const member of node.members) { if (member.name.kind === SyntaxKind.ComputedPropertyName) { @@ -13255,7 +13261,7 @@ namespace ts { const previousEnumMemberIsNonConstant = autoValue === undefined; - let initializer = member.initializer; + const initializer = member.initializer; if (initializer) { autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); } @@ -13284,7 +13290,7 @@ namespace ts { // Controls if error should be reported after evaluation of constant value is completed // Can be false if another more precise error was already reported during evaluation. let reportError = true; - let value = evalConstant(initializer); + const value = evalConstant(initializer); if (reportError) { if (value === undefined) { @@ -13314,7 +13320,7 @@ namespace ts { function evalConstant(e: Node): number { switch (e.kind) { case SyntaxKind.PrefixUnaryExpression: - let value = evalConstant((e).operand); + const value = evalConstant((e).operand); if (value === undefined) { return undefined; } @@ -13325,11 +13331,11 @@ namespace ts { } return undefined; case SyntaxKind.BinaryExpression: - let left = evalConstant((e).left); + const left = evalConstant((e).left); if (left === undefined) { return undefined; } - let right = evalConstant((e).right); + const right = evalConstant((e).right); if (right === undefined) { return undefined; } @@ -13354,8 +13360,8 @@ namespace ts { case SyntaxKind.Identifier: case SyntaxKind.ElementAccessExpression: case SyntaxKind.PropertyAccessExpression: - let member = initializer.parent; - let currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); + const member = initializer.parent; + const currentType = getTypeOfSymbol(getSymbolOfNode(member.parent)); let enumType: Type; let propertyName: string; @@ -13405,12 +13411,12 @@ namespace ts { return undefined; } - let property = getPropertyOfObjectType(enumType, propertyName); + const property = getPropertyOfObjectType(enumType, propertyName); if (!property || !(property.flags & SymbolFlags.EnumMember)) { return undefined; } - let propertyDecl = property.valueDeclaration; + const propertyDecl = property.valueDeclaration; // self references are illegal if (member === propertyDecl) { return undefined; @@ -13444,7 +13450,7 @@ namespace ts { computeEnumMemberValues(node); - let enumIsConst = isConst(node); + const enumIsConst = isConst(node); if (compilerOptions.isolatedModules && enumIsConst && isInAmbientContext(node)) { error(node.name, Diagnostics.Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided); } @@ -13455,8 +13461,8 @@ namespace ts { // for the first member. // // Only perform this check once per symbol - let enumSymbol = getSymbolOfNode(node); - let firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind); + const enumSymbol = getSymbolOfNode(node); + const firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind); if (node === firstDeclaration) { if (enumSymbol.declarations.length > 1) { // check that const is placed\omitted on all enum declarations @@ -13474,12 +13480,12 @@ namespace ts { return false; } - let enumDeclaration = declaration; + const enumDeclaration = declaration; if (!enumDeclaration.members.length) { return false; } - let firstEnumMember = enumDeclaration.members[0]; + const firstEnumMember = enumDeclaration.members[0]; if (!firstEnumMember.initializer) { if (seenEnumMissingInitialInitializer) { error(firstEnumMember.name, Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element); @@ -13493,8 +13499,8 @@ namespace ts { } function getFirstNonAmbientClassOrFunctionDeclaration(symbol: Symbol): Declaration { - let declarations = symbol.declarations; - for (let declaration of declarations) { + const declarations = symbol.declarations; + for (const declaration of declarations) { if ((declaration.kind === SyntaxKind.ClassDeclaration || (declaration.kind === SyntaxKind.FunctionDeclaration && nodeIsPresent((declaration).body))) && !isInAmbientContext(declaration)) { @@ -13505,8 +13511,8 @@ namespace ts { } function inSameLexicalScope(node1: Node, node2: Node) { - let container1 = getEnclosingBlockScopeContainer(node1); - let container2 = getEnclosingBlockScopeContainer(node2); + const container1 = getEnclosingBlockScopeContainer(node1); + const container2 = getEnclosingBlockScopeContainer(node2); if (isGlobalSourceFile(container1)) { return isGlobalSourceFile(container2); } @@ -13521,8 +13527,8 @@ namespace ts { function checkModuleDeclaration(node: ModuleDeclaration) { if (produceDiagnostics) { // Grammar checking - let isAmbientExternalModule = node.name.kind === SyntaxKind.StringLiteral; - let contextErrorMessage = isAmbientExternalModule + const isAmbientExternalModule = node.name.kind === SyntaxKind.StringLiteral; + const contextErrorMessage = isAmbientExternalModule ? Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file : Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module; if (checkGrammarModuleElementContext(node, contextErrorMessage)) { @@ -13539,14 +13545,14 @@ namespace ts { checkCollisionWithCapturedThisVariable(node, node.name); checkCollisionWithRequireExportsInGeneratedCode(node, node.name); checkExportsOnMergedDeclarations(node); - let symbol = getSymbolOfNode(node); + const symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & SymbolFlags.ValueModule && symbol.declarations.length > 1 && !isInAmbientContext(node) && isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules)) { - let firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); + const firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { if (getSourceFileOfNode(node) !== getSourceFileOfNode(firstNonAmbientClassOrFunc)) { error(node.name, Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged); @@ -13558,7 +13564,7 @@ namespace ts { // if the module merges with a class declaration in the same lexical scope, // we need to track this to ensure the correct emit. - let mergedClass = getDeclarationOfKind(symbol, SyntaxKind.ClassDeclaration); + const mergedClass = getDeclarationOfKind(symbol, SyntaxKind.ClassDeclaration); if (mergedClass && inSameLexicalScope(node, mergedClass)) { getNodeLinks(node).flags |= NodeCheckFlags.LexicalModuleMergesWithClass; @@ -13595,12 +13601,12 @@ namespace ts { } function checkExternalImportOrExportDeclaration(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): boolean { - let moduleName = getExternalModuleName(node); + const moduleName = getExternalModuleName(node); if (!nodeIsMissing(moduleName) && moduleName.kind !== SyntaxKind.StringLiteral) { error(moduleName, Diagnostics.String_literal_expected); return false; } - let inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && (node.parent.parent).name.kind === SyntaxKind.StringLiteral; + const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && (node.parent.parent).name.kind === SyntaxKind.StringLiteral; if (node.parent.kind !== SyntaxKind.SourceFile && !inAmbientExternalModule) { error(moduleName, node.kind === SyntaxKind.ExportDeclaration ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : @@ -13619,15 +13625,15 @@ namespace ts { } function checkAliasSymbol(node: ImportEqualsDeclaration | ImportClause | NamespaceImport | ImportSpecifier | ExportSpecifier) { - let symbol = getSymbolOfNode(node); - let target = resolveAlias(symbol); + const symbol = getSymbolOfNode(node); + const target = resolveAlias(symbol); if (target !== unknownSymbol) { - let excludedMeanings = + const excludedMeanings = (symbol.flags & SymbolFlags.Value ? SymbolFlags.Value : 0) | (symbol.flags & SymbolFlags.Type ? SymbolFlags.Type : 0) | (symbol.flags & SymbolFlags.Namespace ? SymbolFlags.Namespace : 0); if (target.flags & excludedMeanings) { - let message = node.kind === SyntaxKind.ExportSpecifier ? + const message = node.kind === SyntaxKind.ExportSpecifier ? Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0; error(node, message, symbolToString(symbol)); @@ -13650,7 +13656,7 @@ namespace ts { grammarErrorOnFirstToken(node, Diagnostics.An_import_declaration_cannot_have_modifiers); } if (checkExternalImportOrExportDeclaration(node)) { - let importClause = node.importClause; + const importClause = node.importClause; if (importClause) { if (importClause.name) { checkImportBinding(importClause); @@ -13680,11 +13686,11 @@ namespace ts { markExportAsReferenced(node); } if (isInternalModuleImportEqualsDeclaration(node)) { - let target = resolveAlias(getSymbolOfNode(node)); + const target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & SymbolFlags.Value) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name - let moduleName = getFirstIdentifier(node.moduleReference); + const moduleName = getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, SymbolFlags.Value | SymbolFlags.Namespace).flags & SymbolFlags.Namespace)) { error(moduleName, Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, declarationNameToString(moduleName)); } @@ -13719,14 +13725,14 @@ namespace ts { // export { x, y } from "foo" forEach(node.exportClause.elements, checkExportSpecifier); - let inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && (node.parent.parent).name.kind === SyntaxKind.StringLiteral; + const inAmbientExternalModule = node.parent.kind === SyntaxKind.ModuleBlock && (node.parent.parent).name.kind === SyntaxKind.StringLiteral; if (node.parent.kind !== SyntaxKind.SourceFile && !inAmbientExternalModule) { error(node, Diagnostics.Export_declarations_are_not_permitted_in_a_namespace); } } else { // export * from "foo" - let moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); + const moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); if (moduleSymbol && moduleSymbol.exports["export="]) { error(node.moduleSpecifier, Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol)); } @@ -13753,7 +13759,7 @@ namespace ts { return; } - let container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent; + const container = node.parent.kind === SyntaxKind.SourceFile ? node.parent : node.parent.parent; if (container.kind === SyntaxKind.ModuleDeclaration && (container).name.kind === SyntaxKind.Identifier) { error(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace); return; @@ -13803,12 +13809,12 @@ namespace ts { } function checkExternalModuleExports(node: SourceFile | ModuleDeclaration) { - let moduleSymbol = getSymbolOfNode(node); - let links = getSymbolLinks(moduleSymbol); + const moduleSymbol = getSymbolOfNode(node); + const links = getSymbolLinks(moduleSymbol); if (!links.exportsChecked) { - let exportEqualsSymbol = moduleSymbol.exports["export="]; + const exportEqualsSymbol = moduleSymbol.exports["export="]; if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) { - let declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; + const declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration; error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } links.exportsChecked = true; @@ -13826,7 +13832,7 @@ namespace ts { return; } - let kind = node.kind; + const kind = node.kind; if (cancellationToken) { // Only bother checking on a few construct kinds. We don't want to be excessivly // hitting the cancellation token on every node we check. @@ -13950,8 +13956,8 @@ namespace ts { // Function and class expression bodies are checked after all statements in the enclosing body. This is // to ensure constructs like the following are permitted: - // let foo = function () { - // let s = foo(); + // const foo = function () { + // const s = foo(); // return "hello"; // } // Here, performing a full type check of the body of the function expression whilst in the process of @@ -14057,7 +14063,7 @@ namespace ts { } function checkSourceFile(node: SourceFile) { - let start = new Date().getTime(); + const start = new Date().getTime(); checkSourceFileWorker(node); @@ -14066,7 +14072,7 @@ namespace ts { // Fully type check a source file and collect the relevant diagnostics. function checkSourceFileWorker(node: SourceFile) { - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!(links.flags & NodeCheckFlags.TypeChecked)) { // Check whether the file has declared it is the default lib, // and whether the user has specifically chosen to avoid checking it. @@ -14168,7 +14174,7 @@ namespace ts { } function getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[] { - let symbols: SymbolTable = {}; + const symbols: SymbolTable = {}; let memberFlags: NodeFlags = 0; if (isInsideWithStatementBody(location)) { @@ -14198,7 +14204,7 @@ namespace ts { copySymbols(getSymbolOfNode(location).exports, meaning & SymbolFlags.EnumMember); break; case SyntaxKind.ClassExpression: - let className = (location).name; + const className = (location).name; if (className) { copySymbol(location.symbol, meaning); } @@ -14215,7 +14221,7 @@ namespace ts { } break; case SyntaxKind.FunctionExpression: - let funcName = (location).name; + const funcName = (location).name; if (funcName) { copySymbol(location.symbol, meaning); } @@ -14242,7 +14248,7 @@ namespace ts { */ function copySymbol(symbol: Symbol, meaning: SymbolFlags): void { if (symbol.flags & meaning) { - let id = symbol.name; + const id = symbol.name; // We will copy all symbol regardless of its reserved name because // symbolsToArray will check whether the key is a reserved name and // it will not copy symbol with reserved name to the array @@ -14254,8 +14260,8 @@ namespace ts { function copySymbols(source: SymbolTable, meaning: SymbolFlags): void { if (meaning) { - for (let id in source) { - let symbol = source[id]; + for (const id in source) { + const symbol = source[id]; copySymbol(symbol, meaning); } } @@ -14372,18 +14378,18 @@ namespace ts { if (entityName.kind === SyntaxKind.Identifier) { // Include aliases in the meaning, this ensures that we do not follow aliases to where they point and instead // return the alias symbol. - let meaning: SymbolFlags = SymbolFlags.Value | SymbolFlags.Alias; + const meaning: SymbolFlags = SymbolFlags.Value | SymbolFlags.Alias; return resolveEntityName(entityName, meaning); } else if (entityName.kind === SyntaxKind.PropertyAccessExpression) { - let symbol = getNodeLinks(entityName).resolvedSymbol; + const symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkPropertyAccessExpression(entityName); } return getNodeLinks(entityName).resolvedSymbol; } else if (entityName.kind === SyntaxKind.QualifiedName) { - let symbol = getNodeLinks(entityName).resolvedSymbol; + const symbol = getNodeLinks(entityName).resolvedSymbol; if (!symbol) { checkQualifiedName(entityName); } @@ -14429,8 +14435,8 @@ namespace ts { else if (node.parent.kind === SyntaxKind.BindingElement && node.parent.parent.kind === SyntaxKind.ObjectBindingPattern && node === (node.parent).propertyName) { - let typeOfPattern = getTypeOfNode(node.parent.parent); - let propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, (node).text); + const typeOfPattern = getTypeOfNode(node.parent.parent); + const propertyDeclaration = typeOfPattern && getPropertyOfType(typeOfPattern, (node).text); if (propertyDeclaration) { return propertyDeclaration; @@ -14446,12 +14452,12 @@ namespace ts { case SyntaxKind.ThisKeyword: case SyntaxKind.SuperKeyword: - let type = isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); + const type = isExpression(node) ? checkExpression(node) : getTypeFromTypeNode(node); return type.symbol; case SyntaxKind.ConstructorKeyword: // constructor keyword for an overload, should take us to the definition if it exist - let constructorDeclaration = node.parent; + const constructorDeclaration = node.parent; if (constructorDeclaration && constructorDeclaration.kind === SyntaxKind.Constructor) { return (constructorDeclaration.parent).symbol; } @@ -14470,9 +14476,9 @@ namespace ts { case SyntaxKind.NumericLiteral: // index access if (node.parent.kind === SyntaxKind.ElementAccessExpression && (node.parent).argumentExpression === node) { - let objectType = checkExpression((node.parent).expression); + const objectType = checkExpression((node.parent).expression); if (objectType === unknownType) return undefined; - let apparentType = getApparentType(objectType); + const apparentType = getApparentType(objectType); if (apparentType === unknownType) return undefined; return getPropertyOfType(apparentType, (node).text); } @@ -14513,23 +14519,23 @@ namespace ts { if (isTypeDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration - let symbol = getSymbolOfNode(node); + const symbol = getSymbolOfNode(node); return getDeclaredTypeOfSymbol(symbol); } if (isTypeDeclarationName(node)) { - let symbol = getSymbolAtLocation(node); + const symbol = getSymbolAtLocation(node); return symbol && getDeclaredTypeOfSymbol(symbol); } if (isDeclaration(node)) { // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration - let symbol = getSymbolOfNode(node); + const symbol = getSymbolOfNode(node); return getTypeOfSymbol(symbol); } if (isDeclarationName(node)) { - let symbol = getSymbolAtLocation(node); + const symbol = getSymbolAtLocation(node); return symbol && getTypeOfSymbol(symbol); } @@ -14538,8 +14544,8 @@ namespace ts { } if (isInRightSideOfImportOrExportAssignment(node)) { - let symbol = getSymbolAtLocation(node); - let declaredType = symbol && getDeclaredTypeOfSymbol(symbol); + const symbol = getSymbolAtLocation(node); + const declaredType = symbol && getDeclaredTypeOfSymbol(symbol); return declaredType !== unknownType ? declaredType : getTypeOfSymbol(symbol); } @@ -14559,7 +14565,7 @@ namespace ts { * whether the element is declared as "static". */ function getParentTypeOfClassElement(node: ClassElement) { - let classSymbol = getSymbolOfNode(node.parent); + const classSymbol = getSymbolOfNode(node.parent); return node.flags & NodeFlags.Static ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol); @@ -14569,7 +14575,7 @@ namespace ts { // if the type has call or construct signatures function getAugmentedPropertiesOfType(type: Type): Symbol[] { type = getApparentType(type); - let propsByName = createSymbolTable(getPropertiesOfType(type)); + const propsByName = createSymbolTable(getPropertiesOfType(type)); if (getSignaturesOfType(type, SignatureKind.Call).length || getSignaturesOfType(type, SignatureKind.Construct).length) { forEach(getPropertiesOfType(globalFunctionType), p => { if (!hasProperty(propsByName, p.name)) { @@ -14582,10 +14588,10 @@ namespace ts { function getRootSymbols(symbol: Symbol): Symbol[] { if (symbol.flags & SymbolFlags.SyntheticProperty) { - let symbols: Symbol[] = []; - let name = symbol.name; + const symbols: Symbol[] = []; + const name = symbol.name; forEach(getSymbolLinks(symbol).containingType.types, t => { - let symbol = getPropertyOfType(t, name); + const symbol = getPropertyOfType(t, name); if (symbol) { symbols.push(symbol); } @@ -14593,7 +14599,7 @@ namespace ts { return symbols; } else if (symbol.flags & SymbolFlags.Transient) { - let target = getSymbolLinks(symbol).target; + const target = getSymbolLinks(symbol).target; if (target) { return [target]; } @@ -14616,13 +14622,13 @@ namespace ts { // If we reference an exported entity within the same module declaration, then whether // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the // kinds that we do NOT prefix. - let exportSymbol = getMergedSymbol(symbol.exportSymbol); + const exportSymbol = getMergedSymbol(symbol.exportSymbol); if (exportSymbol.flags & SymbolFlags.ExportHasLocal) { return undefined; } symbol = exportSymbol; } - let parentSymbol = getParentOfSymbol(symbol); + const parentSymbol = getParentOfSymbol(symbol); if (parentSymbol) { if (parentSymbol.flags & SymbolFlags.ValueModule && parentSymbol.valueDeclaration.kind === SyntaxKind.SourceFile) { return parentSymbol.valueDeclaration; @@ -14639,7 +14645,7 @@ namespace ts { // When resolved as an expression identifier, if the given node references an import, return the declaration of // that import. Otherwise, return undefined. function getReferencedImportDeclaration(node: Identifier): Declaration { - let symbol = getReferencedValueSymbol(node); + const symbol = getReferencedValueSymbol(node); return symbol && symbol.flags & SymbolFlags.Alias ? getDeclarationOfAliasSymbol(symbol) : undefined; } @@ -14657,9 +14663,9 @@ namespace ts { function isNestedRedeclarationSymbol(symbol: Symbol): boolean { if (symbol.flags & SymbolFlags.BlockScoped) { - let links = getSymbolLinks(symbol); + const links = getSymbolLinks(symbol); if (links.isNestedRedeclaration === undefined) { - let container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); + const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration); links.isNestedRedeclaration = isStatementWithLocals(container) && !!resolveName(container.parent, symbol.name, SymbolFlags.Value, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined); } @@ -14671,7 +14677,7 @@ namespace ts { // When resolved as an expression identifier, if the given node references a nested block scoped entity with // a name that hides an existing name, return the declaration of that entity. Otherwise, return undefined. function getReferencedNestedRedeclaration(node: Identifier): Declaration { - let symbol = getReferencedValueSymbol(node); + const symbol = getReferencedValueSymbol(node); return symbol && isNestedRedeclarationSymbol(symbol) ? symbol.valueDeclaration : undefined; } @@ -14690,7 +14696,7 @@ namespace ts { case SyntaxKind.ExportSpecifier: return isAliasResolvedToValue(getSymbolOfNode(node)); case SyntaxKind.ExportDeclaration: - let exportClause = (node).exportClause; + const exportClause = (node).exportClause; return exportClause && forEach(exportClause.elements, isValueAliasDeclaration); case SyntaxKind.ExportAssignment: return (node).expression && (node).expression.kind === SyntaxKind.Identifier ? isAliasResolvedToValue(getSymbolOfNode(node)) : true; @@ -14704,12 +14710,12 @@ namespace ts { return false; } - let isValue = isAliasResolvedToValue(getSymbolOfNode(node)); + const isValue = isAliasResolvedToValue(getSymbolOfNode(node)); return isValue && node.moduleReference && !nodeIsMissing(node.moduleReference); } function isAliasResolvedToValue(symbol: Symbol): boolean { - let target = resolveAlias(symbol); + const target = resolveAlias(symbol); if (target === unknownSymbol && compilerOptions.isolatedModules) { return true; } @@ -14727,7 +14733,7 @@ namespace ts { function isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean { if (isAliasSymbolDeclaration(node)) { - let symbol = getSymbolOfNode(node); + const symbol = getSymbolOfNode(node); if (getSymbolLinks(symbol).referenced) { return true; } @@ -14741,8 +14747,8 @@ namespace ts { function isImplementationOfOverload(node: FunctionLikeDeclaration) { if (nodeIsPresent(node.body)) { - let symbol = getSymbolOfNode(node); - let signaturesOfSymbol = getSignaturesOfSymbol(symbol); + const symbol = getSymbolOfNode(node); + const signaturesOfSymbol = getSignaturesOfSymbol(symbol); // If this function body corresponds to function with multiple signature, it is implementation of overload // e.g.: function foo(a: string): string; // function foo(a: number): number; @@ -14774,7 +14780,7 @@ namespace ts { return getEnumMemberValue(node); } - let symbol = getNodeLinks(node).resolvedSymbol; + const symbol = getNodeLinks(node).resolvedSymbol; if (symbol && (symbol.flags & SymbolFlags.EnumMember)) { // inline property\index accesses only for const enums if (isConstEnumDeclaration(symbol.valueDeclaration.parent)) { @@ -14791,19 +14797,19 @@ namespace ts { function getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind { // Resolve the symbol as a value to ensure the type can be reached at runtime during emit. - let valueSymbol = resolveEntityName(typeName, SymbolFlags.Value, /*ignoreErrors*/ true); - let constructorType = valueSymbol ? getTypeOfSymbol(valueSymbol) : undefined; + const valueSymbol = resolveEntityName(typeName, SymbolFlags.Value, /*ignoreErrors*/ true); + const constructorType = valueSymbol ? getTypeOfSymbol(valueSymbol) : undefined; if (constructorType && isConstructorType(constructorType)) { return TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue; } // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer. - let typeSymbol = resolveEntityName(typeName, SymbolFlags.Type, /*ignoreErrors*/ true); + const typeSymbol = resolveEntityName(typeName, SymbolFlags.Type, /*ignoreErrors*/ true); // We might not be able to resolve type symbol so use unknown type in that case (eg error case) if (!typeSymbol) { return TypeReferenceSerializationKind.ObjectType; } - let type = getDeclaredTypeOfSymbol(typeSymbol); + const type = getDeclaredTypeOfSymbol(typeSymbol); if (type === unknownType) { return TypeReferenceSerializationKind.Unknown; } @@ -14841,8 +14847,8 @@ namespace ts { function writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { // Get type of the symbol if this is the valid symbol otherwise get type at location - let symbol = getSymbolOfNode(declaration); - let type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature)) + const symbol = getSymbolOfNode(declaration); + const type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature)) ? getTypeOfSymbol(symbol) : unknownType; @@ -14850,12 +14856,12 @@ namespace ts { } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { - let signature = getSignatureFromDeclaration(signatureDeclaration); + const signature = getSignatureFromDeclaration(signatureDeclaration); getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); } function writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter) { - let type = getTypeOfExpression(expr); + const type = getTypeOfExpression(expr); getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } @@ -14871,7 +14877,7 @@ namespace ts { function getReferencedValueDeclaration(reference: Identifier): Declaration { Debug.assert(!nodeIsSynthesized(reference)); - let symbol = getReferencedValueSymbol(reference); + const symbol = getReferencedValueSymbol(reference); return symbol && getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration; } @@ -14880,12 +14886,12 @@ namespace ts { return unknownType; } - let signature = getSingleCallSignature(functionType); + const signature = getSingleCallSignature(functionType); if (!signature) { return unknownType; } - let instantiatedSignature = getSignatureInstantiation(signature, typeArguments); + const instantiatedSignature = getSignatureInstantiation(signature, typeArguments); return getOrCreateTypeFromSignature(instantiatedSignature); } @@ -14919,7 +14925,7 @@ namespace ts { function initializeTypeChecker() { // Bind all source files and propagate errors forEach(host.getSourceFiles(), file => { - bindSourceFile(file); + bindSourceFile(file, compilerOptions); }); // Initialize global symbol table @@ -14983,7 +14989,7 @@ namespace ts { } function createInstantiatedPromiseLikeType(): ObjectType { - let promiseLikeType = getGlobalPromiseLikeType(); + const promiseLikeType = getGlobalPromiseLikeType(); if (promiseLikeType !== emptyGenericType) { return createTypeReference(promiseLikeType, [anyType]); } @@ -14993,10 +14999,10 @@ namespace ts { function createThenableType() { // build the thenable type that is used to verify against a non-promise "thenable" operand to `await`. - let thenPropertySymbol = createSymbol(SymbolFlags.Transient | SymbolFlags.Property, "then"); + const thenPropertySymbol = createSymbol(SymbolFlags.Transient | SymbolFlags.Property, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; - let thenableType = createObjectType(TypeFlags.Anonymous); + const thenableType = createObjectType(TypeFlags.Anonymous); thenableType.properties = [thenPropertySymbol]; thenableType.members = createSymbolTable(thenableType.properties); thenableType.callSignatures = []; @@ -15013,7 +15019,7 @@ namespace ts { return grammarErrorOnFirstToken(node, Diagnostics.Decorators_are_not_valid_here); } else if (node.kind === SyntaxKind.GetAccessor || node.kind === SyntaxKind.SetAccessor) { - let accessors = getAllAccessorDeclarations((node.parent).members, node); + const accessors = getAllAccessorDeclarations((node.parent).members, node); if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) { return grammarErrorOnFirstToken(node, Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name); } @@ -15068,7 +15074,7 @@ namespace ts { let lastStatic: Node, lastPrivate: Node, lastProtected: Node, lastDeclare: Node, lastAsync: Node; let flags = 0; - for (let modifier of node.modifiers) { + for (const modifier of node.modifiers) { switch (modifier.kind) { case SyntaxKind.PublicKeyword: case SyntaxKind.ProtectedKeyword: @@ -15259,9 +15265,9 @@ namespace ts { function checkGrammarForDisallowedTrailingComma(list: NodeArray): boolean { if (list && list.hasTrailingComma) { - let start = list.end - ",".length; - let end = list.end; - let sourceFile = getSourceFileOfNode(list[0]); + const start = list.end - ",".length; + const end = list.end; + const sourceFile = getSourceFileOfNode(list[0]); return grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.Trailing_comma_not_allowed); } } @@ -15272,8 +15278,8 @@ namespace ts { } if (typeParameters && typeParameters.length === 0) { - let start = typeParameters.pos - "<".length; - let end = skipTrivia(file.text, typeParameters.end) + ">".length; + const start = typeParameters.pos - "<".length; + const end = skipTrivia(file.text, typeParameters.end) + ">".length; return grammarErrorAtPos(file, start, end - start, Diagnostics.Type_parameter_list_cannot_be_empty); } } @@ -15284,10 +15290,10 @@ namespace ts { } let seenOptionalParameter = false; - let parameterCount = parameters.length; + const parameterCount = parameters.length; for (let i = 0; i < parameterCount; i++) { - let parameter = parameters[i]; + const parameter = parameters[i]; if (parameter.dotDotDotToken) { if (i !== (parameterCount - 1)) { return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list); @@ -15320,16 +15326,16 @@ namespace ts { function checkGrammarFunctionLikeDeclaration(node: FunctionLikeDeclaration): boolean { // Prevent cascading error by short-circuit - let file = getSourceFileOfNode(node); + const file = getSourceFileOfNode(node); return checkGrammarDecorators(node) || checkGrammarModifiers(node) || checkGrammarTypeParameterList(node, node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file); } function checkGrammarArrowFunction(node: FunctionLikeDeclaration, file: SourceFile): boolean { if (node.kind === SyntaxKind.ArrowFunction) { - let arrowFunction = node; - let startLine = getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; - let endLine = getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; + const arrowFunction = node; + const startLine = getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.pos).line; + const endLine = getLineAndCharacterOfPosition(file, arrowFunction.equalsGreaterThanToken.end).line; if (startLine !== endLine) { return grammarErrorOnNode(arrowFunction.equalsGreaterThanToken, Diagnostics.Line_terminator_not_permitted_before_arrow); } @@ -15338,7 +15344,7 @@ namespace ts { } function checkGrammarIndexSignatureParameters(node: SignatureDeclaration): boolean { - let parameter = node.parameters[0]; + const parameter = node.parameters[0]; if (node.parameters.length !== 1) { if (parameter) { return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_must_have_exactly_one_parameter); @@ -15383,9 +15389,9 @@ namespace ts { function checkGrammarForAtLeastOneTypeArgument(node: Node, typeArguments: NodeArray): boolean { if (typeArguments && typeArguments.length === 0) { - let sourceFile = getSourceFileOfNode(node); - let start = typeArguments.pos - "<".length; - let end = skipTrivia(sourceFile.text, typeArguments.end) + ">".length; + const sourceFile = getSourceFileOfNode(node); + const start = typeArguments.pos - "<".length; + const end = skipTrivia(sourceFile.text, typeArguments.end) + ">".length; return grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.Type_argument_list_cannot_be_empty); } } @@ -15397,8 +15403,8 @@ namespace ts { function checkGrammarForOmittedArgument(node: CallExpression, args: NodeArray): boolean { if (args) { - let sourceFile = getSourceFileOfNode(node); - for (let arg of args) { + const sourceFile = getSourceFileOfNode(node); + for (const arg of args) { if (arg.kind === SyntaxKind.OmittedExpression) { return grammarErrorAtPos(sourceFile, arg.pos, 0, Diagnostics.Argument_expression_expected); } @@ -15412,13 +15418,13 @@ namespace ts { } function checkGrammarHeritageClause(node: HeritageClause): boolean { - let types = node.types; + const types = node.types; if (checkGrammarForDisallowedTrailingComma(types)) { return true; } if (types && types.length === 0) { - let listType = tokenToString(node.token); - let sourceFile = getSourceFileOfNode(node); + const listType = tokenToString(node.token); + const sourceFile = getSourceFileOfNode(node); return grammarErrorAtPos(sourceFile, types.pos, 0, Diagnostics._0_list_cannot_be_empty, listType); } } @@ -15428,7 +15434,7 @@ namespace ts { let seenImplementsClause = false; if (!checkGrammarDecorators(node) && !checkGrammarModifiers(node) && node.heritageClauses) { - for (let heritageClause of node.heritageClauses) { + for (const heritageClause of node.heritageClauses) { if (heritageClause.token === SyntaxKind.ExtendsKeyword) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen); @@ -15463,7 +15469,7 @@ namespace ts { let seenExtendsClause = false; if (node.heritageClauses) { - for (let heritageClause of node.heritageClauses) { + for (const heritageClause of node.heritageClauses) { if (heritageClause.token === SyntaxKind.ExtendsKeyword) { if (seenExtendsClause) { return grammarErrorOnFirstToken(heritageClause, Diagnostics.extends_clause_already_seen); @@ -15490,7 +15496,7 @@ namespace ts { return false; } - let computedPropertyName = node; + const computedPropertyName = node; if (computedPropertyName.expression.kind === SyntaxKind.BinaryExpression && (computedPropertyName.expression).operatorToken.kind === SyntaxKind.CommaToken) { return grammarErrorOnNode(computedPropertyName.expression, Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } @@ -15521,14 +15527,14 @@ namespace ts { } function checkGrammarObjectLiteralExpression(node: ObjectLiteralExpression, inDestructuring: boolean) { - let seen: Map = {}; - let Property = 1; - let GetAccessor = 2; - let SetAccesor = 4; - let GetOrSetAccessor = GetAccessor | SetAccesor; + const seen: Map = {}; + const Property = 1; + const GetAccessor = 2; + const SetAccesor = 4; + const GetOrSetAccessor = GetAccessor | SetAccesor; - for (let prop of node.properties) { - let name = prop.name; + for (const prop of node.properties) { + const name = prop.name; if (prop.kind === SyntaxKind.OmittedExpression || name.kind === SyntaxKind.ComputedPropertyName) { // If the name is not a ComputedPropertyName, the grammar checking will skip it @@ -15576,7 +15582,7 @@ namespace ts { seen[(name).text] = currentKind; } else { - let existingKind = seen[(name).text]; + const existingKind = seen[(name).text]; if (currentKind === Property && existingKind === Property) { continue; } @@ -15597,13 +15603,13 @@ namespace ts { function checkGrammarJsxElement(node: JsxOpeningLikeElement) { const seen: Map = {}; - for (let attr of node.attributes) { + for (const attr of node.attributes) { if (attr.kind === SyntaxKind.JsxSpreadAttribute) { continue; } - let jsxAttr = (attr); - let name = jsxAttr.name; + const jsxAttr = (attr); + const name = jsxAttr.name; if (!hasProperty(seen, name.text)) { seen[name.text] = true; } @@ -15611,7 +15617,7 @@ namespace ts { return grammarErrorOnNode(name, Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } - let initializer = jsxAttr.initializer; + const initializer = jsxAttr.initializer; if (initializer && initializer.kind === SyntaxKind.JsxExpression && !(initializer).expression) { return grammarErrorOnNode(jsxAttr.initializer, Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression); } @@ -15624,23 +15630,23 @@ namespace ts { } if (forInOrOfStatement.initializer.kind === SyntaxKind.VariableDeclarationList) { - let variableList = forInOrOfStatement.initializer; + const variableList = forInOrOfStatement.initializer; if (!checkGrammarVariableDeclarationList(variableList)) { if (variableList.declarations.length > 1) { - let diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement + const diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement ? Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement : Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement; return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic); } - let firstDeclaration = variableList.declarations[0]; + const firstDeclaration = variableList.declarations[0]; if (firstDeclaration.initializer) { - let diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement + const diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement ? Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer : Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer; return grammarErrorOnNode(firstDeclaration.name, diagnostic); } if (firstDeclaration.type) { - let diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement + const diagnostic = forInOrOfStatement.kind === SyntaxKind.ForInStatement ? Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation : Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation; return grammarErrorOnNode(firstDeclaration, diagnostic); @@ -15652,7 +15658,7 @@ namespace ts { } function checkGrammarAccessor(accessor: MethodDeclaration): boolean { - let kind = accessor.kind; + const kind = accessor.kind; if (languageVersion < ScriptTarget.ES5) { return grammarErrorOnNode(accessor.name, Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } @@ -15676,7 +15682,7 @@ namespace ts { return grammarErrorOnNode(accessor.name, Diagnostics.A_set_accessor_must_have_exactly_one_parameter); } else { - let parameter = accessor.parameters[0]; + const parameter = accessor.parameters[0]; if (parameter.dotDotDotToken) { return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_set_accessor_cannot_have_rest_parameter); } @@ -15751,7 +15757,7 @@ namespace ts { if (node.label && (current).label.text === node.label.text) { // found matching label - verify that label usage is correct // continue can only target labels that are on iteration statements - let isMisplacedContinueLabel = node.kind === SyntaxKind.ContinueStatement + const isMisplacedContinueLabel = node.kind === SyntaxKind.ContinueStatement && !isIterationStatement((current).statement, /*lookInLabeledStatement*/ true); if (isMisplacedContinueLabel) { @@ -15779,14 +15785,14 @@ namespace ts { } if (node.label) { - let message = node.kind === SyntaxKind.BreakStatement + const message = node.kind === SyntaxKind.BreakStatement ? Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement : Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); } else { - let message = node.kind === SyntaxKind.BreakStatement + const message = node.kind === SyntaxKind.BreakStatement ? Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement : Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement; return grammarErrorOnNode(node, message); @@ -15795,7 +15801,7 @@ namespace ts { function checkGrammarBindingElement(node: BindingElement) { if (node.dotDotDotToken) { - let elements = (node.parent).elements; + const elements = (node.parent).elements; if (node !== lastOrUndefined(elements)) { return grammarErrorOnNode(node, Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } @@ -15816,7 +15822,7 @@ namespace ts { if (isInAmbientContext(node)) { if (node.initializer) { // Error on equals token which immediate precedes the initializer - let equalsTokenLength = "=".length; + const equalsTokenLength = "=".length; return grammarErrorAtPos(getSourceFileOfNode(node), node.initializer.pos - equalsTokenLength, equalsTokenLength, Diagnostics.Initializers_are_not_allowed_in_ambient_contexts); } @@ -15831,7 +15837,7 @@ namespace ts { } } - let checkLetConstNames = languageVersion >= ScriptTarget.ES6 && (isLet(node) || isConst(node)); + const checkLetConstNames = languageVersion >= ScriptTarget.ES6 && (isLet(node) || isConst(node)); // 1. LexicalDeclaration : LetOrConst BindingList ; // It is a Syntax Error if the BoundNames of BindingList contains "let". @@ -15850,8 +15856,8 @@ namespace ts { } } else { - let elements = (name).elements; - for (let element of elements) { + const elements = (name).elements; + for (const element of elements) { if (element.kind !== SyntaxKind.OmittedExpression) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -15860,7 +15866,7 @@ namespace ts { } function checkGrammarVariableDeclarationList(declarationList: VariableDeclarationList): boolean { - let declarations = declarationList.declarations; + const declarations = declarationList.declarations; if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) { return true; } @@ -15900,7 +15906,7 @@ namespace ts { function isIntegerLiteral(expression: Expression): boolean { if (expression.kind === SyntaxKind.PrefixUnaryExpression) { - let unaryExpression = expression; + const unaryExpression = expression; if (unaryExpression.operator === SyntaxKind.PlusToken || unaryExpression.operator === SyntaxKind.MinusToken) { expression = unaryExpression.operand; } @@ -15922,9 +15928,9 @@ namespace ts { } function grammarErrorOnFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { - let sourceFile = getSourceFileOfNode(node); + const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - let span = getSpanOfTokenAtPosition(sourceFile, node.pos); + const span = getSpanOfTokenAtPosition(sourceFile, node.pos); diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2)); return true; } @@ -15938,7 +15944,7 @@ namespace ts { } function grammarErrorOnNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { - let sourceFile = getSourceFileOfNode(node); + const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { diagnostics.add(createDiagnosticForNode(node, message, arg0, arg1, arg2)); return true; @@ -16014,7 +16020,7 @@ namespace ts { } function checkGrammarTopLevelElementsForRequiredDeclareModifier(file: SourceFile): boolean { - for (let decl of file.statements) { + for (const decl of file.statements) { if (isDeclaration(decl) || decl.kind === SyntaxKind.VariableStatement) { if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) { return true; @@ -16035,7 +16041,7 @@ namespace ts { } // Find containing block which is either Block, ModuleBlock, SourceFile - let links = getNodeLinks(node); + const links = getNodeLinks(node); if (!links.hasReportedStatementInAmbientContext && isFunctionLike(node.parent)) { return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts); } @@ -16046,7 +16052,7 @@ namespace ts { // this has already been reported, and don't report if it has. // if (node.parent.kind === SyntaxKind.Block || node.parent.kind === SyntaxKind.ModuleBlock || node.parent.kind === SyntaxKind.SourceFile) { - let links = getNodeLinks(node.parent); + const links = getNodeLinks(node.parent); // Check if the containing block ever report this error if (!links.hasReportedStatementInAmbientContext) { return links.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, Diagnostics.Statements_are_not_allowed_in_ambient_contexts); @@ -16068,9 +16074,9 @@ namespace ts { } function grammarErrorAfterFirstToken(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): boolean { - let sourceFile = getSourceFileOfNode(node); + const sourceFile = getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - let span = getSpanOfTokenAtPosition(sourceFile, node.pos); + const span = getSpanOfTokenAtPosition(sourceFile, node.pos); diagnostics.add(createFileDiagnostic(sourceFile, textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2)); return true; } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index a89687a4390..3c3bb14174d 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -1,6 +1,7 @@ /// /// /// +/// /// namespace ts { @@ -150,6 +151,12 @@ namespace ts { type: "boolean", description: Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code }, + { + name: "pretty", + paramType: Diagnostics.KIND, + description: Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental, + type: "boolean" + }, { name: "project", shortName: "p", @@ -248,6 +255,26 @@ namespace ts { description: Diagnostics.Specifies_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6, error: Diagnostics.Argument_for_moduleResolution_option_must_be_node_or_classic, }, + { + name: "allowUnusedLabels", + type: "boolean", + description: Diagnostics.Do_not_report_errors_on_unused_labels + }, + { + name: "noImplicitReturns", + type: "boolean", + description: Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value + }, + { + name: "noFallthroughCasesInSwitch", + type: "boolean", + description: Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement + }, + { + name: "allowUnreachableCode", + type: "boolean", + description: Diagnostics.Do_not_report_errors_on_unreachable_code + }, { name: "forceConsistentCasingInFileNames", type: "boolean", @@ -273,8 +300,8 @@ namespace ts { return optionNameMapCache; } - let optionNameMap: Map = {}; - let shortOptionNames: Map = {}; + const optionNameMap: Map = {}; + const shortOptionNames: Map = {}; forEach(optionDeclarations, option => { optionNameMap[option.name.toLowerCase()] = option; if (option.shortName) { @@ -287,10 +314,10 @@ namespace ts { } export function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine { - let options: CompilerOptions = {}; - let fileNames: string[] = []; - let errors: Diagnostic[] = []; - let { optionNameMap, shortOptionNames } = getOptionNameMap(); + const options: CompilerOptions = {}; + const fileNames: string[] = []; + const errors: Diagnostic[] = []; + const { optionNameMap, shortOptionNames } = getOptionNameMap(); parseStrings(commandLine); return { @@ -315,7 +342,7 @@ namespace ts { } if (hasProperty(optionNameMap, s)) { - let opt = optionNameMap[s]; + const opt = optionNameMap[s]; // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument). if (!args[i] && opt.type !== "boolean") { @@ -355,19 +382,19 @@ namespace ts { } function parseResponseFile(fileName: string) { - let text = readFile ? readFile(fileName) : sys.readFile(fileName); + const text = readFile ? readFile(fileName) : sys.readFile(fileName); if (!text) { errors.push(createCompilerDiagnostic(Diagnostics.File_0_not_found, fileName)); return; } - let args: string[] = []; + const args: string[] = []; let pos = 0; while (true) { while (pos < text.length && text.charCodeAt(pos) <= CharacterCodes.space) pos++; if (pos >= text.length) break; - let start = pos; + const start = pos; if (text.charCodeAt(start) === CharacterCodes.doubleQuote) { pos++; while (pos < text.length && text.charCodeAt(pos) !== CharacterCodes.doubleQuote) pos++; @@ -410,13 +437,41 @@ namespace ts { */ export function parseConfigFileTextToJson(fileName: string, jsonText: string): { config?: any; error?: Diagnostic } { try { - return { config: /\S/.test(jsonText) ? JSON.parse(jsonText) : {} }; + const jsonTextWithoutComments = removeComments(jsonText); + return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; } catch (e) { return { error: createCompilerDiagnostic(Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; } } + + /** + * Remove the comments from a json like text. + * Comments can be single line comments (starting with # or //) or multiline comments using / * * / + * + * This method replace comment content by whitespace rather than completely remove them to keep positions in json parsing error reporting accurate. + */ + function removeComments(jsonText: string): string { + let output = ""; + const scanner = createScanner(ScriptTarget.ES5, /* skipTrivia */ false, LanguageVariant.Standard, jsonText); + let token: SyntaxKind; + while ((token = scanner.scan()) !== SyntaxKind.EndOfFileToken) { + switch (token) { + case SyntaxKind.SingleLineCommentTrivia: + case SyntaxKind.MultiLineCommentTrivia: + // replace comments with whitespace to preserve original character positions + output += scanner.getTokenText().replace(/\S/g, " "); + break; + default: + output += scanner.getTokenText(); + break; + } + } + return output; + } + + /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -425,9 +480,9 @@ namespace ts { * file to. e.g. outDir */ export function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions: CompilerOptions = {}): ParsedCommandLine { - let { options, errors } = convertCompilerOptionsFromJson(json["compilerOptions"], basePath); + const { options: optionsFromJsonConfigFile, errors } = convertCompilerOptionsFromJson(json["compilerOptions"], basePath); - options = extend(existingOptions, options); + const options = extend(existingOptions, optionsFromJsonConfigFile); return { options, fileNames: getFileNames(), @@ -445,20 +500,20 @@ namespace ts { } } else { - let filesSeen: Map = {}; - let exclude = json["exclude"] instanceof Array ? map(json["exclude"], normalizeSlashes) : undefined; - let extensionsByPriority = getSupportedExtensions(options); + const filesSeen: Map = {}; + const exclude = json["exclude"] instanceof Array ? map(json["exclude"], normalizeSlashes) : undefined; + const extensionsByPriority = getSupportedExtensions(options); for (let extensionsIndex = 0; extensionsIndex < extensionsByPriority.length; extensionsIndex++) { - let currentExtension = extensionsByPriority[extensionsIndex]; - let filesInDirWithExtension = host.readDirectory(basePath, currentExtension, exclude); + const currentExtension = extensionsByPriority[extensionsIndex]; + const filesInDirWithExtension = host.readDirectory(basePath, currentExtension, exclude); // Get list of conflicting extensions, conflicting extension is // - extension that is lower priority than current extension and // - extension also is current extension (ends with "." + currentExtension) - let conflictingExtensions: string[] = []; + const conflictingExtensions: string[] = []; for (let i = extensionsIndex + 1; i < extensionsByPriority.length; i++) { - let extension = extensionsByPriority[i]; // lower priority extension + const extension = extensionsByPriority[i]; // lower priority extension if (fileExtensionIs(extension, currentExtension)) { // also has current extension - conflictingExtensions.push(extension); + conflictingExtensions.push(extension); } } @@ -490,24 +545,24 @@ namespace ts { } export function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string): { options: CompilerOptions, errors: Diagnostic[] } { - let options: CompilerOptions = {}; - let errors: Diagnostic[] = []; + const options: CompilerOptions = {}; + const errors: Diagnostic[] = []; if (!jsonOptions) { return { options, errors }; } - let optionNameMap = arrayToMap(optionDeclarations, opt => opt.name); + const optionNameMap = arrayToMap(optionDeclarations, opt => opt.name); - for (let id in jsonOptions) { + for (const id in jsonOptions) { if (hasProperty(optionNameMap, id)) { - let opt = optionNameMap[id]; - let optType = opt.type; + const opt = optionNameMap[id]; + const optType = opt.type; let value = jsonOptions[id]; - let expectedType = typeof optType === "string" ? optType : "string"; + const expectedType = typeof optType === "string" ? optType : "string"; if (typeof value === expectedType) { if (typeof optType !== "string") { - let key = value.toLowerCase(); + const key = value.toLowerCase(); if (hasProperty(optType, key)) { value = optType[key]; } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 1b19eb5a77b..5b0eedfc1f9 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -29,7 +29,7 @@ namespace ts { }; function forEachValueInMap(f: (key: Path, value: T) => void) { - for (let key in files) { + for (const key in files) { f(key, files[key]); } } @@ -84,7 +84,7 @@ namespace ts { export function forEach(array: T[], callback: (element: T, index: number) => U): U { if (array) { for (let i = 0, len = array.length; i < len; i++) { - let result = callback(array[i], i); + const result = callback(array[i], i); if (result) { return result; } @@ -95,7 +95,7 @@ namespace ts { export function contains(array: T[], value: T): boolean { if (array) { - for (let v of array) { + for (const v of array) { if (v === value) { return true; } @@ -118,7 +118,7 @@ namespace ts { export function countWhere(array: T[], predicate: (x: T) => boolean): number { let count = 0; if (array) { - for (let v of array) { + for (const v of array) { if (predicate(v)) { count++; } @@ -131,7 +131,7 @@ namespace ts { let result: T[]; if (array) { result = []; - for (let item of array) { + for (const item of array) { if (f(item)) { result.push(item); } @@ -144,7 +144,7 @@ namespace ts { let result: U[]; if (array) { result = []; - for (let v of array) { + for (const v of array) { result.push(f(v)); } } @@ -162,7 +162,7 @@ namespace ts { let result: T[]; if (array) { result = []; - for (let item of array) { + for (const item of array) { if (!contains(result, item)) { result.push(item); } @@ -173,7 +173,7 @@ namespace ts { export function sum(array: any[], prop: string): number { let result = 0; - for (let v of array) { + for (const v of array) { result += v[prop]; } return result; @@ -181,7 +181,7 @@ namespace ts { export function addRange(to: T[], from: T[]): void { if (to && from) { - for (let v of from) { + for (const v of from) { to.push(v); } } @@ -220,8 +220,8 @@ namespace ts { let high = array.length - 1; while (low <= high) { - let middle = low + ((high - low) >> 1); - let midValue = array[middle]; + const middle = low + ((high - low) >> 1); + const midValue = array[middle]; if (midValue === value) { return middle; @@ -270,7 +270,7 @@ namespace ts { return initial; } - let hasOwnProperty = Object.prototype.hasOwnProperty; + const hasOwnProperty = Object.prototype.hasOwnProperty; export function hasProperty(map: Map, key: string): boolean { return hasOwnProperty.call(map, key); @@ -281,7 +281,7 @@ namespace ts { } export function isEmpty(map: Map) { - for (let id in map) { + for (const id in map) { if (hasProperty(map, id)) { return false; } @@ -290,19 +290,19 @@ namespace ts { } export function clone(object: T): T { - let result: any = {}; - for (let id in object) { + const result: any = {}; + for (const id in object) { result[id] = (object)[id]; } return result; } export function extend(first: Map, second: Map): Map { - let result: Map = {}; - for (let id in first) { + const result: Map = {}; + for (const id in first) { (result as any)[id] = first[id]; } - for (let id in second) { + for (const id in second) { if (!hasProperty(result, id)) { (result as any)[id] = second[id]; } @@ -312,7 +312,7 @@ namespace ts { export function forEachValue(map: Map, callback: (value: T) => U): U { let result: U; - for (let id in map) { + for (const id in map) { if (result = callback(map[id])) break; } return result; @@ -320,7 +320,7 @@ namespace ts { export function forEachKey(map: Map, callback: (key: string) => U): U { let result: U; - for (let id in map) { + for (const id in map) { if (result = callback(id)) break; } return result; @@ -331,7 +331,7 @@ namespace ts { } export function copyMap(source: Map, target: Map): void { - for (let p in source) { + for (const p in source) { target[p] = source[p]; } } @@ -347,7 +347,7 @@ namespace ts { * index in the array will be the one associated with the produced key. */ export function arrayToMap(array: T[], makeKey: (value: T) => string): Map { - let result: Map = {}; + const result: Map = {}; forEach(array, value => { result[makeKey(value)] = value; @@ -383,7 +383,7 @@ namespace ts { export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic; export function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage): Diagnostic { - let end = start + length; + const end = start + length; Debug.assert(start >= 0, "start must be non-negative, is " + start); Debug.assert(length >= 0, "length must be non-negative, is " + length); @@ -479,10 +479,10 @@ namespace ts { function compareMessageText(text1: string | DiagnosticMessageChain, text2: string | DiagnosticMessageChain): Comparison { while (text1 && text2) { // We still have both chains. - let string1 = typeof text1 === "string" ? text1 : text1.messageText; - let string2 = typeof text2 === "string" ? text2 : text2.messageText; + const string1 = typeof text1 === "string" ? text1 : text1.messageText; + const string2 = typeof text2 === "string" ? text2 : text2.messageText; - let res = compareValues(string1, string2); + const res = compareValues(string1, string2); if (res) { return res; } @@ -509,11 +509,11 @@ namespace ts { return diagnostics; } - let newDiagnostics = [diagnostics[0]]; + const newDiagnostics = [diagnostics[0]]; let previousDiagnostic = diagnostics[0]; for (let i = 1; i < diagnostics.length; i++) { - let currentDiagnostic = diagnostics[i]; - let isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === Comparison.EqualTo; + const currentDiagnostic = diagnostics[i]; + const isDupe = compareDiagnostics(currentDiagnostic, previousDiagnostic) === Comparison.EqualTo; if (!isDupe) { newDiagnostics.push(currentDiagnostic); previousDiagnostic = currentDiagnostic; @@ -531,9 +531,9 @@ namespace ts { export function getRootLength(path: string): number { if (path.charCodeAt(0) === CharacterCodes.slash) { if (path.charCodeAt(1) !== CharacterCodes.slash) return 1; - let p1 = path.indexOf("/", 2); + const p1 = path.indexOf("/", 2); if (p1 < 0) return 2; - let p2 = path.indexOf("/", p1 + 1); + const p2 = path.indexOf("/", p1 + 1); if (p2 < 0) return p1 + 1; return p2 + 1; } @@ -549,7 +549,7 @@ namespace ts { if (path.lastIndexOf("file:///", 0) === 0) { return "file:///".length; } - let idx = path.indexOf("://"); + const idx = path.indexOf("://"); if (idx !== -1) { return idx + "://".length; } @@ -558,9 +558,9 @@ namespace ts { export let directorySeparator = "/"; function getNormalizedParts(normalizedSlashedPath: string, rootLength: number) { - let parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator); - let normalized: string[] = []; - for (let part of parts) { + const parts = normalizedSlashedPath.substr(rootLength).split(directorySeparator); + const normalized: string[] = []; + for (const part of parts) { if (part !== ".") { if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { normalized.pop(); @@ -580,8 +580,8 @@ namespace ts { export function normalizePath(path: string): string { path = normalizeSlashes(path); - let rootLength = getRootLength(path); - let normalized = getNormalizedParts(path, rootLength); + const rootLength = getRootLength(path); + const normalized = getNormalizedParts(path, rootLength); return path.substr(0, rootLength) + normalized.join(directorySeparator); } @@ -598,7 +598,7 @@ namespace ts { } function normalizedPathComponents(path: string, rootLength: number) { - let normalizedParts = getNormalizedParts(path, rootLength); + const normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); } @@ -629,7 +629,7 @@ namespace ts { // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] - let urlLength = url.length; + const urlLength = url.length; // Initial root length is http:// part let rootLength = url.indexOf("://") + "://".length; while (rootLength < urlLength) { @@ -650,7 +650,7 @@ namespace ts { } // Find the index of "/" after website.com so the root can be http://www.website.com/ (from existing http://) - let indexOfNextSlash = url.indexOf(directorySeparator, rootLength); + const indexOfNextSlash = url.indexOf(directorySeparator, rootLength); if (indexOfNextSlash !== -1) { // Found the "/" after the website.com so the root is length of http://www.website.com/ // and get components afetr the root normally like any other folder components @@ -676,8 +676,8 @@ namespace ts { } export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: (fileName: string) => string, isAbsolutePathAnUrl: boolean) { - let pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); - let directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); + const pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); + const directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name // that is ["test", "cases", ""] needs to be actually ["test", "cases"] @@ -694,7 +694,7 @@ namespace ts { // Get the relative path if (joinStartIndex) { let relativePath = ""; - let relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); + const relativePathComponents = pathComponents.slice(joinStartIndex, pathComponents.length); for (; joinStartIndex < directoryComponents.length; joinStartIndex++) { if (directoryComponents[joinStartIndex] !== "") { relativePath = relativePath + ".." + directorySeparator; @@ -717,7 +717,7 @@ namespace ts { if (path === undefined) { return undefined; } - let i = path.lastIndexOf(directorySeparator); + const i = path.lastIndexOf(directorySeparator); return i < 0 ? path : path.substring(i + 1); } @@ -730,8 +730,8 @@ namespace ts { } export function fileExtensionIs(path: string, extension: string): boolean { - let pathLen = path.length; - let extLen = extension.length; + const pathLen = path.length; + const extLen = extension.length; return pathLen > extLen && path.substr(pathLen - extLen, extLen) === extension; } @@ -749,7 +749,7 @@ namespace ts { export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions) { if (!fileName) { return false; } - for (let extension of getSupportedExtensions(compilerOptions)) { + for (const extension of getSupportedExtensions(compilerOptions)) { if (fileExtensionIs(fileName, extension)) { return true; } @@ -759,7 +759,7 @@ namespace ts { const extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"]; export function removeFileExtension(path: string): string { - for (let ext of extensionsToRemove) { + for (const ext of extensionsToRemove) { if (fileExtensionIs(path, ext)) { return path.substr(0, path.length - ext.length); } @@ -767,9 +767,9 @@ namespace ts { return path; } - let backslashOrDoubleQuote = /[\"\\]/g; - let escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - let escapedCharsMap: Map = { + const backslashOrDoubleQuote = /[\"\\]/g; + const escapedCharsRegExp = /[\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + const escapedCharsMap: Map = { "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -828,7 +828,7 @@ namespace ts { } export namespace Debug { - let currentAssertionLevel = AssertionLevel.None; + const currentAssertionLevel = AssertionLevel.None; export function shouldAssert(level: AssertionLevel): boolean { return currentAssertionLevel >= level; @@ -851,8 +851,8 @@ namespace ts { } export function copyListRemovingItem(item: T, list: T[]) { - let copiedList: T[] = []; - for (let e of list) { + const copiedList: T[] = []; + for (const e of list) { if (e !== item) { copiedList.push(e); } diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 348a22e23e8..c965a5a3911 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -31,7 +31,7 @@ namespace ts { } export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] { - let declarationDiagnostics = createDiagnosticCollection(); + const declarationDiagnostics = createDiagnosticCollection(); forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); return declarationDiagnostics.getDiagnostics(targetSourceFile.fileName); @@ -42,8 +42,8 @@ namespace ts { function emitDeclarations(host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection, declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): DeclarationEmit { - let newLine = host.getNewLine(); - let compilerOptions = host.getCompilerOptions(); + const newLine = host.getNewLine(); + const compilerOptions = host.getCompilerOptions(); let write: (s: string) => void; let writeLine: () => void; @@ -57,10 +57,10 @@ namespace ts { let currentSourceFile: SourceFile; let reportedDeclarationError = false; let errorNameNode: DeclarationName; - let emitJsDocComments = compilerOptions.removeComments ? function (declaration: Node) { } : writeJsDocComments; - let emit = compilerOptions.stripInternal ? stripInternal : emitNode; + const emitJsDocComments = compilerOptions.removeComments ? function (declaration: Node) { } : writeJsDocComments; + const emit = compilerOptions.stripInternal ? stripInternal : emitNode; - let moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = []; + const moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = []; let asynchronousSubModuleDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[]; // Contains the reference paths that needs to go in the declaration file. @@ -69,14 +69,14 @@ namespace ts { let referencePathsOutput = ""; // Emit references corresponding to each file - let emittedReferencedFiles: SourceFile[] = []; + const emittedReferencedFiles: SourceFile[] = []; let addedGlobalFileReference = false; forEach(sourceFiles, sourceFile => { if (!isJavaScript(sourceFile.fileName)) { // Check what references need to be added if (!compilerOptions.noResolve) { forEach(sourceFile.referencedFiles, fileReference => { - let referencedFile = tryResolveScriptReference(host, sourceFile, fileReference); + const referencedFile = tryResolveScriptReference(host, sourceFile, fileReference); // Emit reference in dts, if the file reference was not already emitted if (referencedFile && !contains(emittedReferencedFiles, referencedFile)) { @@ -96,7 +96,7 @@ namespace ts { // create asynchronous output for the importDeclarations if (moduleElementDeclarationEmitInfo.length) { - let oldWriter = writer; + const oldWriter = writer; forEach(moduleElementDeclarationEmitInfo, aliasEmitInfo => { if (aliasEmitInfo.isVisible) { Debug.assert(aliasEmitInfo.node.kind === SyntaxKind.ImportDeclaration); @@ -119,14 +119,14 @@ namespace ts { }; function hasInternalAnnotation(range: CommentRange) { - let text = currentSourceFile.text; - let comment = text.substring(range.pos, range.end); + const text = currentSourceFile.text; + const comment = text.substring(range.pos, range.end); return comment.indexOf("@internal") >= 0; } function stripInternal(node: Node) { if (node) { - let leadingCommentRanges = getLeadingCommentRanges(currentSourceFile.text, node.pos); + const leadingCommentRanges = getLeadingCommentRanges(currentSourceFile.text, node.pos); if (forEach(leadingCommentRanges, hasInternalAnnotation)) { return; } @@ -136,7 +136,7 @@ namespace ts { } function createAndSetNewTextWriterWithSymbolWriter(): EmitTextWriterWithSymbolWriter { - let writer = createTextWriter(newLine); + const writer = createTextWriter(newLine); writer.trackSymbol = trackSymbol; writer.reportInaccessibleThisError = reportInaccessibleThisError; writer.writeKeyword = writer.write; @@ -160,7 +160,7 @@ namespace ts { } function writeAsynchronousModuleElements(nodes: Node[]) { - let oldWriter = writer; + const oldWriter = writer; forEach(nodes, declaration => { let nodeToCheck: Node; if (declaration.kind === SyntaxKind.VariableDeclaration) { @@ -223,7 +223,7 @@ namespace ts { else { // Report error reportedDeclarationError = true; - let errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); + const errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccesibilityResult); if (errorInfo) { if (errorInfo.typeName) { emitterDiagnostics.add(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode, @@ -283,14 +283,14 @@ namespace ts { } function emitLines(nodes: Node[]) { - for (let node of nodes) { + for (const node of nodes) { emit(node); } } function emitSeparatedList(nodes: Node[], separator: string, eachNodeEmitFn: (node: Node) => void, canEmitFn?: (node: Node) => boolean) { let currentWriterPos = writer.getTextPos(); - for (let node of nodes) { + for (const node of nodes) { if (!canEmitFn || canEmitFn(node)) { if (currentWriterPos !== writer.getTextPos()) { write(separator); @@ -307,7 +307,7 @@ namespace ts { function writeJsDocComments(declaration: Node) { if (declaration) { - let jsDocComments = getJsDocComments(declaration, currentSourceFile); + const jsDocComments = getJsDocComments(declaration, currentSourceFile); emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments); // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space emitComments(currentSourceFile, writer, jsDocComments, /*trailingSeparator*/ true, newLine, writeCommentRange); @@ -364,8 +364,8 @@ namespace ts { writeTextOfNode(currentSourceFile, entityName); } else { - let left = entityName.kind === SyntaxKind.QualifiedName ? (entityName).left : (entityName).expression; - let right = entityName.kind === SyntaxKind.QualifiedName ? (entityName).right : (entityName).name; + const left = entityName.kind === SyntaxKind.QualifiedName ? (entityName).left : (entityName).expression; + const right = entityName.kind === SyntaxKind.QualifiedName ? (entityName).right : (entityName).name; writeEntityName(left); write("."); writeTextOfNode(currentSourceFile, right); @@ -373,7 +373,7 @@ namespace ts { } function emitEntityName(entityName: EntityName | PropertyAccessExpression) { - let visibilityResult = resolver.isEntityNameVisible(entityName, + const visibilityResult = resolver.isEntityNameVisible(entityName, // Aliases can be written asynchronously so use correct enclosing declaration entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration ? entityName.parent : enclosingDeclaration); @@ -454,6 +454,7 @@ namespace ts { function emitSourceFile(node: SourceFile) { currentSourceFile = node; enclosingDeclaration = node; + emitDetachedComments(currentSourceFile, writer, writeCommentRange, node, newLine, true /* remove comments */); emitLines(node.statements); } @@ -462,13 +463,13 @@ namespace ts { // Note that export default is only allowed at most once in a module, so we // do not need to keep track of created temp names. function getExportDefaultTempVariableName(): string { - let baseName = "_default"; + const baseName = "_default"; if (!hasProperty(currentSourceFile.identifiers, baseName)) { return baseName; } let count = 0; while (true) { - let name = baseName + "_" + (++count); + const name = baseName + "_" + (++count); if (!hasProperty(currentSourceFile.identifiers, name)) { return name; } @@ -482,7 +483,7 @@ namespace ts { } else { // Expression - let tempVarName = getExportDefaultTempVariableName(); + const tempVarName = getExportDefaultTempVariableName(); write("declare var "); write(tempVarName); write(": "); @@ -498,7 +499,7 @@ namespace ts { // Make all the declarations visible for the export name if (node.expression.kind === SyntaxKind.Identifier) { - let nodes = resolver.collectLinkedAliases(node.expression); + const nodes = resolver.collectLinkedAliases(node.expression); // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); @@ -535,7 +536,7 @@ namespace ts { } else { if (node.kind === SyntaxKind.ImportDeclaration) { - let importDeclaration = node; + const importDeclaration = node; if (importDeclaration.importClause) { isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || isVisibleNamedBinding(importDeclaration.importClause.namedBindings); @@ -661,7 +662,7 @@ namespace ts { } write("import "); if (node.importClause) { - let currentWriterPos = writer.getTextPos(); + const currentWriterPos = writer.getTextPos(); if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { writeTextOfNode(currentSourceFile, node.importClause.name); } @@ -699,7 +700,7 @@ namespace ts { emitImportOrExportSpecifier(node); // Make all the declarations visible for the export name - let nodes = resolver.collectLinkedAliases(node.propertyName || node.name); + const nodes = resolver.collectLinkedAliases(node.propertyName || node.name); // write each of these declarations asynchronously writeAsynchronousModuleElements(nodes); @@ -739,7 +740,7 @@ namespace ts { write("."); writeTextOfNode(currentSourceFile, node.name); } - let prevEnclosingDeclaration = enclosingDeclaration; + const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; write(" {"); writeLine(); @@ -752,7 +753,7 @@ namespace ts { } function writeTypeAliasDeclaration(node: TypeAliasDeclaration) { - let prevEnclosingDeclaration = enclosingDeclaration; + const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitJsDocComments(node); emitModuleElementDeclarationFlags(node); @@ -794,7 +795,7 @@ namespace ts { function emitEnumMemberDeclaration(node: EnumMember) { emitJsDocComments(node); writeTextOfNode(currentSourceFile, node.name); - let enumMemberValue = resolver.getConstantValue(node); + const enumMemberValue = resolver.getConstantValue(node); if (enumMemberValue !== undefined) { write(" = "); write(enumMemberValue.toString()); @@ -944,10 +945,10 @@ namespace ts { write("class "); writeTextOfNode(currentSourceFile, node.name); - let prevEnclosingDeclaration = enclosingDeclaration; + const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); - let baseTypeNode = getClassExtendsHeritageClauseElement(node); + const baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); } @@ -968,7 +969,7 @@ namespace ts { emitModuleElementDeclarationFlags(node); write("interface "); writeTextOfNode(currentSourceFile, node.name); - let prevEnclosingDeclaration = enclosingDeclaration; + const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; emitTypeParameters(node.typeParameters); emitHeritageClause(getInterfaceBaseTypeNodes(node), /*isImplementsList*/ false); @@ -1054,7 +1055,7 @@ namespace ts { } function getVariableDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - let diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, @@ -1068,8 +1069,8 @@ namespace ts { // For example: // original: var [, c,,] = [ 2,3,4] // emitted: declare var c: number; // instead of declare var c:number, ; - let elements: Node[] = []; - for (let element of bindingPattern.elements) { + const elements: Node[] = []; + for (const element of bindingPattern.elements) { if (element.kind !== SyntaxKind.OmittedExpression) { elements.push(element); } @@ -1079,7 +1080,7 @@ namespace ts { function emitBindingElement(bindingElement: BindingElement) { function getBindingElementTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - let diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: bindingElement, @@ -1135,7 +1136,7 @@ namespace ts { return; } - let accessors = getAllAccessorDeclarations((node.parent).members, node); + const accessors = getAllAccessorDeclarations((node.parent).members, node); let accessorWithTypeAnnotation: AccessorDeclaration; if (node === accessors.firstAccessor) { @@ -1148,7 +1149,7 @@ namespace ts { let type = getTypeAnnotationFromAccessor(node); if (!type) { // couldn't get type for the first accessor, try the another one - let anotherAccessor = node.kind === SyntaxKind.GetAccessor ? accessors.setAccessor : accessors.getAccessor; + const anotherAccessor = node.kind === SyntaxKind.GetAccessor ? accessors.setAccessor : accessors.getAccessor; type = getTypeAnnotationFromAccessor(anotherAccessor); if (type) { accessorWithTypeAnnotation = anotherAccessor; @@ -1265,7 +1266,7 @@ namespace ts { write("("); } - let prevEnclosingDeclaration = enclosingDeclaration; + const prevEnclosingDeclaration = enclosingDeclaration; enclosingDeclaration = node; // Parameters @@ -1279,7 +1280,7 @@ namespace ts { } // If this is not a constructor and is not private, emit the return type - let isFunctionTypeOrConstructorType = node.kind === SyntaxKind.FunctionType || node.kind === SyntaxKind.ConstructorType; + const isFunctionTypeOrConstructorType = node.kind === SyntaxKind.FunctionType || node.kind === SyntaxKind.ConstructorType; if (isFunctionTypeOrConstructorType || node.parent.kind === SyntaxKind.TypeLiteral) { // Emit type literal signature return type only if specified if (node.type) { @@ -1395,7 +1396,7 @@ namespace ts { } function getParameterDeclarationTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - let diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + const diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: node, @@ -1468,7 +1469,7 @@ namespace ts { } else if (bindingPattern.kind === SyntaxKind.ArrayBindingPattern) { write("["); - let elements = bindingPattern.elements; + const elements = bindingPattern.elements; emitCommaList(elements, emitBindingElement); if (elements && elements.hasTrailingComma) { write(", "); @@ -1479,7 +1480,7 @@ namespace ts { function emitBindingElement(bindingElement: BindingElement) { function getBindingElementTypeVisibilityError(symbolAccesibilityResult: SymbolAccessiblityResult): SymbolAccessibilityDiagnostic { - let diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); + const diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccesibilityResult); return diagnosticMessage !== undefined ? { diagnosticMessage, errorNode: bindingElement, @@ -1618,13 +1619,12 @@ namespace ts { /* @internal */ export function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection) { - let emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); - let emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath); + const emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + const emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath); if (!emitSkipped) { - let declarationOutput = emitDeclarationResult.referencePathsOutput + const declarationOutput = emitDeclarationResult.referencePathsOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - let compilerOptions = host.getCompilerOptions(); - writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, compilerOptions.emitBOM); + writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM); } return emitSkipped; diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 6cb5858f8ee..ca31abceb85 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1012,7 +1012,7 @@ "category": "Error", "code": 2354 }, - "A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement.": { + "A function whose declared type is neither 'void' nor 'any' must return a value.": { "category": "Error", "code": 2355 }, @@ -1096,7 +1096,7 @@ "category": "Error", "code": 2377 }, - "A 'get' accessor must return a value or consist of a single 'throw' statement.": { + "A 'get' accessor must return a value.": { "category": "Error", "code": 2378 }, @@ -2266,14 +2266,6 @@ "code": 6063 }, - "Specify JSX code generation: 'preserve' or 'react'": { - "category": "Message", - "code": 6080 - }, - "Argument for '--jsx' must be 'preserve' or 'react'.": { - "category": "Message", - "code": 6081 - }, "Enables experimental support for ES7 decorators.": { "category": "Message", "code": 6065 @@ -2302,14 +2294,43 @@ "category": "Message", "code": 6072 }, - "Disallow inconsistently-cased references to the same file.": { + "Stylize errors and messages using color and context. (experimental)": { "category": "Message", "code": 6073 }, - "Allow javascript files to be compiled.": { + "Do not report errors on unused labels.": { "category": "Message", "code": 6074 }, + "Report error when not all code paths in function return a value.": { + "category": "Message", + "code": 6075 + }, + "Report errors for fallthrough cases in switch statement.": { + "category": "Message", + "code": 6076 + }, + "Do not report errors on unreachable code.": { + "category": "Message", + "code": 6077 + }, + "Disallow inconsistently-cased references to the same file.": { + "category": "Message", + "code": 6078 + }, + + "Specify JSX code generation: 'preserve' or 'react'": { + "category": "Message", + "code": 6080 + }, + "Argument for '--jsx' must be 'preserve' or 'react'.": { + "category": "Message", + "code": 6081 + }, + "Allow javascript files to be compiled.": { + "category": "Message", + "code": 6082 + }, "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", @@ -2379,8 +2400,22 @@ "category": "Error", "code": 7026 }, - - + "Unreachable code detected.": { + "category": "Error", + "code": 7027 + }, + "Unused label.": { + "category": "Error", + "code": 7028 + }, + "Fallthrough case in switch.": { + "category": "Error", + "code": 7029 + }, + "Not all code paths return a value.": { + "category": "Error", + "code": 7030 + }, "You cannot rename this element.": { "category": "Error", "code": 8000 diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index d3fc80a3c5e..eb4b9a6218f 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -9,7 +9,13 @@ namespace ts { type DependencyGroup = Array; - let entities: Map = { + const enum Jump { + Break = 1 << 1, + Continue = 1 << 2, + Return = 1 << 3 + } + + const entities: Map = { "quot": 0x0022, "amp": 0x0026, "apos": 0x0027, @@ -318,13 +324,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi }); };`; - let compilerOptions = host.getCompilerOptions(); - let languageVersion = compilerOptions.target || ScriptTarget.ES3; - let modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None; - let sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; - let emitterDiagnostics = createDiagnosticCollection(); + const compilerOptions = host.getCompilerOptions(); + const languageVersion = compilerOptions.target || ScriptTarget.ES3; + const modulekind = compilerOptions.module ? compilerOptions.module : languageVersion === ScriptTarget.ES6 ? ModuleKind.ES6 : ModuleKind.None; + const sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined; + const emitterDiagnostics = createDiagnosticCollection(); let emitSkipped = false; - let newLine = host.getNewLine(); + const newLine = host.getNewLine(); forEachExpectedEmitFile(host, emitFile, targetSourceFile); @@ -334,14 +340,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi sourceMaps: sourceMapDataList }; - function isNodeDescendentOf(node: Node, ancestor: Node): boolean { - while (node) { - if (node === ancestor) return true; - node = node.parent; - } - return false; - } - function isUniqueLocalName(name: string, container: Node): boolean { for (let node = container; isNodeDescendentOf(node, container); node = node.nextContainer) { if (node.locals && hasProperty(node.locals, name)) { @@ -354,12 +352,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return true; } - const enum Jump { - Break = 1 << 1, - Continue = 1 << 2, - Return = 1 << 3 - } - interface ConvertedLoopState { /* * set of labels that occured inside the converted loop @@ -454,8 +446,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitJavaScript(jsFilePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) { - let writer = createTextWriter(newLine); - let { write, writeTextOfNode, writeLine, increaseIndent, decreaseIndent } = writer; + const writer = createTextWriter(newLine); + const { write, writeTextOfNode, writeLine, increaseIndent, decreaseIndent } = writer; let currentSourceFile: SourceFile; // name of an exporter function if file is a System external module @@ -466,8 +458,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // var x;... exporter("x", x = 1) let exportFunctionForFile: string; - let generatedNameSet: Map = {}; - let nodeToGeneratedName: string[] = []; + const generatedNameSet: Map = {}; + const nodeToGeneratedName: string[] = []; let computedPropertyNamesToGeneratedNames: string[]; let convertedLoopState: ConvertedLoopState; @@ -520,9 +512,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let sourceMapData: SourceMapData; /** If removeComments is true, no leading-comments needed to be emitted **/ - let emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos: number) { } : emitLeadingCommentsOfPositionWorker; + const emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos: number) { } : emitLeadingCommentsOfPositionWorker; - let moduleEmitDelegates: Map<(node: SourceFile) => void> = { + const moduleEmitDelegates: Map<(node: SourceFile) => void> = { [ModuleKind.ES6]: emitES6Module, [ModuleKind.AMD]: emitAMDModule, [ModuleKind.System]: emitSystemModule, @@ -558,18 +550,18 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Note that names generated by makeTempVariableName and makeUniqueName will never conflict. function makeTempVariableName(flags: TempFlags): string { if (flags && !(tempFlags & flags)) { - let name = flags === TempFlags._i ? "_i" : "_n"; + const name = flags === TempFlags._i ? "_i" : "_n"; if (isUniqueName(name)) { tempFlags |= flags; return name; } } while (true) { - let count = tempFlags & TempFlags.CountMask; + const count = tempFlags & TempFlags.CountMask; tempFlags++; // Skip over 'i' and 'n' if (count !== 8 && count !== 13) { - let name = count < 26 ? "_" + String.fromCharCode(CharacterCodes.a + count) : "_" + (count - 26); + const name = count < 26 ? "_" + String.fromCharCode(CharacterCodes.a + count) : "_" + (count - 26); if (isUniqueName(name)) { return name; } @@ -588,7 +580,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } let i = 1; while (true) { - let generatedName = baseName + i; + const generatedName = baseName + i; if (isUniqueName(generatedName)) { return generatedNameSet[generatedName] = generatedName; } @@ -597,14 +589,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function generateNameForModuleOrEnum(node: ModuleDeclaration | EnumDeclaration) { - let name = node.name.text; + const name = node.name.text; // Use module/enum name itself if it is unique, otherwise make a unique variation return isUniqueLocalName(name, node) ? name : makeUniqueName(name); } function generateNameForImportOrExportDeclaration(node: ImportDeclaration | ExportDeclaration) { - let expr = getExternalModuleName(node); - let baseName = expr.kind === SyntaxKind.StringLiteral ? + const expr = getExternalModuleName(node); + const baseName = expr.kind === SyntaxKind.StringLiteral ? escapeIdentifier(makeIdentifierFromModuleName((expr).text)) : "module"; return makeUniqueName(baseName); } @@ -637,7 +629,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function getGeneratedNameForNode(node: Node) { - let id = getNodeId(node); + const id = getNodeId(node); return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = unescapeIdentifier(generateNameForNode(node))); } @@ -648,8 +640,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let sourceMapSourceIndex = -1; // Names and its index map - let sourceMapNameIndexMap: Map = {}; - let sourceMapNameIndices: number[] = []; + const sourceMapNameIndexMap: Map = {}; + const sourceMapNameIndices: number[] = []; function getSourceMapNameIndex() { return sourceMapNameIndices.length ? lastOrUndefined(sourceMapNameIndices) : -1; } @@ -745,14 +737,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function recordSourceMapSpan(pos: number) { - let sourceLinePos = getLineAndCharacterOfPosition(currentSourceFile, pos); + const sourceLinePos = getLineAndCharacterOfPosition(currentSourceFile, pos); // Convert the location to be one-based. sourceLinePos.line++; sourceLinePos.character++; - let emittedLine = writer.getLine(); - let emittedColumn = writer.getColumn(); + const emittedLine = writer.getLine(); + const emittedColumn = writer.getColumn(); // If this location wasn't recorded or the location in source is going backwards, record the span if (!lastRecordedSourceMapSpan || @@ -792,9 +784,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function writeTextWithSpanRecord(tokenKind: SyntaxKind, startPos: number, emitFn?: () => void) { - let tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); + const tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); recordSourceMapSpan(tokenStartPos); - let tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); + const tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); recordSourceMapSpan(tokenEndPos); return tokenEndPos; } @@ -803,7 +795,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Add the file to tsFilePaths // If sourceroot option: Use the relative path corresponding to the common directory path // otherwise source locations relative to map file location - let sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; + const sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; sourceMapData.sourceMapSources.push(getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, @@ -831,12 +823,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function recordScopeNameStart(scopeName: string) { let scopeNameIndex = -1; if (scopeName) { - let parentIndex = getSourceMapNameIndex(); + const parentIndex = getSourceMapNameIndex(); if (parentIndex !== -1) { // Child scopes are always shown with a dot (even if they have no name), // unless it is a computed property. Then it is shown with brackets, // but the brackets are included in the name. - let name = (node).name; + const name = (node).name; if (!name || name.kind !== SyntaxKind.ComputedPropertyName) { scopeName = "." + scopeName; } @@ -868,7 +860,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi node.kind === SyntaxKind.EnumDeclaration) { // Declaration and has associated name use it if ((node).name) { - let name = (node).name; + const name = (node).name; // For computed property names, the text will include the brackets scopeName = name.kind === SyntaxKind.ComputedPropertyName ? getTextOfNode(name) @@ -894,7 +886,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function serializeSourceMapContents(version: number, file: string, sourceRoot: string, sources: string[], names: string[], mappings: string, sourcesContent?: string[]) { if (typeof JSON !== "undefined") { - let map: any = { + const map: any = { version, file, sourceRoot, @@ -927,7 +919,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function writeJavaScriptAndSourceMapFile(emitOutput: string, writeByteOrderMark: boolean) { encodeLastRecordedSourceMapSpan(); - let sourceMapText = serializeSourceMapContents( + const sourceMapText = serializeSourceMapContents( 3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, @@ -941,7 +933,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let sourceMapUrl: string; if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url - let base64SourceMapText = convertToBase64(sourceMapText); + const base64SourceMapText = convertToBase64(sourceMapText); sourceMapData.jsSourceMappingURL = `data:application/json;base64,${base64SourceMapText}`; } else { @@ -1039,7 +1031,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Create a temporary variable with a unique unused name. function createTempVariable(flags: TempFlags): Identifier { - let result = createSynthesizedNode(SyntaxKind.Identifier); + const result = createSynthesizedNode(SyntaxKind.Identifier); result.text = makeTempVariableName(flags); return result; } @@ -1052,7 +1044,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createAndRecordTempVariable(flags: TempFlags): Identifier { - let temp = createTempVariable(flags); + const temp = createTempVariable(flags); recordTempDeclaration(temp); return temp; @@ -1073,7 +1065,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitTokenText(tokenKind: SyntaxKind, startPos: number, emitFn?: () => void) { - let tokenString = tokenToString(tokenKind); + const tokenString = tokenToString(tokenKind); if (emitFn) { emitFn(); } @@ -1167,7 +1159,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(", "); } } - let node = nodes[start + i]; + const node = nodes[start + i]; // This emitting is to make sure we emit following comment properly // ...(x, /*comment1*/ y)... // ^ => node.pos @@ -1219,7 +1211,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitLiteral(node: LiteralExpression) { - let text = getLiteralText(node); + const text = getLiteralText(node); if ((compilerOptions.sourceMap || compilerOptions.inlineSourceMap) && (node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind))) { writer.writeLiteral(text); @@ -1280,7 +1272,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // thus we need to remove those characters. // First template piece starts with "`", others with "}" // Last template piece ends with "`", others with "${" - let isLast = node.kind === SyntaxKind.NoSubstitutionTemplateLiteral || node.kind === SyntaxKind.TemplateTail; + const isLast = node.kind === SyntaxKind.NoSubstitutionTemplateLiteral || node.kind === SyntaxKind.TemplateTail; text = text.substring(1, text.length - (isLast ? 1 : 2)); // Newline normalization: @@ -1308,7 +1300,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitDownlevelTaggedTemplate(node: TaggedTemplateExpression) { - let tempVariable = createAndRecordTempVariable(TempFlags.Auto); + const tempVariable = createAndRecordTempVariable(TempFlags.Auto); write("("); emit(tempVariable); write(" = "); @@ -1328,7 +1320,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (node.template.kind === SyntaxKind.TemplateExpression) { forEach((node.template).templateSpans, templateSpan => { write(", "); - let needsParens = templateSpan.expression.kind === SyntaxKind.BinaryExpression + const needsParens = templateSpan.expression.kind === SyntaxKind.BinaryExpression && (templateSpan.expression).operatorToken.kind === SyntaxKind.CommaToken; emitParenthesizedIf(templateSpan.expression, needsParens); }); @@ -1344,7 +1336,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return; } - let emitOuterParens = isExpression(node.parent) + const emitOuterParens = isExpression(node.parent) && templateNeedsParens(node, node.parent); if (emitOuterParens) { @@ -1358,7 +1350,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } for (let i = 0, n = node.templateSpans.length; i < n; i++) { - let templateSpan = node.templateSpans[i]; + const templateSpan = node.templateSpans[i]; // Check if the expression has operands and binds its operands less closely than binary '+'. // If it does, we need to wrap the expression in parentheses. Otherwise, something like @@ -1369,7 +1361,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // ("abc" + 1) << (2 + "") // rather than // "abc" + (1 << 2) + "" - let needsParens = templateSpan.expression.kind !== SyntaxKind.ParenthesizedExpression + const needsParens = templateSpan.expression.kind !== SyntaxKind.ParenthesizedExpression && comparePrecedenceToBinaryPlus(templateSpan.expression) !== Comparison.GreaterThan; if (i > 0 || headEmitted) { @@ -1512,7 +1504,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitJsxElement(openingNode: JsxOpeningLikeElement, children?: JsxChild[]) { - let syntheticReactRef = createSynthesizedNode(SyntaxKind.Identifier); + const syntheticReactRef = createSynthesizedNode(SyntaxKind.Identifier); syntheticReactRef.text = "React"; syntheticReactRef.parent = openingNode; @@ -1531,7 +1523,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi else { // Either emit one big object literal (no spread attribs), or // a call to React.__spread - let attrs = openingNode.attributes; + const attrs = openingNode.attributes; if (forEach(attrs, attr => attr.kind === SyntaxKind.JsxSpreadAttribute)) { emitExpressionIdentifier(syntheticReactRef); write(".__spread("); @@ -1595,7 +1587,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Don't emit empty strings if (children[i].kind === SyntaxKind.JsxText) { - let text = getTextToEmit(children[i]); + const text = getTextToEmit(children[i]); if (text !== undefined) { write(", \""); write(text); @@ -1754,7 +1746,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function isExpressionIdentifier(node: Node): boolean { - let parent = node.parent; + const parent = node.parent; switch (parent.kind) { case SyntaxKind.ArrayLiteralExpression: case SyntaxKind.AsExpression: @@ -1822,7 +1814,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return; } - let container = resolver.getReferencedExportContainer(node); + const container = resolver.getReferencedExportContainer(node); if (container) { if (container.kind === SyntaxKind.SourceFile) { // Identifier references module export @@ -1838,7 +1830,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } else { if (modulekind !== ModuleKind.ES6) { - let declaration = resolver.getReferencedImportDeclaration(node); + const declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { if (declaration.kind === SyntaxKind.ImportClause) { // Identifier references default import @@ -1849,8 +1841,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi else if (declaration.kind === SyntaxKind.ImportSpecifier) { // Identifier references named import write(getGeneratedNameForNode(declaration.parent.parent.parent)); - let name = (declaration).propertyName || (declaration).name; - let identifier = getSourceTextOfNodeFromSourceFile(currentSourceFile, name); + const name = (declaration).propertyName || (declaration).name; + const identifier = getSourceTextOfNodeFromSourceFile(currentSourceFile, name); if (languageVersion === ScriptTarget.ES3 && identifier === "default") { write(`["default"]`); } @@ -1864,7 +1856,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } if (languageVersion !== ScriptTarget.ES6) { - let declaration = resolver.getReferencedNestedRedeclaration(node); + const declaration = resolver.getReferencedNestedRedeclaration(node); if (declaration) { write(getGeneratedNameForNode(declaration.name)); return; @@ -1882,7 +1874,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function isNameOfNestedRedeclaration(node: Identifier) { if (languageVersion < ScriptTarget.ES6) { - let parent = node.parent; + const parent = node.parent; switch (parent.kind) { case SyntaxKind.BindingElement: case SyntaxKind.ClassDeclaration: @@ -1898,7 +1890,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (convertedLoopState) { if (node.text == "arguments" && resolver.isArgumentsLocalBinding(node)) { // in converted loop body arguments cannot be used directly. - let name = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); + const name = convertedLoopState.argumentsName || (convertedLoopState.argumentsName = makeUniqueName("arguments")); write(name); return; } @@ -1935,7 +1927,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("super"); } else { - let flags = resolver.getNodeCheckFlags(node); + const flags = resolver.getNodeCheckFlags(node); if (flags & NodeCheckFlags.SuperInstance) { write("_super.prototype"); } @@ -1947,14 +1939,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitObjectBindingPattern(node: BindingPattern) { write("{ "); - let elements = node.elements; + const elements = node.elements; emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma); write(" }"); } function emitArrayBindingPattern(node: BindingPattern) { write("["); - let elements = node.elements; + const elements = node.elements; emitList(elements, 0, elements.length, /*multiLine*/ false, /*trailingComma*/ elements.hasTrailingComma); write("]"); } @@ -1993,7 +1985,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitAwaitExpression(node: AwaitExpression) { - let needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node); + const needsParenthesis = needsParenthesisForAwaitExpressionAsYield(node); if (needsParenthesis) { write("("); } @@ -2034,7 +2026,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitListWithSpread(elements: Expression[], needsUniqueCopy: boolean, multiLine: boolean, trailingComma: boolean, useConcat: boolean) { let pos = 0; let group = 0; - let length = elements.length; + const length = elements.length; while (pos < length) { // Emit using the pattern .concat(, , ...) if (group === 1 && useConcat) { @@ -2082,7 +2074,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitArrayLiteral(node: ArrayLiteralExpression) { - let elements = node.elements; + const elements = node.elements; if (elements.length === 0) { write("[]"); } @@ -2106,7 +2098,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("{"); if (numElements > 0) { - let properties = node.properties; + const properties = node.properties; // If we are not doing a downlevel transformation for object literals, // then try to preserve the original shape of the object literal. @@ -2115,7 +2107,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitLinePreservingList(node, properties, /* allowTrailingComma */ languageVersion >= ScriptTarget.ES5, /* spacesBetweenBraces */ true); } else { - let multiLine = (node.flags & NodeFlags.MultiLine) !== 0; + const multiLine = (node.flags & NodeFlags.MultiLine) !== 0; if (!multiLine) { write(" "); } @@ -2138,8 +2130,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitDownlevelObjectLiteralWithComputedProperties(node: ObjectLiteralExpression, firstComputedPropertyIndex: number) { - let multiLine = (node.flags & NodeFlags.MultiLine) !== 0; - let properties = node.properties; + const multiLine = (node.flags & NodeFlags.MultiLine) !== 0; + const properties = node.properties; write("("); @@ -2149,7 +2141,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // For computed properties, we need to create a unique handle to the object // literal so we can modify it without risking internal assignments tainting the object. - let tempVar = createAndRecordTempVariable(TempFlags.Auto); + const tempVar = createAndRecordTempVariable(TempFlags.Auto); // Write out the first non-computed properties // (or all properties if none of them are computed), @@ -2161,12 +2153,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi for (let i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { writeComma(); - let property = properties[i]; + const property = properties[i]; emitStart(property); if (property.kind === SyntaxKind.GetAccessor || property.kind === SyntaxKind.SetAccessor) { // TODO (drosen): Reconcile with 'emitMemberFunctions'. - let accessors = getAllAccessorDeclarations(node.properties, property); + const accessors = getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { continue; } @@ -2257,10 +2249,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitObjectLiteral(node: ObjectLiteralExpression): void { - let properties = node.properties; + const properties = node.properties; if (languageVersion < ScriptTarget.ES6) { - let numProperties = properties.length; + const numProperties = properties.length; // Find the first computed property. // Everything until that point can be emitted as part of the initial object literal. @@ -2272,7 +2264,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } } - let hasComputedProperty = numInitialNonComputedProperties !== properties.length; + const hasComputedProperty = numInitialNonComputedProperties !== properties.length; if (hasComputedProperty) { emitDownlevelObjectLiteralWithComputedProperties(node, numInitialNonComputedProperties); return; @@ -2285,7 +2277,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createBinaryExpression(left: Expression, operator: SyntaxKind, right: Expression, startsOnNewLine?: boolean): BinaryExpression { - let result = createSynthesizedNode(SyntaxKind.BinaryExpression, startsOnNewLine); + const result = createSynthesizedNode(SyntaxKind.BinaryExpression, startsOnNewLine); result.operatorToken = createSynthesizedNode(operator); result.left = left; result.right = right; @@ -2294,7 +2286,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createPropertyAccessExpression(expression: Expression, name: Identifier): PropertyAccessExpression { - let result = createSynthesizedNode(SyntaxKind.PropertyAccessExpression); + const result = createSynthesizedNode(SyntaxKind.PropertyAccessExpression); result.expression = parenthesizeForAccess(expression); result.dotToken = createSynthesizedNode(SyntaxKind.DotToken); result.name = name; @@ -2303,7 +2295,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createElementAccessExpression(expression: Expression, argumentExpression: Expression): ElementAccessExpression { - let result = createSynthesizedNode(SyntaxKind.ElementAccessExpression); + const result = createSynthesizedNode(SyntaxKind.ElementAccessExpression); result.expression = parenthesizeForAccess(expression); result.argumentExpression = argumentExpression; @@ -2331,7 +2323,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return expr; } - let node = createSynthesizedNode(SyntaxKind.ParenthesizedExpression); + const node = createSynthesizedNode(SyntaxKind.ParenthesizedExpression); node.expression = expr; return node; } @@ -2370,7 +2362,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Return true if identifier resolves to an exported member of a namespace function isNamespaceExportReference(node: Identifier) { - let container = resolver.getReferencedExportContainer(node); + const container = resolver.getReferencedExportContainer(node); return container && container.kind !== SyntaxKind.SourceFile; } @@ -2400,11 +2392,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function tryEmitConstantValue(node: PropertyAccessExpression | ElementAccessExpression): boolean { - let constantValue = tryGetConstEnumValue(node); + const constantValue = tryGetConstEnumValue(node); if (constantValue !== undefined) { write(constantValue.toString()); if (!compilerOptions.removeComments) { - let propertyName: string = node.kind === SyntaxKind.PropertyAccessExpression ? declarationNameToString((node).name) : getTextOfNode((node).argumentExpression); + const propertyName: string = node.kind === SyntaxKind.PropertyAccessExpression ? declarationNameToString((node).name) : getTextOfNode((node).argumentExpression); write(" /* " + propertyName + " */"); } return true; @@ -2426,10 +2418,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // If the code is not indented, an optional valueToWriteWhenNotIndenting will be // emitted instead. function indentIfOnDifferentLines(parent: Node, node1: Node, node2: Node, valueToWriteWhenNotIndenting?: string): boolean { - let realNodesAreOnDifferentLines = !nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); + const realNodesAreOnDifferentLines = !nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); // Always use a newline for synthesized code if the synthesizer desires it. - let synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2); + const synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2); if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) { increaseIndent(); @@ -2450,7 +2442,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } emit(node.expression); - let indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); + const indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); // 1 .toString is a valid property access, emit a space after the literal // Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal @@ -2458,12 +2450,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (!indentedBeforeDot) { if (node.expression.kind === SyntaxKind.NumericLiteral) { // check if numeric literal was originally written with a dot - let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression); + const text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression); shouldEmitSpace = text.indexOf(tokenToString(SyntaxKind.DotToken)) < 0; } else { // check if constant enum value is integer - let constantValue = tryGetConstEnumValue(node.expression); + const constantValue = tryGetConstEnumValue(node.expression); // isFinite handles cases when constantValue is undefined shouldEmitSpace = isFinite(constantValue) && Math.floor(constantValue) === constantValue; } @@ -2476,7 +2468,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("."); } - let indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); + const indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); emit(node.name); decreaseIndentIf(indentedBeforeDot, indentedAfterDot); } @@ -2492,7 +2484,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitEntityNameAsExpression(node.left, useFallback); } else if (useFallback) { - let temp = createAndRecordTempVariable(TempFlags.Auto); + const temp = createAndRecordTempVariable(TempFlags.Auto); write("("); emitNodeWithoutSourceMap(temp); write(" = "); @@ -2552,7 +2544,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emit(node); return node; } - let temp = createAndRecordTempVariable(TempFlags.Auto); + const temp = createAndRecordTempVariable(TempFlags.Auto); write("("); emit(temp); @@ -2564,7 +2556,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitCallWithSpread(node: CallExpression) { let target: Expression; - let expr = skipParentheses(node.expression); + const expr = skipParentheses(node.expression); if (expr.kind === SyntaxKind.PropertyAccessExpression) { // Target will be emitted as "this" argument target = emitCallTarget((expr).expression); @@ -2658,7 +2650,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi hasSpreadElement(node.arguments)) { write("("); - let target = emitCallTarget(node.expression); + const target = emitCallTarget(node.expression); write(".bind.apply("); emit(target); write(", [void 0].concat("); @@ -2790,7 +2782,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // expression a prefix increment whose operand is a plus expression - (++(+x)) // The same is true of minus of course. if (node.operand.kind === SyntaxKind.PrefixUnaryExpression) { - let operand = node.operand; + const operand = node.operand; if (node.operator === SyntaxKind.PlusToken && (operand.operator === SyntaxKind.PlusToken || operand.operator === SyntaxKind.PlusPlusToken)) { write(" "); } @@ -2869,7 +2861,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi * @param node a binary expression node containing exponentiationOperator (**, **=) */ function emitExponentiationOperator(node: BinaryExpression) { - let leftHandSideExpression = node.left; + const leftHandSideExpression = node.left; if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskEqualsToken) { let synthesizedLHS: ElementAccessExpression | PropertyAccessExpression; let shouldEmitParentheses = false; @@ -2879,12 +2871,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi synthesizedLHS = createSynthesizedNode(SyntaxKind.ElementAccessExpression, /*startsOnNewLine*/ false); - let identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false); + const identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldEmitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; if (leftHandSideExpression.argumentExpression.kind !== SyntaxKind.NumericLiteral && leftHandSideExpression.argumentExpression.kind !== SyntaxKind.StringLiteral) { - let tempArgumentExpression = createAndRecordTempVariable(TempFlags._i); + const tempArgumentExpression = createAndRecordTempVariable(TempFlags._i); (synthesizedLHS).argumentExpression = tempArgumentExpression; emitAssignment(tempArgumentExpression, leftHandSideExpression.argumentExpression, /*shouldEmitCommaBeforeAssignment*/ true); } @@ -2898,7 +2890,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write("("); synthesizedLHS = createSynthesizedNode(SyntaxKind.PropertyAccessExpression, /*startsOnNewLine*/ false); - let identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false); + const identifier = emitTempVariableAssignment(leftHandSideExpression.expression, /*canDefinedTempVariablesInPlaces*/ false, /*shouldemitCommaBeforeAssignment*/ false); synthesizedLHS.expression = identifier; (synthesizedLHS).dotToken = leftHandSideExpression.dotToken; @@ -2957,9 +2949,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // emitted as // 3 // + 2; - let indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== SyntaxKind.CommaToken ? " " : undefined); + const indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== SyntaxKind.CommaToken ? " " : undefined); write(tokenToString(node.operatorToken.kind)); - let indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, " "); + const indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, " "); emit(node.right); decreaseIndentIf(indentedBeforeOperator, indentedAfterOperator); } @@ -2976,14 +2968,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitConditionalExpression(node: ConditionalExpression) { emit(node.condition); - let indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, " "); + const indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, " "); write("?"); - let indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, " "); + const indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, " "); emit(node.whenTrue); decreaseIndentIf(indentedBeforeQuestion, indentedAfterQuestion); - let indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, " "); + const indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, " "); write(":"); - let indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, " "); + const indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, " "); emit(node.whenFalse); decreaseIndentIf(indentedBeforeColon, indentedAfterColon); } @@ -3003,7 +2995,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function isSingleLineEmptyBlock(node: Node) { if (node && node.kind === SyntaxKind.Block) { - let block = node; + const block = node; return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); } } @@ -3164,7 +3156,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitVariableDeclarationListSkippingUninitializedEntries(list: VariableDeclarationList): boolean { let started = false; - for (let decl of list.declarations) { + for (const decl of list.declarations) { if (!decl.initializer) { continue; } @@ -3442,8 +3434,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return; } - for (let labelText in table) { - let labelMarker = table[labelText]; + for (const labelText in table) { + const labelMarker = table[labelText]; writeLine(); write(`case "${labelMarker}": `); // if there are no outer converted loop or outer label in question is located inside outer converted loop @@ -3475,8 +3467,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(" "); endPos = emitToken(SyntaxKind.OpenParenToken, endPos); if (node.initializer && node.initializer.kind === SyntaxKind.VariableDeclarationList) { - let variableDeclarationList = node.initializer; - let startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); + const variableDeclarationList = node.initializer; + const startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); if (startIsEmitted) { emitCommaList(variableDeclarationList.declarations); } @@ -3515,7 +3507,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(" "); endPos = emitToken(SyntaxKind.OpenParenToken, endPos); if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { - let variableDeclarationList = node.initializer; + const variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length >= 1) { tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); emit(variableDeclarationList.declarations[0]); @@ -3580,10 +3572,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // // for (let v of arr) { } // - // we don't want to emit a temporary variable for the RHS, just use it directly. - let rhsIsIdentifier = node.expression.kind === SyntaxKind.Identifier; - let counter = createTempVariable(TempFlags._i); - let rhsReference = rhsIsIdentifier ? node.expression : createTempVariable(TempFlags.Auto); + // we can't reuse 'arr' because it might be modified within the body of the loop. + const counter = createTempVariable(TempFlags._i); + const rhsReference = createSynthesizedNode(SyntaxKind.Identifier) as Identifier; + rhsReference.text = node.expression.kind === SyntaxKind.Identifier ? + makeUniqueName((node.expression).text) : + makeTempVariableName(TempFlags.Auto); // This is the let keyword for the counter and rhsReference. The let keyword for // the LHS will be emitted inside the body. @@ -3595,15 +3589,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(" = 0"); emitEnd(node.expression); - if (!rhsIsIdentifier) { - // , _a = expr - write(", "); - emitStart(node.expression); - emitNodeWithoutSourceMap(rhsReference); - write(" = "); - emitNodeWithoutSourceMap(node.expression); - emitEnd(node.expression); - } + // , _a = expr + write(", "); + emitStart(node.expression); + emitNodeWithoutSourceMap(rhsReference); + write(" = "); + emitNodeWithoutSourceMap(node.expression); + emitEnd(node.expression); write("; "); @@ -3632,13 +3624,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Initialize LHS // let v = _a[_i]; - let rhsIterationValue = createElementAccessExpression(rhsReference, counter); + const rhsIterationValue = createElementAccessExpression(rhsReference, counter); emitStart(node.initializer); if (node.initializer.kind === SyntaxKind.VariableDeclarationList) { write("var "); - let variableDeclarationList = node.initializer; + const variableDeclarationList = node.initializer; if (variableDeclarationList.declarations.length > 0) { - let declaration = variableDeclarationList.declarations[0]; + const declaration = variableDeclarationList.declarations[0]; if (isBindingPattern(declaration.name)) { // This works whether the declaration is a var, let, or const. // It will use rhsIterationValue _a[_i] as the initializer. @@ -3663,7 +3655,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi else { // Initializer is an expression. Emit the expression in the body, so that it's // evaluated on every iteration. - let assignmentExpression = createBinaryExpression(node.initializer, SyntaxKind.EqualsToken, rhsIterationValue, /*startsOnNewLine*/ false); + const assignmentExpression = createBinaryExpression(node.initializer, SyntaxKind.EqualsToken, rhsIterationValue, /*startsOnNewLine*/ false); if (node.initializer.kind === SyntaxKind.ArrayLiteralExpression || node.initializer.kind === SyntaxKind.ObjectLiteralExpression) { // This is a destructuring pattern, so call emitDestructuring instead of emit. Calling emit will not work, because it will cause // the BinaryExpression to be passed in instead of the expression statement, which will cause emitDestructuring to crash. @@ -3843,7 +3835,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitCatchClause(node: CatchClause) { writeLine(); - let endPos = emitToken(SyntaxKind.CatchKeyword, node.pos); + const endPos = emitToken(SyntaxKind.CatchKeyword, node.pos); write(" "); emitToken(SyntaxKind.OpenParenToken, endPos); emit(node.variableDeclaration); @@ -3889,14 +3881,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitContainingModuleName(node: Node) { - let container = getContainingModule(node); + const container = getContainingModule(node); write(container ? getGeneratedNameForNode(container) : "exports"); } function emitModuleMemberName(node: Declaration) { emitStart(node.name); if (getCombinedNodeFlags(node) & NodeFlags.Export) { - let container = getContainingModule(node); + const container = getContainingModule(node); if (container) { write(getGeneratedNameForNode(container)); write("."); @@ -3910,9 +3902,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createVoidZero(): Expression { - let zero = createSynthesizedNode(SyntaxKind.NumericLiteral); + const zero = createSynthesizedNode(SyntaxKind.NumericLiteral); zero.text = "0"; - let result = createSynthesizedNode(SyntaxKind.VoidExpression); + const result = createSynthesizedNode(SyntaxKind.VoidExpression); result.expression = zero; return result; } @@ -3984,7 +3976,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } if (!exportEquals && exportSpecifiers && hasProperty(exportSpecifiers, name.text)) { - for (let specifier of exportSpecifiers[name.text]) { + for (const specifier of exportSpecifiers[name.text]) { writeLine(); emitStart(specifier.name); emitContainingModuleName(specifier); @@ -4027,7 +4019,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(", "); } - let exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); + const exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); if (exportChanged) { write(`${exportFunctionForFile}("`); @@ -4060,7 +4052,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi * @param shouldEmitCommaBeforeAssignment a boolean indicating whether an assignment should prefix with comma */ function emitTempVariableAssignment(expression: Expression, canDefineTempVariablesInPlace: boolean, shouldEmitCommaBeforeAssignment: boolean): Identifier { - let identifier = createTempVariable(TempFlags.Auto); + const identifier = createTempVariable(TempFlags.Auto); if (!canDefineTempVariablesInPlace) { recordTempDeclaration(identifier); } @@ -4077,8 +4069,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // because actual variable declarations are hoisted let canDefineTempVariablesInPlace = false; if (root.kind === SyntaxKind.VariableDeclaration) { - let isExported = getCombinedNodeFlags(root) & NodeFlags.Export; - let isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); + const isExported = getCombinedNodeFlags(root) & NodeFlags.Export; + const isSourceLevelForSystemModuleKind = shouldHoistDeclarationInSystemJsModule(root); canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; } else if (root.kind === SyntaxKind.Parameter) { @@ -4108,7 +4100,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return expr; } - let identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0); + const identifier = emitTempVariableAssignment(expr, canDefineTempVariablesInPlace, emitCount > 0); emitCount++; return identifier; } @@ -4118,7 +4110,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // we need to generate a temporary variable value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); // Return the expression 'value === void 0 ? defaultValue : value' - let equals = createSynthesizedNode(SyntaxKind.BinaryExpression); + const equals = createSynthesizedNode(SyntaxKind.BinaryExpression); equals.left = value; equals.operatorToken = createSynthesizedNode(SyntaxKind.EqualsEqualsEqualsToken); equals.right = createVoidZero(); @@ -4126,7 +4118,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createConditionalExpression(condition: Expression, whenTrue: Expression, whenFalse: Expression) { - let cond = createSynthesizedNode(SyntaxKind.ConditionalExpression); + const cond = createSynthesizedNode(SyntaxKind.ConditionalExpression); cond.condition = condition; cond.questionToken = createSynthesizedNode(SyntaxKind.QuestionToken); cond.whenTrue = whenTrue; @@ -4136,7 +4128,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createNumericLiteral(value: number) { - let node = createSynthesizedNode(SyntaxKind.NumericLiteral); + const node = createSynthesizedNode(SyntaxKind.NumericLiteral); node.text = "" + value; return node; } @@ -4144,7 +4136,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function createPropertyAccessForDestructuringProperty(object: Expression, propName: Identifier | LiteralExpression): Expression { // We create a synthetic copy of the identifier in order to avoid the rewriting that might // otherwise occur when the identifier is emitted. - let syntheticName = createSynthesizedNode(propName.kind); + const syntheticName = createSynthesizedNode(propName.kind); syntheticName.text = propName.text; if (syntheticName.kind !== SyntaxKind.Identifier) { return createElementAccessExpression(object, syntheticName); @@ -4153,8 +4145,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function createSliceCall(value: Expression, sliceIndex: number): CallExpression { - let call = createSynthesizedNode(SyntaxKind.CallExpression); - let sliceIdentifier = createSynthesizedNode(SyntaxKind.Identifier); + const call = createSynthesizedNode(SyntaxKind.CallExpression); + const sliceIdentifier = createSynthesizedNode(SyntaxKind.Identifier); sliceIdentifier.text = "slice"; call.expression = createPropertyAccessExpression(value, sliceIdentifier); call.arguments = >createSynthesizedNodeArray(); @@ -4163,30 +4155,30 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitObjectLiteralAssignment(target: ObjectLiteralExpression, value: Expression) { - let properties = target.properties; + const properties = target.properties; if (properties.length !== 1) { // For anything but a single element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); } - for (let p of properties) { + for (const p of properties) { if (p.kind === SyntaxKind.PropertyAssignment || p.kind === SyntaxKind.ShorthandPropertyAssignment) { - let propName = (p).name; - let target = p.kind === SyntaxKind.ShorthandPropertyAssignment ? p : (p).initializer || propName; + const propName = (p).name; + const target = p.kind === SyntaxKind.ShorthandPropertyAssignment ? p : (p).initializer || propName; emitDestructuringAssignment(target, createPropertyAccessForDestructuringProperty(value, propName)); } } } function emitArrayLiteralAssignment(target: ArrayLiteralExpression, value: Expression) { - let elements = target.elements; + const elements = target.elements; if (elements.length !== 1) { // For anything but a single element destructuring we need to generate a temporary // to ensure value is evaluated exactly once. value = ensureIdentifier(value, /*reuseIdentifierExpressions*/ true); } for (let i = 0; i < elements.length; i++) { - let e = elements[i]; + const e = elements[i]; if (e.kind !== SyntaxKind.OmittedExpression) { if (e.kind !== SyntaxKind.SpreadElementExpression) { emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); @@ -4222,7 +4214,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitAssignmentExpression(root: BinaryExpression) { - let target = root.left; + const target = root.left; let value = root.right; if (isEmptyObjectLiteralOrArrayLiteral(target)) { @@ -4268,10 +4260,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } for (let i = 0; i < numElements; i++) { - let element = elements[i]; + const element = elements[i]; if (pattern.kind === SyntaxKind.ObjectBindingPattern) { // Rewrite element to a declaration with an initializer that fetches property - let propName = element.propertyName || element.name; + const propName = element.propertyName || element.name; emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); } else if (element.kind !== SyntaxKind.OmittedExpression) { @@ -4312,7 +4304,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // for (...) { var = void 0; } // this is necessary to preserve ES6 semantic in scenarios like // for (...) { let x; console.log(x); x = 1 } // assignment on one iteration should not affect other iterations - let isLetDefinedInLoop = + const isLetDefinedInLoop = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.BlockScopedBindingInLoop) && (getCombinedFlagsForIdentifier(node.name) & NodeFlags.Let); @@ -4324,7 +4316,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } } - let exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.name); + const exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.name); if (exportChanged) { write(`${exportFunctionForFile}("`); @@ -4345,7 +4337,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (node.kind === SyntaxKind.OmittedExpression) { return; } - let name = node.name; + const name = node.name; if (name.kind === SyntaxKind.Identifier) { emitExportMemberAssignments(name); } @@ -4387,7 +4379,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(";"); } else { - let atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries(node.declarationList); + const atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries(node.declarationList); if (atLeastOneItem) { write(";"); } @@ -4411,7 +4403,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } // Otherwise, only emit if we have at least one initializer present. - for (let declaration of node.declarationList.declarations) { + for (const declaration of node.declarationList.declarations) { if (declaration.initializer) { return true; } @@ -4422,7 +4414,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitParameter(node: ParameterDeclaration) { if (languageVersion < ScriptTarget.ES6) { if (isBindingPattern(node.name)) { - let name = createTempVariable(TempFlags.Auto); + const name = createTempVariable(TempFlags.Auto); if (!tempParameters) { tempParameters = []; } @@ -4452,12 +4444,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return; } - let { name: paramName, initializer } = parameter; + const { name: paramName, initializer } = parameter; if (isBindingPattern(paramName)) { // In cases where a binding pattern is simply '[]' or '{}', // we usually don't want to emit a var declaration; however, in the presence // of an initializer, we must emit that expression to preserve side effects. - let hasBindingElements = paramName.elements.length > 0; + const hasBindingElements = paramName.elements.length > 0; if (hasBindingElements || initializer) { writeLine(); write("var "); @@ -4496,15 +4488,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitRestParameter(node: FunctionLikeDeclaration) { if (languageVersion < ScriptTarget.ES6 && hasRestParameter(node)) { - let restIndex = node.parameters.length - 1; - let restParam = node.parameters[restIndex]; + const restIndex = node.parameters.length - 1; + const restParam = node.parameters[restIndex]; // A rest parameter cannot have a binding pattern, so let's just ignore it if it does. if (isBindingPattern(restParam.name)) { return; } - let tempName = createTempVariable(TempFlags._i).text; + const tempName = createTempVariable(TempFlags._i).text; writeLine(); emitLeadingComments(restParam); emitStart(restParam); @@ -4641,8 +4633,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi increaseIndent(); write("("); if (node) { - let parameters = node.parameters; - let omitCount = languageVersion < ScriptTarget.ES6 && hasRestParameter(node) ? 1 : 0; + const parameters = node.parameters; + const omitCount = languageVersion < ScriptTarget.ES6 && hasRestParameter(node) ? 1 : 0; emitList(parameters, 0, parameters.length - omitCount, /*multiLine*/ false, /*trailingComma*/ false); } write(")"); @@ -4660,10 +4652,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitAsyncFunctionBodyForES6(node: FunctionLikeDeclaration) { - let promiseConstructor = getEntityNameFromTypeNode(node.type); - let isArrowFunction = node.kind === SyntaxKind.ArrowFunction; - let hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0; - let args: string; + const promiseConstructor = getEntityNameFromTypeNode(node.type); + const isArrowFunction = node.kind === SyntaxKind.ArrowFunction; + const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0; // An async function is emit as an outer function that calls an inner // generator function. To preserve lexical bindings, we pass the current @@ -4801,9 +4792,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitSignatureAndBody(node: FunctionLikeDeclaration) { const saveConvertedLoopState = convertedLoopState; - let saveTempFlags = tempFlags; - let saveTempVariables = tempVariables; - let saveTempParameters = tempParameters; + const saveTempFlags = tempFlags; + const saveTempVariables = tempVariables; + const saveTempParameters = tempParameters; convertedLoopState = undefined; tempFlags = 0; @@ -4819,7 +4810,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitSignatureParameters(node); } - let isAsync = isAsyncFunctionLike(node); + const isAsync = isAsyncFunctionLike(node); if (isAsync && languageVersion === ScriptTarget.ES6) { emitAsyncFunctionBodyForES6(node); } @@ -4872,10 +4863,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi scopeEmitStart(node); increaseIndent(); - let outPos = writer.getTextPos(); - emitDetachedComments(node.body); + const outPos = writer.getTextPos(); + emitDetachedCommentsAndUpdateCommentsInfo(node.body); emitFunctionBodyPreamble(node); - let preambleEmitted = writer.getTextPos() !== outPos; + const preambleEmitted = writer.getTextPos() !== outPos; decreaseIndent(); // If we didn't have to emit any preamble code, then attempt to keep the arrow @@ -4915,21 +4906,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(" {"); scopeEmitStart(node); - let initialTextPos = writer.getTextPos(); + const initialTextPos = writer.getTextPos(); increaseIndent(); - emitDetachedComments(body.statements); + emitDetachedCommentsAndUpdateCommentsInfo(body.statements); // Emit all the directive prologues (like "use strict"). These have to come before // any other preamble code we write (like parameter initializers). - let startIndex = emitDirectivePrologues(body.statements, /*startWithNewLine*/ true); + const startIndex = emitDirectivePrologues(body.statements, /*startWithNewLine*/ true); emitFunctionBodyPreamble(node); decreaseIndent(); - let preambleEmitted = writer.getTextPos() !== initialTextPos; + const preambleEmitted = writer.getTextPos() !== initialTextPos; if (!preambleEmitted && nodeEndIsOnSameLineAsNodeStart(body, body)) { - for (let statement of body.statements) { + for (const statement of body.statements) { write(" "); emit(statement); } @@ -4953,11 +4944,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function findInitialSuperCall(ctor: ConstructorDeclaration): ExpressionStatement { if (ctor.body) { - let statement = (ctor.body).statements[0]; + const statement = (ctor.body).statements[0]; if (statement && statement.kind === SyntaxKind.ExpressionStatement) { - let expr = (statement).expression; + const expr = (statement).expression; if (expr && expr.kind === SyntaxKind.CallExpression) { - let func = (expr).expression; + const func = (expr).expression; if (func && func.kind === SyntaxKind.SuperKeyword) { return statement; } @@ -5002,8 +4993,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function getInitializedProperties(node: ClassLikeDeclaration, isStatic: boolean) { - let properties: PropertyDeclaration[] = []; - for (let member of node.members) { + const properties: PropertyDeclaration[] = []; + for (const member of node.members) { if (member.kind === SyntaxKind.PropertyDeclaration && isStatic === ((member.flags & NodeFlags.Static) !== 0) && (member).initializer) { properties.push(member); } @@ -5013,7 +5004,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitPropertyDeclarations(node: ClassLikeDeclaration, properties: PropertyDeclaration[]) { - for (let property of properties) { + for (const property of properties) { emitPropertyDeclaration(node, property); } } @@ -5071,7 +5062,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitTrailingComments(member); } else if (member.kind === SyntaxKind.GetAccessor || member.kind === SyntaxKind.SetAccessor) { - let accessors = getAllAccessorDeclarations(node.members, member); + const accessors = getAllAccessorDeclarations(node.members, member); if (member === accessors.firstAccessor) { writeLine(); emitStart(member); @@ -5119,7 +5110,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitMemberFunctionsForES6AndHigher(node: ClassLikeDeclaration) { - for (let member of node.members) { + for (const member of node.members) { if ((member.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature) && !(member).body) { emitCommentsOnNotEmittedNode(member); } @@ -5156,9 +5147,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitConstructor(node: ClassLikeDeclaration, baseTypeElement: ExpressionWithTypeArguments) { const saveConvertedLoopState = convertedLoopState; - let saveTempFlags = tempFlags; - let saveTempVariables = tempVariables; - let saveTempParameters = tempParameters; + const saveTempFlags = tempFlags; + const saveTempVariables = tempVariables; + const saveTempParameters = tempParameters; convertedLoopState = undefined; tempFlags = 0; @@ -5192,7 +5183,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } }); - let ctor = getFirstConstructorWithBody(node); + const ctor = getFirstConstructorWithBody(node); // For target ES6 and above, if there is no user-defined constructor and there is no property assignment // do not emit constructor in class declaration. @@ -5240,7 +5231,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Emit all the directive prologues (like "use strict"). These have to come before // any other preamble code we write (like parameter initializers). startIndex = emitDirectivePrologues(ctor.body.statements, /*startWithNewLine*/ true); - emitDetachedComments(ctor.body.statements); + emitDetachedCommentsAndUpdateCommentsInfo(ctor.body.statements); } emitCaptureThisForNodeIfNecessary(node); let superCall: ExpressionStatement; @@ -5312,7 +5303,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitClassLikeDeclarationForES6AndHigher(node: ClassLikeDeclaration) { - let thisNodeIsDecorated = nodeIsDecorated(node); + const thisNodeIsDecorated = nodeIsDecorated(node); if (node.kind === SyntaxKind.ClassDeclaration) { if (thisNodeIsDecorated) { // To preserve the correct runtime semantics when decorators are applied to the class, @@ -5391,8 +5382,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // // This keeps the expression as an expression, while ensuring that the static parts // of it have been initialized by the time it is used. - let staticProperties = getInitializedProperties(node, /*static:*/ true); - let isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === SyntaxKind.ClassExpression; + const staticProperties = getInitializedProperties(node, /*static:*/ true); + const isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === SyntaxKind.ClassExpression; let tempVariable: Identifier; if (isClassExpressionWithStaticProperties) { @@ -5413,7 +5404,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitDeclarationName(node); } - let baseTypeNode = getClassExtendsHeritageClauseElement(node); + const baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { write(" extends "); emit(baseTypeNode.expression); @@ -5498,16 +5489,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } write("(function ("); - let baseTypeNode = getClassExtendsHeritageClauseElement(node); + const baseTypeNode = getClassExtendsHeritageClauseElement(node); if (baseTypeNode) { write("_super"); } write(") {"); - let saveTempFlags = tempFlags; - let saveTempVariables = tempVariables; - let saveTempParameters = tempParameters; - let saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames; - let saveConvertedLoopState = convertedLoopState; + const saveTempFlags = tempFlags; + const saveTempVariables = tempVariables; + const saveTempParameters = tempParameters; + const saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames; + const saveConvertedLoopState = convertedLoopState; convertedLoopState = undefined; tempFlags = 0; @@ -5579,9 +5570,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitDecoratorsOfConstructor(node: ClassLikeDeclaration) { - let decorators = node.decorators; - let constructor = getFirstConstructorWithBody(node); - let hasDecoratedParameters = constructor && forEach(constructor.parameters, nodeIsDecorated); + const decorators = node.decorators; + const constructor = getFirstConstructorWithBody(node); + const hasDecoratedParameters = constructor && forEach(constructor.parameters, nodeIsDecorated); // skip decoration of the constructor if neither it nor its parameters are decorated if (!decorators && !hasDecoratedParameters) { @@ -5606,7 +5597,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi increaseIndent(); writeLine(); - let decoratorCount = decorators ? decorators.length : 0; + const decoratorCount = decorators ? decorators.length : 0; let argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, decorator => { emitStart(decorator); emit(decorator.expression); @@ -5626,7 +5617,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitDecoratorsOfMembers(node: ClassLikeDeclaration, staticFlag: NodeFlags) { - for (let member of node.members) { + for (const member of node.members) { // only emit members in the correct group if ((member.flags & NodeFlags.Static) !== staticFlag) { continue; @@ -5646,7 +5637,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let decorators: NodeArray; let functionLikeMember: FunctionLikeDeclaration; if (isAccessor(member)) { - let accessors = getAllAccessorDeclarations(node.members, member); + const accessors = getAllAccessorDeclarations(node.members, member); if (member !== accessors.firstAccessor) { continue; } @@ -5706,7 +5697,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi increaseIndent(); writeLine(); - let decoratorCount = decorators ? decorators.length : 0; + const decoratorCount = decorators ? decorators.length : 0; let argumentsWritten = emitList(decorators, 0, decoratorCount, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ false, /*noTrailingNewLine*/ true, decorator => { emitStart(decorator); emit(decorator.expression); @@ -5748,9 +5739,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi let argumentsWritten = 0; if (node) { let parameterIndex = 0; - for (let parameter of node.parameters) { + for (const parameter of node.parameters) { if (nodeIsDecorated(parameter)) { - let decorators = parameter.decorators; + const decorators = parameter.decorators; argumentsWritten += emitList(decorators, 0, decorators.length, /*multiLine*/ true, /*trailingComma*/ false, /*leadingComma*/ leadingComma, /*noTrailingNewLine*/ true, decorator => { emitStart(decorator); write(`__param(${parameterIndex}, `); @@ -5915,10 +5906,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } // Clone the type name and parent it to a location outside of the current declaration. - let typeName = cloneEntityName(node.typeName); + const typeName = cloneEntityName(node.typeName); typeName.parent = location; - let result = resolver.getTypeReferenceSerializationKind(typeName); + const result = resolver.getTypeReferenceSerializationKind(typeName); switch (result) { case TypeReferenceSerializationKind.Unknown: let temp = createAndRecordTempVariable(TempFlags.Auto); @@ -6080,7 +6071,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function shouldEmitEnumDeclaration(node: EnumDeclaration) { - let isConstEnum = isConst(node); + const isConstEnum = isConst(node); return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.isolatedModules; } @@ -6149,7 +6140,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitEnumMember(node: EnumMember) { - let enumParent = node.parent; + const enumParent = node.parent; emitStart(node); write(getGeneratedNameForNode(enumParent)); write("["); @@ -6165,7 +6156,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function writeEnumMemberDeclarationValue(member: EnumMember) { - let value = resolver.getConstantValue(member); + const value = resolver.getConstantValue(member); if (value !== undefined) { write(value.toString()); return; @@ -6180,7 +6171,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration: ModuleDeclaration): ModuleDeclaration { if (moduleDeclaration.body.kind === SyntaxKind.ModuleDeclaration) { - let recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); + const recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); return recursiveInnerModule || moduleDeclaration.body; } } @@ -6195,13 +6186,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitModuleDeclaration(node: ModuleDeclaration) { // Emit only if this module is non-ambient. - let shouldEmit = shouldEmitModuleDeclaration(node); + const shouldEmit = shouldEmitModuleDeclaration(node); if (!shouldEmit) { return emitCommentsOnNotEmittedNode(node); } - let hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); - let emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); + const hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node); + const emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); if (emitVarForModule) { emitStart(node); @@ -6223,8 +6214,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(") "); if (node.body.kind === SyntaxKind.ModuleBlock) { const saveConvertedLoopState = convertedLoopState; - let saveTempFlags = tempFlags; - let saveTempVariables = tempVariables; + const saveTempFlags = tempFlags; + const saveTempVariables = tempVariables; convertedLoopState = undefined; tempFlags = 0; tempVariables = undefined; @@ -6246,7 +6237,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emit(node.body); decreaseIndent(); writeLine(); - let moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; + const moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; emitToken(SyntaxKind.CloseBraceToken, moduleBlock.statements.end); scopeEmitEnd(); } @@ -6288,7 +6279,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitRequire(moduleName: Expression) { if (moduleName.kind === SyntaxKind.StringLiteral) { write("require("); - let text = tryRenameExternalModule(moduleName); + const text = tryRenameExternalModule(moduleName); if (text) { write(text); } @@ -6308,7 +6299,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (node.kind === SyntaxKind.ImportEqualsDeclaration) { return node; } - let importClause = (node).importClause; + const importClause = (node).importClause; if (importClause && importClause.namedBindings && importClause.namedBindings.kind === SyntaxKind.NamespaceImport) { return importClause.namedBindings; } @@ -6332,8 +6323,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // ES6 import if (node.importClause) { - let shouldEmitDefaultBindings = resolver.isReferencedAliasDeclaration(node.importClause); - let shouldEmitNamedBindings = node.importClause.namedBindings && resolver.isReferencedAliasDeclaration(node.importClause.namedBindings, /* checkChildren */ true); + const shouldEmitDefaultBindings = resolver.isReferencedAliasDeclaration(node.importClause); + const shouldEmitNamedBindings = node.importClause.namedBindings && resolver.isReferencedAliasDeclaration(node.importClause.namedBindings, /* checkChildren */ true); if (shouldEmitDefaultBindings || shouldEmitNamedBindings) { write("import "); emitStart(node.importClause); @@ -6374,8 +6365,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function emitExternalImportDeclaration(node: ImportDeclaration | ImportEqualsDeclaration) { if (contains(externalImports, node)) { - let isExportedImport = node.kind === SyntaxKind.ImportEqualsDeclaration && (node.flags & NodeFlags.Export) !== 0; - let namespaceDeclaration = getNamespaceDeclarationNode(node); + const isExportedImport = node.kind === SyntaxKind.ImportEqualsDeclaration && (node.flags & NodeFlags.Export) !== 0; + const namespaceDeclaration = getNamespaceDeclarationNode(node); if (modulekind !== ModuleKind.AMD) { emitLeadingComments(node); @@ -6393,7 +6384,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // import { x, y } from "foo" // import d, * as x from "foo" // import d, { x, y } from "foo" - let isNakedImport = SyntaxKind.ImportDeclaration && !(node).importClause; + const isNakedImport = SyntaxKind.ImportDeclaration && !(node).importClause; if (!isNakedImport) { write("var "); write(getGeneratedNameForNode(node)); @@ -6448,11 +6439,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // variable declaration for import-equals declaration can be hoisted in system modules // in this case 'var' should be omitted and emit should contain only initialization - let variableDeclarationIsHoisted = shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ true); + const variableDeclarationIsHoisted = shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ true); // is it top level export import v = a.b.c in system module? // if yes - it needs to be rewritten as exporter('v', v = a.b.c) - let isExported = isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ true); + const isExported = isSourceFileLevelDeclarationInSystemJsModule(node, /*isExported*/ true); if (!variableDeclarationIsHoisted) { Debug.assert(!isExported); @@ -6494,7 +6485,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (modulekind !== ModuleKind.ES6) { if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) { emitStart(node); - let generatedName = getGeneratedNameForNode(node); + const generatedName = getGeneratedNameForNode(node); if (node.exportClause) { // export { x, y, ... } from "foo" if (modulekind !== ModuleKind.AMD) { @@ -6504,7 +6495,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitRequire(getExternalModuleName(node)); write(";"); } - for (let specifier of node.exportClause.elements) { + for (const specifier of node.exportClause.elements) { if (resolver.isValueAliasDeclaration(specifier)) { writeLine(); emitStart(specifier); @@ -6560,7 +6551,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi Debug.assert(modulekind === ModuleKind.ES6); let needsComma = false; - for (let specifier of specifiers) { + for (const specifier of specifiers) { if (shouldEmit(specifier)) { if (needsComma) { write(", "); @@ -6581,7 +6572,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi writeLine(); emitStart(node); write("export default "); - let expression = node.expression; + const expression = node.expression; emit(expression); if (expression.kind !== SyntaxKind.FunctionDeclaration && expression.kind !== SyntaxKind.ClassDeclaration) { @@ -6619,7 +6610,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi exportSpecifiers = {}; exportEquals = undefined; hasExportStars = false; - for (let node of sourceFile.statements) { + for (const node of sourceFile.statements) { switch (node.kind) { case SyntaxKind.ImportDeclaration: if (!(node).importClause || @@ -6651,8 +6642,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } else { // export { x, y } - for (let specifier of (node).exportClause.elements) { - let name = (specifier.propertyName || specifier.name).text; + for (const specifier of (node).exportClause.elements) { + const name = (specifier.propertyName || specifier.name).text; (exportSpecifiers[name] || (exportSpecifiers[name] = [])).push(specifier); } } @@ -6681,7 +6672,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function getLocalNameForExternalImport(node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration): string { - let namespaceDeclaration = getNamespaceDeclarationNode(node); + const namespaceDeclaration = getNamespaceDeclarationNode(node); if (namespaceDeclaration && !isDefaultImport(node)) { return getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); } @@ -6694,7 +6685,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function getExternalModuleNameText(importNode: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration): string { - let moduleName = getExternalModuleName(importNode); + const moduleName = getExternalModuleName(importNode); if (moduleName.kind === SyntaxKind.StringLiteral) { return tryRenameExternalModule(moduleName) || getLiteralText(moduleName); } @@ -6709,9 +6700,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi writeLine(); let started = false; - for (let importNode of externalImports) { + for (const importNode of externalImports) { // do not create variable declaration for exports and imports that lack import clause - let skipNode = + const skipNode = importNode.kind === SyntaxKind.ExportDeclaration || (importNode.kind === SyntaxKind.ImportDeclaration && !(importNode).importClause); @@ -6750,7 +6741,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // no exported declarations (export var ...) or export specifiers (export {x}) // check if we have any non star export declarations. let hasExportDeclarationWithExportClause = false; - for (let externalImport of externalImports) { + for (const externalImport of externalImports) { if (externalImport.kind === SyntaxKind.ExportDeclaration && (externalImport).exportClause) { hasExportDeclarationWithExportClause = true; break; @@ -6778,26 +6769,26 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } if (exportSpecifiers) { - for (let n in exportSpecifiers) { - for (let specifier of exportSpecifiers[n]) { + for (const n in exportSpecifiers) { + for (const specifier of exportSpecifiers[n]) { // write name of export specified, i.e. 'export {x}' writeExportedName(specifier.name); } } } - for (let externalImport of externalImports) { + for (const externalImport of externalImports) { if (externalImport.kind !== SyntaxKind.ExportDeclaration) { continue; } - let exportDecl = externalImport; + const exportDecl = externalImport; if (!exportDecl.exportClause) { // export * from ... continue; } - for (let element of exportDecl.exportClause.elements) { + for (const element of exportDecl.exportClause.elements) { // write name of indirectly exported entry, i.e. 'export {x} from ...' writeExportedName(element.name || element.propertyName); } @@ -6886,16 +6877,16 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (hoistedVars) { writeLine(); write("var "); - let seen: Map = {}; + const seen: Map = {}; for (let i = 0; i < hoistedVars.length; ++i) { - let local = hoistedVars[i]; - let name = local.kind === SyntaxKind.Identifier + const local = hoistedVars[i]; + const name = local.kind === SyntaxKind.Identifier ? local : (local).name; if (name) { // do not emit duplicate entries (in case of declaration merging) in the list of hoisted variables - let text = unescapeIdentifier(name.text); + const text = unescapeIdentifier(name.text); if (hasProperty(seen, text)) { continue; } @@ -6915,7 +6906,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emit(local); } - let flags = getCombinedNodeFlags(local.kind === SyntaxKind.Identifier ? local.parent : local); + const flags = getCombinedNodeFlags(local.kind === SyntaxKind.Identifier ? local.parent : local); if (flags & NodeFlags.Export) { if (!exportedDeclarations) { exportedDeclarations = []; @@ -6927,7 +6918,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } if (hoistedFunctionDeclarations) { - for (let f of hoistedFunctionDeclarations) { + for (const f of hoistedFunctionDeclarations) { writeLine(); emit(f); @@ -6990,7 +6981,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement) { if (shouldHoistVariable(node, /*checkIfSourceFileLevelDecl*/ false)) { - let name = (node).name; + const name = (node).name; if (name.kind === SyntaxKind.Identifier) { if (!hoistedVars) { hoistedVars = []; @@ -7081,8 +7072,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // } emitVariableDeclarationsForImports(); writeLine(); - let exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node); - let exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations); + const exportedDeclarations = processTopLevelVariableAndFunctionDeclarations(node); + const exportStarFunction = emitLocalStorageForExportedNamesIfNecessary(exportedDeclarations); writeLine(); write("return {"); increaseIndent(); @@ -7107,15 +7098,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi writeLine(); increaseIndent(); - let group = dependencyGroups[i]; + const group = dependencyGroups[i]; // derive a unique name for parameter from the first named entry in the group - let parameterName = makeUniqueName(forEach(group, getLocalNameForExternalImport) || ""); + const parameterName = makeUniqueName(forEach(group, getLocalNameForExternalImport) || ""); write(`function (${parameterName}) {`); increaseIndent(); - for (let entry of group) { - let importVariableName = getLocalNameForExternalImport(entry) || ""; + for (const entry of group) { + const importVariableName = getLocalNameForExternalImport(entry) || ""; switch (entry.kind) { case SyntaxKind.ImportDeclaration: @@ -7153,7 +7144,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi writeLine(); } - let e = (entry).exportClause.elements[i]; + const e = (entry).exportClause.elements[i]; write(`"`); emitNodeWithCommentsAndWithoutSourcemap(e.name); write(`": ${parameterName}["`); @@ -7191,7 +7182,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi increaseIndent(); writeLine(); for (let i = startIndex; i < node.statements.length; ++i) { - let statement = node.statements[i]; + const statement = node.statements[i]; switch (statement.kind) { // - function declarations are not emitted because they were already hoisted // - import declarations are not emitted since they are already handled in setters @@ -7202,7 +7193,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi continue; case SyntaxKind.ExportDeclaration: if (!(statement).moduleSpecifier) { - for (let element of (statement).exportClause.elements) { + for (const element of (statement).exportClause.elements) { // write call to exporter function for every export specifier in exports list emitExportSpecifierInSystemModule(element); } @@ -7244,14 +7235,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } write("["); - let groupIndices: Map = {}; - let dependencyGroups: DependencyGroup[] = []; + const groupIndices: Map = {}; + const dependencyGroups: DependencyGroup[] = []; for (let i = 0; i < externalImports.length; ++i) { - let text = getExternalModuleNameText(externalImports[i]); + const text = getExternalModuleNameText(externalImports[i]); if (hasProperty(groupIndices, text)) { // deduplicate/group entries in dependency list by the dependency name - let groupIndex = groupIndices[text]; + const groupIndex = groupIndices[text]; dependencyGroups[groupIndex].push(externalImports[i]); continue; } @@ -7269,7 +7260,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi write(`], function(${exportFunctionForFile}) {`); writeLine(); increaseIndent(); - let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitSystemModuleBody(node, dependencyGroups, startIndex); @@ -7286,15 +7277,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function getAMDDependencyNames(node: SourceFile, includeNonAmdDependencies: boolean): AMDDependencyNames { // names of modules with corresponding parameter in the factory function - let aliasedModuleNames: string[] = []; + const aliasedModuleNames: string[] = []; // names of modules with no corresponding parameters in factory function - let unaliasedModuleNames: string[] = []; - let importAliasNames: string[] = []; // names of the parameters in the factory function; these + const unaliasedModuleNames: string[] = []; + const importAliasNames: string[] = []; // names of the parameters in the factory function; these // parameters need to match the indexes of the corresponding // module names in aliasedModuleNames. // Fill in amd-dependency tags - for (let amdDependency of node.amdDependencies) { + for (const amdDependency of node.amdDependencies) { if (amdDependency.name) { aliasedModuleNames.push("\"" + amdDependency.path + "\""); importAliasNames.push(amdDependency.name); @@ -7304,12 +7295,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } } - for (let importNode of externalImports) { + for (const importNode of externalImports) { // Find the name of the external module - let externalModuleName = getExternalModuleNameText(importNode); + const externalModuleName = getExternalModuleNameText(importNode); // Find the name of the module alias, if there is one - let importAliasName = getLocalNameForExternalImport(importNode); + const importAliasName = getLocalNameForExternalImport(importNode); if (includeNonAmdDependencies && importAliasName) { aliasedModuleNames.push(externalModuleName); importAliasNames.push(importAliasName); @@ -7335,7 +7326,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // `import "module"` or `` // we need to add modules without alias names to the end of the dependencies list - let dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies); + const dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies); emitAMDDependencyList(dependencyNames); write(", "); emitAMDFactoryHeader(dependencyNames); @@ -7374,7 +7365,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } emitAMDDependencies(node, /*includeNonAmdDependencies*/ true); increaseIndent(); - let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -7386,7 +7377,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function emitCommonJSModule(node: SourceFile) { - let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); emitEmitHelpers(node); collectExternalModuleInfo(node); emitExportStarHelper(); @@ -7400,7 +7391,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitEmitHelpers(node); collectExternalModuleInfo(node); - let dependencyNames = getAMDDependencyNames(node, /*includeNonAmdDependencies*/ false); + const dependencyNames = getAMDDependencyNames(node, /*includeNonAmdDependencies*/ false); // Module is detected first to support Browserify users that load into a browser with an AMD loader writeLines(`(function (factory) { @@ -7415,7 +7406,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi })(`); emitAMDFactoryHeader(dependencyNames); increaseIndent(); - let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); + const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true); emitExportStarHelper(); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -7431,7 +7422,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi exportSpecifiers = undefined; exportEquals = undefined; hasExportStars = false; - let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); emitEmitHelpers(node); emitCaptureThisForNodeIfNecessary(node); emitLinesStartingAt(node.statements, startIndex); @@ -7466,7 +7457,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function trimReactWhitespaceAndApplyEntities(node: JsxText): string { let result: string = undefined; - let text = getTextOfNode(node, /*includeTrivia*/ true); + const text = getTextOfNode(node, /*includeTrivia*/ true); let firstNonWhitespace = 0; let lastNonWhitespace = -1; @@ -7474,10 +7465,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // start/end of a tag is considered a start/end of a line only if that line is // on the same line as the closing tag. See examples in tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx for (let i = 0; i < text.length; i++) { - let c = text.charCodeAt(i); + const c = text.charCodeAt(i); if (isLineBreak(c)) { if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) { - let part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); + const part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1); result = (result ? result + "\" + ' ' + \"" : "") + escapeString(part); } firstNonWhitespace = -1; @@ -7491,7 +7482,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } if (firstNonWhitespace !== -1) { - let part = text.substr(firstNonWhitespace); + const part = text.substr(firstNonWhitespace); result = (result ? result + "\" + ' ' + \"" : "") + escapeString(part); } @@ -7574,9 +7565,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } function writeLines(text: string): void { - let lines = text.split(/\r\n|\r|\n/g); + const lines = text.split(/\r\n|\r|\n/g); for (let i = 0; i < lines.length; ++i) { - let line = lines[i]; + const line = lines[i]; if (line.length) { writeLine(); write(line); @@ -7618,15 +7609,15 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi // Start new file on new line writeLine(); emitShebang(); - emitDetachedComments(node); + emitDetachedCommentsAndUpdateCommentsInfo(node); if (isExternalModule(node) || compilerOptions.isolatedModules) { - let emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ModuleKind.CommonJS]; + const emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ModuleKind.CommonJS]; emitModule(node); } else { // emit prologue directives prior to __extends - let startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); + const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ false); externalImports = undefined; exportSpecifiers = undefined; exportEquals = undefined; @@ -7655,7 +7646,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return emitNodeWithoutSourceMap(node); } - let emitComments = shouldEmitLeadingAndTrailingComments(node); + const emitComments = shouldEmitLeadingAndTrailingComments(node); if (emitComments) { emitLeadingComments(node); } @@ -7902,7 +7893,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi function getLeadingCommentsWithoutDetachedComments() { // get the leading comments from detachedPos - let leadingComments = getLeadingCommentRanges(currentSourceFile.text, + const leadingComments = getLeadingCommentRanges(currentSourceFile.text, lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); @@ -7914,11 +7905,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return leadingComments; } - function isPinnedComments(comment: CommentRange) { - return currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk && - currentSourceFile.text.charCodeAt(comment.pos + 2) === CharacterCodes.exclamation; - } - /** * Determine if the given comment is a triple-slash * @@ -7930,7 +7916,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.slash && comment.pos + 2 < comment.end && currentSourceFile.text.charCodeAt(comment.pos + 2) === CharacterCodes.slash) { - let textSubStr = currentSourceFile.text.substring(comment.pos, comment.end); + const textSubStr = currentSourceFile.text.substring(comment.pos, comment.end); return textSubStr.match(fullTripleSlashReferencePathRegEx) || textSubStr.match(fullTripleSlashAMDReferencePathRegEx) ? true : false; @@ -8009,7 +7995,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi } // Emit the trailing comments only if the parent's end doesn't match - let trailingComments = getTrailingCommentsToEmit(node); + const trailingComments = getTrailingCommentsToEmit(node); // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment); @@ -8025,7 +8011,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return; } - let trailingComments = getTrailingCommentRanges(currentSourceFile.text, pos); + const trailingComments = getTrailingCommentRanges(currentSourceFile.text, pos); // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment); @@ -8052,68 +8038,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment); } - function emitDetachedComments(node: TextRange) { - let leadingComments: CommentRange[]; - if (compilerOptions.removeComments) { - // removeComments is true, only reserve pinned comment at the top of file - // For example: - // /*! Pinned Comment */ - // - // var x = 10; - if (node.pos === 0) { - leadingComments = filter(getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComments); + function emitDetachedCommentsAndUpdateCommentsInfo(node: TextRange) { + const currentDetachedCommentInfo = emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments); + + if (currentDetachedCommentInfo) { + if (detachedCommentsInfo) { + detachedCommentsInfo.push(currentDetachedCommentInfo); } - } - else { - // removeComments is false, just get detached as normal and bypass the process to filter comment - leadingComments = getLeadingCommentRanges(currentSourceFile.text, node.pos); - } - - if (leadingComments) { - let detachedComments: CommentRange[] = []; - let lastComment: CommentRange; - - forEach(leadingComments, comment => { - if (lastComment) { - let lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); - let commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); - - if (commentLine >= lastCommentLine + 2) { - // There was a blank line between the last comment and this comment. This - // comment is not part of the copyright comments. Return what we have so - // far. - return detachedComments; - } - } - - detachedComments.push(comment); - lastComment = comment; - }); - - if (detachedComments.length) { - // All comments look like they could have been part of the copyright header. Make - // sure there is at least one blank line between it and the node. If not, it's not - // a copyright header. - let lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastOrUndefined(detachedComments).end); - let nodeLine = getLineOfLocalPosition(currentSourceFile, skipTrivia(currentSourceFile.text, node.pos)); - if (nodeLine >= lastCommentLine + 2) { - // Valid detachedComments - emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); - let currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: lastOrUndefined(detachedComments).end }; - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } + else { + detachedCommentsInfo = [currentDetachedCommentInfo]; } } } function emitShebang() { - let shebang = getShebang(currentSourceFile.text); + const shebang = getShebang(currentSourceFile.text); if (shebang) { write(shebang); } diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 01fd0c20963..4a8d97a3dfb 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -2,7 +2,7 @@ /// namespace ts { - let nodeConstructors = new Array Node>(SyntaxKind.Count); + const nodeConstructors = new Array Node>(SyntaxKind.Count); /* @internal */ export let parseTime = 0; export function getNodeConstructor(kind: SyntaxKind): new (pos?: number, end?: number) => Node { @@ -27,8 +27,8 @@ namespace ts { function visitEachNode(cbNode: (node: Node) => T, nodes: Node[]) { if (nodes) { - for (let node of nodes) { - let result = cbNode(node); + for (const node of nodes) { + const result = cbNode(node); if (result) { return result; } @@ -47,8 +47,8 @@ namespace ts { // The visitXXX functions could be written as local functions that close over the cbNode and cbNodeArray // callback parameters, but that causes a closure allocation for each invocation with noticeable effects // on performance. - let visitNodes: (cb: (node: Node | Node[]) => T, nodes: Node[]) => T = cbNodeArray ? visitNodeArray : visitEachNode; - let cbNodes = cbNodeArray || cbNode; + const visitNodes: (cb: (node: Node | Node[]) => T, nodes: Node[]) => T = cbNodeArray ? visitNodeArray : visitEachNode; + const cbNodes = cbNodeArray || cbNode; switch (node.kind) { case SyntaxKind.QualifiedName: return visitNode(cbNode, (node).left) || @@ -397,8 +397,8 @@ namespace ts { } export function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes = false): SourceFile { - let start = new Date().getTime(); - let result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); + const start = new Date().getTime(); + const result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes); parseTime += new Date().getTime() - start; return result; @@ -529,7 +529,7 @@ namespace ts { export function parseSourceFile(fileName: string, _sourceText: string, languageVersion: ScriptTarget, _syntaxCursor: IncrementalParser.SyntaxCursor, setParentNodes?: boolean): SourceFile { initializeState(fileName, _sourceText, languageVersion, _syntaxCursor); - let result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); + const result = parseSourceFileWorker(fileName, languageVersion, setParentNodes); clearState(); @@ -625,10 +625,10 @@ namespace ts { } function addJSDocComment(node: Node) { - let comments = getLeadingCommentRangesOfNode(node, sourceFile); + const comments = getLeadingCommentRangesOfNode(node, sourceFile); if (comments) { - for (let comment of comments) { - let jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); + for (const comment of comments) { + const jsDocComment = JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); if (jsDocComment) { node.jsDocComment = jsDocComment; } @@ -653,7 +653,7 @@ namespace ts { if (n.parent !== parent) { n.parent = parent; - let saveParent = parent; + const saveParent = parent; parent = n; forEachChild(n, visitNode); parent = saveParent; @@ -662,7 +662,7 @@ namespace ts { } function createSourceFile(fileName: string, languageVersion: ScriptTarget): SourceFile { - let sourceFile = createNode(SyntaxKind.SourceFile, /*pos*/ 0); + const sourceFile = createNode(SyntaxKind.SourceFile, /*pos*/ 0); sourceFile.pos = 0; sourceFile.end = sourceText.length; @@ -708,11 +708,11 @@ namespace ts { // that we do not mutate cached flags for the incremental // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and // HasAggregatedChildData). - let contextFlagsToClear = context & contextFlags; + const contextFlagsToClear = context & contextFlags; if (contextFlagsToClear) { // clear the requested context flags setContextFlag(false, contextFlagsToClear); - let result = func(); + const result = func(); // restore the context flags we just cleared setContextFlag(true, contextFlagsToClear); return result; @@ -729,11 +729,11 @@ namespace ts { // that we do not mutate cached flags for the incremental // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and // HasAggregatedChildData). - let contextFlagsToSet = context & ~contextFlags; + const contextFlagsToSet = context & ~contextFlags; if (contextFlagsToSet) { // set the requested context flags setContextFlag(true, contextFlagsToSet); - let result = func(); + const result = func(); // reset the context flags we just set setContextFlag(false, contextFlagsToSet); return result; @@ -800,15 +800,15 @@ namespace ts { } function parseErrorAtCurrentToken(message: DiagnosticMessage, arg0?: any): void { - let start = scanner.getTokenPos(); - let length = scanner.getTextPos() - start; + const start = scanner.getTokenPos(); + const length = scanner.getTextPos() - start; parseErrorAtPosition(start, length, message, arg0); } function parseErrorAtPosition(start: number, length: number, message: DiagnosticMessage, arg0?: any): void { // Don't report another error if it would just be at the same position as the last error. - let lastError = lastOrUndefined(parseDiagnostics); + const lastError = lastOrUndefined(parseDiagnostics); if (!lastError || start !== lastError.start) { parseDiagnostics.push(createFileDiagnostic(sourceFile, start, length, message, arg0)); } @@ -819,7 +819,7 @@ namespace ts { } function scanError(message: DiagnosticMessage, length?: number) { - let pos = scanner.getTextPos(); + const pos = scanner.getTextPos(); parseErrorAtPosition(pos, length || 0, message); } @@ -862,20 +862,20 @@ namespace ts { function speculationHelper(callback: () => T, isLookAhead: boolean): T { // Keep track of the state we'll need to rollback to if lookahead fails (or if the // caller asked us to always reset our state). - let saveToken = token; - let saveParseDiagnosticsLength = parseDiagnostics.length; - let saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; + const saveToken = token; + const saveParseDiagnosticsLength = parseDiagnostics.length; + const saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode; // Note: it is not actually necessary to save/restore the context flags here. That's // because the saving/restoring of these flags happens naturally through the recursive // descent nature of our parser. However, we still store this here just so we can // assert that that invariant holds. - let saveContextFlags = contextFlags; + const saveContextFlags = contextFlags; // If we're only looking ahead, then tell the scanner to only lookahead as well. // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the // same. - let result = isLookAhead + const result = isLookAhead ? scanner.lookAhead(callback) : scanner.tryScan(callback); @@ -967,7 +967,7 @@ namespace ts { } function parseTokenNode(): T { - let node = createNode(token); + const node = createNode(token); nextToken(); return finishNode(node); } @@ -1030,7 +1030,7 @@ namespace ts { parseErrorAtCurrentToken(diagnosticMessage, arg0); } - let result = createNode(kind, scanner.getStartPos()); + const result = createNode(kind, scanner.getStartPos()); (result).text = ""; return finishNode(result); } @@ -1046,7 +1046,7 @@ namespace ts { function createIdentifier(isIdentifier: boolean, diagnosticMessage?: DiagnosticMessage): Identifier { identifierCount++; if (isIdentifier) { - let node = createNode(SyntaxKind.Identifier); + const node = createNode(SyntaxKind.Identifier); // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker if (token !== SyntaxKind.Identifier) { @@ -1100,7 +1100,7 @@ namespace ts { // PropertyName [Yield]: // LiteralPropertyName // ComputedPropertyName[?Yield] - let node = createNode(SyntaxKind.ComputedPropertyName); + const node = createNode(SyntaxKind.ComputedPropertyName); parseExpected(SyntaxKind.OpenBracketToken); // We parse any expression (including a comma expression). But the grammar @@ -1161,7 +1161,7 @@ namespace ts { // True if positioned at the start of a list element function isListElement(parsingContext: ParsingContext, inErrorRecovery: boolean): boolean { - let node = currentNode(parsingContext); + const node = currentNode(parsingContext); if (node) { return true; } @@ -1255,7 +1255,7 @@ namespace ts { // extends {} extends // extends {} implements - let next = nextToken(); + const next = nextToken(); return next === SyntaxKind.CommaToken || next === SyntaxKind.OpenBraceToken || next === SyntaxKind.ExtendsKeyword || next === SyntaxKind.ImplementsKeyword; } @@ -1383,14 +1383,14 @@ namespace ts { // Parses a list of elements function parseList(kind: ParsingContext, parseElement: () => T): NodeArray { - let saveParsingContext = parsingContext; + const saveParsingContext = parsingContext; parsingContext |= 1 << kind; - let result = >[]; + const result = >[]; result.pos = getNodePos(); while (!isListTerminator(kind)) { if (isListElement(kind, /* inErrorRecovery */ false)) { - let element = parseListElement(kind, parseElement); + const element = parseListElement(kind, parseElement); result.push(element); continue; @@ -1407,7 +1407,7 @@ namespace ts { } function parseListElement(parsingContext: ParsingContext, parseElement: () => T): T { - let node = currentNode(parsingContext); + const node = currentNode(parsingContext); if (node) { return consumeNode(node); } @@ -1432,7 +1432,7 @@ namespace ts { return undefined; } - let node = syntaxCursor.currentNode(scanner.getStartPos()); + const node = syntaxCursor.currentNode(scanner.getStartPos()); // Can't reuse a missing node. if (nodeIsMissing(node)) { @@ -1461,7 +1461,7 @@ namespace ts { // differently depending on what mode it is in. // // This also applies to all our other context flags as well. - let nodeContextFlags = node.parserContextFlags & ParserContextFlags.ParserGeneratedFlags; + const nodeContextFlags = node.parserContextFlags & ParserContextFlags.ParserGeneratedFlags; if (nodeContextFlags !== contextFlags) { return undefined; } @@ -1673,7 +1673,7 @@ namespace ts { // // In order to prevent this, we do not allow a variable declarator to be reused if it // has an initializer. - let variableDeclarator = node; + const variableDeclarator = node; return variableDeclarator.initializer === undefined; } @@ -1683,7 +1683,7 @@ namespace ts { } // See the comment in isReusableVariableDeclaration for why we do this. - let parameter = node; + const parameter = node; return parameter.initializer === undefined; } @@ -1731,9 +1731,9 @@ namespace ts { // Parses a comma-delimited list of elements function parseDelimitedList(kind: ParsingContext, parseElement: () => T, considerSemicolonAsDelimeter?: boolean): NodeArray { - let saveParsingContext = parsingContext; + const saveParsingContext = parsingContext; parsingContext |= 1 << kind; - let result = >[]; + const result = >[]; result.pos = getNodePos(); let commaStart = -1; // Meaning the previous token was not a comma @@ -1790,8 +1790,8 @@ namespace ts { } function createMissingList(): NodeArray { - let pos = getNodePos(); - let result = >[]; + const pos = getNodePos(); + const result = >[]; result.pos = pos; result.end = pos; return result; @@ -1799,7 +1799,7 @@ namespace ts { function parseBracketedList(kind: ParsingContext, parseElement: () => T, open: SyntaxKind, close: SyntaxKind): NodeArray { if (parseExpected(open)) { - let result = parseDelimitedList(kind, parseElement); + const result = parseDelimitedList(kind, parseElement); parseExpected(close); return result; } @@ -1811,7 +1811,7 @@ namespace ts { function parseEntityName(allowReservedWords: boolean, diagnosticMessage?: DiagnosticMessage): EntityName { let entity: EntityName = parseIdentifier(diagnosticMessage); while (parseOptional(SyntaxKind.DotToken)) { - let node = createNode(SyntaxKind.QualifiedName, entity.pos); + const node = createNode(SyntaxKind.QualifiedName, entity.pos); node.left = entity; node.right = parseRightSideOfDot(allowReservedWords); entity = finishNode(node); @@ -1840,7 +1840,7 @@ namespace ts { // In the first case though, ASI will not take effect because there is not a // line terminator after the identifier or keyword. if (scanner.hasPrecedingLineBreak() && tokenIsIdentifierOrKeyword(token)) { - let matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); + const matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine); if (matchesPattern) { // Report that we need an identifier. However, report it right after the dot, @@ -1854,12 +1854,12 @@ namespace ts { } function parseTemplateExpression(): TemplateExpression { - let template = createNode(SyntaxKind.TemplateExpression); + const template = createNode(SyntaxKind.TemplateExpression); template.head = parseLiteralNode(); Debug.assert(template.head.kind === SyntaxKind.TemplateHead, "Template head has wrong token kind"); - let templateSpans = >[]; + const templateSpans = >[]; templateSpans.pos = getNodePos(); do { @@ -1874,7 +1874,7 @@ namespace ts { } function parseTemplateSpan(): TemplateSpan { - let span = createNode(SyntaxKind.TemplateSpan); + const span = createNode(SyntaxKind.TemplateSpan); span.expression = allowInAnd(parseExpression); let literal: LiteralExpression; @@ -1892,8 +1892,8 @@ namespace ts { } function parseLiteralNode(internName?: boolean): LiteralExpression { - let node = createNode(token); - let text = scanner.getTokenValue(); + const node = createNode(token); + const text = scanner.getTokenValue(); node.text = internName ? internIdentifier(text) : text; if (scanner.hasExtendedUnicodeEscape()) { @@ -1904,7 +1904,7 @@ namespace ts { node.isUnterminated = true; } - let tokenPos = scanner.getTokenPos(); + const tokenPos = scanner.getTokenPos(); nextToken(); finishNode(node); @@ -1927,15 +1927,15 @@ namespace ts { // TYPES function parseTypeReferenceOrTypePredicate(): TypeReferenceNode | TypePredicateNode { - let typeName = parseEntityName(/*allowReservedWords*/ false, Diagnostics.Type_expected); + const typeName = parseEntityName(/*allowReservedWords*/ false, Diagnostics.Type_expected); if (typeName.kind === SyntaxKind.Identifier && token === SyntaxKind.IsKeyword && !scanner.hasPrecedingLineBreak()) { nextToken(); - let node = createNode(SyntaxKind.TypePredicate, typeName.pos); + const node = createNode(SyntaxKind.TypePredicate, typeName.pos); node.parameterName = typeName; node.type = parseType(); return finishNode(node); } - let node = createNode(SyntaxKind.TypeReference, typeName.pos); + const node = createNode(SyntaxKind.TypeReference, typeName.pos); node.typeName = typeName; if (!scanner.hasPrecedingLineBreak() && token === SyntaxKind.LessThanToken) { node.typeArguments = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken); @@ -1944,14 +1944,14 @@ namespace ts { } function parseTypeQuery(): TypeQueryNode { - let node = createNode(SyntaxKind.TypeQuery); + const node = createNode(SyntaxKind.TypeQuery); parseExpected(SyntaxKind.TypeOfKeyword); node.exprName = parseEntityName(/*allowReservedWords*/ true); return finishNode(node); } function parseTypeParameter(): TypeParameterDeclaration { - let node = createNode(SyntaxKind.TypeParameter); + const node = createNode(SyntaxKind.TypeParameter); node.name = parseIdentifier(); if (parseOptional(SyntaxKind.ExtendsKeyword)) { // It's not uncommon for people to write improper constraints to a generic. If the @@ -2004,7 +2004,7 @@ namespace ts { } function parseParameter(): ParameterDeclaration { - let node = createNode(SyntaxKind.Parameter); + const node = createNode(SyntaxKind.Parameter); node.decorators = parseDecorators(); setModifiers(node, parseModifiers()); node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken); @@ -2056,7 +2056,7 @@ namespace ts { requireCompleteParameterList: boolean, signature: SignatureDeclaration): void { - let returnTokenRequired = returnToken === SyntaxKind.EqualsGreaterThanToken; + const returnTokenRequired = returnToken === SyntaxKind.EqualsGreaterThanToken; signature.typeParameters = parseTypeParameters(); signature.parameters = parseParameterList(yieldContext, awaitContext, requireCompleteParameterList); @@ -2084,13 +2084,13 @@ namespace ts { // SingleNameBinding [Yield,Await]: // BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt if (parseExpected(SyntaxKind.OpenParenToken)) { - let savedYieldContext = inYieldContext(); - let savedAwaitContext = inAwaitContext(); + const savedYieldContext = inYieldContext(); + const savedAwaitContext = inAwaitContext(); setYieldContext(yieldContext); setAwaitContext(awaitContext); - let result = parseDelimitedList(ParsingContext.Parameters, parseParameter); + const result = parseDelimitedList(ParsingContext.Parameters, parseParameter); setYieldContext(savedYieldContext); setAwaitContext(savedAwaitContext); @@ -2122,7 +2122,7 @@ namespace ts { } function parseSignatureMember(kind: SyntaxKind): SignatureDeclaration { - let node = createNode(kind); + const node = createNode(kind); if (kind === SyntaxKind.ConstructSignature) { parseExpected(SyntaxKind.NewKeyword); } @@ -2195,7 +2195,7 @@ namespace ts { } function parseIndexSignatureDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): IndexSignatureDeclaration { - let node = createNode(SyntaxKind.IndexSignature, fullStart); + const node = createNode(SyntaxKind.IndexSignature, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.parameters = parseBracketedList(ParsingContext.Parameters, parseParameter, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken); @@ -2205,12 +2205,12 @@ namespace ts { } function parsePropertyOrMethodSignature(): Declaration { - let fullStart = scanner.getStartPos(); - let name = parsePropertyName(); - let questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + const fullStart = scanner.getStartPos(); + const name = parsePropertyName(); + const questionToken = parseOptionalToken(SyntaxKind.QuestionToken); if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) { - let method = createNode(SyntaxKind.MethodSignature, fullStart); + const method = createNode(SyntaxKind.MethodSignature, fullStart); method.name = name; method.questionToken = questionToken; @@ -2221,7 +2221,7 @@ namespace ts { return finishNode(method); } else { - let property = createNode(SyntaxKind.PropertySignature, fullStart); + const property = createNode(SyntaxKind.PropertySignature, fullStart); property.name = name; property.questionToken = questionToken; property.type = parseTypeAnnotation(); @@ -2238,7 +2238,7 @@ namespace ts { return true; default: if (isModifier(token)) { - let result = lookAhead(isStartOfIndexSignatureDeclaration); + const result = lookAhead(isStartOfIndexSignatureDeclaration); if (result) { return result; } @@ -2291,7 +2291,7 @@ namespace ts { // if it has the same text regardless of whether it is inside a class or an // object type. if (isModifier(token)) { - let result = tryParse(parseIndexSignatureWithModifiers); + const result = tryParse(parseIndexSignatureWithModifiers); if (result) { return result; } @@ -2304,9 +2304,9 @@ namespace ts { } function parseIndexSignatureWithModifiers() { - let fullStart = scanner.getStartPos(); - let decorators = parseDecorators(); - let modifiers = parseModifiers(); + const fullStart = scanner.getStartPos(); + const decorators = parseDecorators(); + const modifiers = parseModifiers(); return isIndexSignature() ? parseIndexSignatureDeclaration(fullStart, decorators, modifiers) : undefined; @@ -2318,7 +2318,7 @@ namespace ts { } function parseTypeLiteral(): TypeLiteralNode { - let node = createNode(SyntaxKind.TypeLiteral); + const node = createNode(SyntaxKind.TypeLiteral); node.members = parseObjectTypeMembers(); return finishNode(node); } @@ -2337,13 +2337,13 @@ namespace ts { } function parseTupleType(): TupleTypeNode { - let node = createNode(SyntaxKind.TupleType); + const node = createNode(SyntaxKind.TupleType); node.elementTypes = parseBracketedList(ParsingContext.TupleElementTypes, parseType, SyntaxKind.OpenBracketToken, SyntaxKind.CloseBracketToken); return finishNode(node); } function parseParenthesizedType(): ParenthesizedTypeNode { - let node = createNode(SyntaxKind.ParenthesizedType); + const node = createNode(SyntaxKind.ParenthesizedType); parseExpected(SyntaxKind.OpenParenToken); node.type = parseType(); parseExpected(SyntaxKind.CloseParenToken); @@ -2351,7 +2351,7 @@ namespace ts { } function parseFunctionOrConstructorType(kind: SyntaxKind): FunctionOrConstructorTypeNode { - let node = createNode(kind); + const node = createNode(kind); if (kind === SyntaxKind.ConstructorType) { parseExpected(SyntaxKind.NewKeyword); } @@ -2360,7 +2360,7 @@ namespace ts { } function parseKeywordAndNoDot(): TypeNode { - let node = parseTokenNode(); + const node = parseTokenNode(); return token === SyntaxKind.DotToken ? undefined : node; } @@ -2372,7 +2372,7 @@ namespace ts { case SyntaxKind.BooleanKeyword: case SyntaxKind.SymbolKeyword: // If these are followed by a dot, then parse these out as a dotted type reference instead. - let node = tryParse(parseKeywordAndNoDot); + const node = tryParse(parseKeywordAndNoDot); return node || parseTypeReferenceOrTypePredicate(); case SyntaxKind.VoidKeyword: case SyntaxKind.ThisKeyword: @@ -2423,7 +2423,7 @@ namespace ts { let type = parseNonArrayType(); while (!scanner.hasPrecedingLineBreak() && parseOptional(SyntaxKind.OpenBracketToken)) { parseExpected(SyntaxKind.CloseBracketToken); - let node = createNode(SyntaxKind.ArrayType, type.pos); + const node = createNode(SyntaxKind.ArrayType, type.pos); node.elementType = type; type = finishNode(node); } @@ -2433,13 +2433,13 @@ namespace ts { function parseUnionOrIntersectionType(kind: SyntaxKind, parseConstituentType: () => TypeNode, operator: SyntaxKind): TypeNode { let type = parseConstituentType(); if (token === operator) { - let types = >[type]; + const types = >[type]; types.pos = type.pos; while (parseOptional(operator)) { types.push(parseConstituentType()); } types.end = getNodeEnd(); - let node = createNode(kind, type.pos); + const node = createNode(kind, type.pos); node.types = types; type = finishNode(node); } @@ -2593,7 +2593,7 @@ namespace ts { // Expression[in] , AssignmentExpression[in] // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator - let saveDecoratorContext = inDecoratorContext(); + const saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { setDecoratorContext(false); } @@ -2654,7 +2654,7 @@ namespace ts { // parameter list. If we do, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. - let arrowExpression = tryParseParenthesizedArrowFunctionExpression(); + const arrowExpression = tryParseParenthesizedArrowFunctionExpression(); if (arrowExpression) { return arrowExpression; } @@ -2668,7 +2668,7 @@ namespace ts { // Otherwise, we try to parse out the conditional expression bit. We want to allow any // binary expression here, so we pass in the 'lowest' precedence here so that it matches // and consumes anything. - let expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); + const expr = parseBinaryExpressionOrHigher(/*precedence*/ 0); // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single @@ -2725,7 +2725,7 @@ namespace ts { } function parseYieldExpression(): YieldExpression { - let node = createNode(SyntaxKind.YieldExpression); + const node = createNode(SyntaxKind.YieldExpression); // YieldExpression[In] : // yield @@ -2749,9 +2749,9 @@ namespace ts { function parseSimpleArrowFunctionExpression(identifier: Identifier): Expression { Debug.assert(token === SyntaxKind.EqualsGreaterThanToken, "parseSimpleArrowFunctionExpression should only have been called if we had a =>"); - let node = createNode(SyntaxKind.ArrowFunction, identifier.pos); + const node = createNode(SyntaxKind.ArrowFunction, identifier.pos); - let parameter = createNode(SyntaxKind.Parameter, identifier.pos); + const parameter = createNode(SyntaxKind.Parameter, identifier.pos); parameter.name = identifier; finishNode(parameter); @@ -2766,7 +2766,7 @@ namespace ts { } function tryParseParenthesizedArrowFunctionExpression(): Expression { - let triState = isParenthesizedArrowFunctionExpression(); + const triState = isParenthesizedArrowFunctionExpression(); if (triState === Tristate.False) { // It's definitely not a parenthesized arrow function expression. return undefined; @@ -2776,7 +2776,7 @@ namespace ts { // following => or { token. Otherwise, we *might* have an arrow function. Try to parse // it out, but don't allow any ambiguity, and return 'undefined' if this could be an // expression instead. - let arrowFunction = triState === Tristate.True + const arrowFunction = triState === Tristate.True ? parseParenthesizedArrowFunctionExpressionHead(/*allowAmbiguity*/ true) : tryParse(parsePossibleParenthesizedArrowFunctionExpressionHead); @@ -2785,11 +2785,11 @@ namespace ts { return undefined; } - let isAsync = !!(arrowFunction.flags & NodeFlags.Async); + const isAsync = !!(arrowFunction.flags & NodeFlags.Async); // If we have an arrow, then try to parse the body. Even if not, try to parse if we // have an opening brace, just in case we're in an error state. - let lastToken = token; + const lastToken = token; arrowFunction.equalsGreaterThanToken = parseExpectedToken(SyntaxKind.EqualsGreaterThanToken, /*reportAtCurrentPosition*/false, Diagnostics._0_expected, "=>"); arrowFunction.body = (lastToken === SyntaxKind.EqualsGreaterThanToken || lastToken === SyntaxKind.OpenBraceToken) ? parseArrowFunctionExpressionBody(isAsync) @@ -2828,8 +2828,8 @@ namespace ts { } } - let first = token; - let second = nextToken(); + const first = token; + const second = nextToken(); if (first === SyntaxKind.OpenParenToken) { if (second === SyntaxKind.CloseParenToken) { @@ -2837,7 +2837,7 @@ namespace ts { // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. - let third = nextToken(); + const third = nextToken(); switch (third) { case SyntaxKind.EqualsGreaterThanToken: case SyntaxKind.ColonToken: @@ -2880,7 +2880,7 @@ namespace ts { } // This *could* be a parenthesized arrow function. - // Return Unknown to let the caller know. + // Return Unknown to const the caller know. return Tristate.Unknown; } else { @@ -2894,10 +2894,10 @@ namespace ts { // JSX overrides if (sourceFile.languageVariant === LanguageVariant.JSX) { - let isArrowFunctionInJsx = lookAhead(() => { - let third = nextToken(); + const isArrowFunctionInJsx = lookAhead(() => { + const third = nextToken(); if (third === SyntaxKind.ExtendsKeyword) { - let fourth = nextToken(); + const fourth = nextToken(); switch (fourth) { case SyntaxKind.EqualsToken: case SyntaxKind.GreaterThanToken: @@ -2929,9 +2929,9 @@ namespace ts { } function parseParenthesizedArrowFunctionExpressionHead(allowAmbiguity: boolean): ArrowFunction { - let node = createNode(SyntaxKind.ArrowFunction); + const node = createNode(SyntaxKind.ArrowFunction); setModifiers(node, parseModifiersForArrowFunction()); - let isAsync = !!(node.flags & NodeFlags.Async); + const isAsync = !!(node.flags & NodeFlags.Async); // Arrow functions are never generators. // @@ -2979,7 +2979,7 @@ namespace ts { // user meant to supply a block. For example, if the user wrote: // // a => - // let v = 0; + // const v = 0; // } // // they may be missing an open brace. Check to see if that's the case so we can @@ -2997,14 +2997,14 @@ namespace ts { function parseConditionalExpressionRest(leftOperand: Expression): Expression { // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher. - let questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + const questionToken = parseOptionalToken(SyntaxKind.QuestionToken); if (!questionToken) { return leftOperand; } // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and // we do not that for the 'whenFalse' part. - let node = createNode(SyntaxKind.ConditionalExpression, leftOperand.pos); + const node = createNode(SyntaxKind.ConditionalExpression, leftOperand.pos); node.condition = leftOperand; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); @@ -3015,7 +3015,7 @@ namespace ts { } function parseBinaryExpressionOrHigher(precedence: number): Expression { - let leftOperand = parseUnaryExpressionOrHigher(); + const leftOperand = parseUnaryExpressionOrHigher(); return parseBinaryExpressionRest(precedence, leftOperand); } @@ -3029,7 +3029,7 @@ namespace ts { // reScanGreaterToken so that we merge token sequences like > and = into >= reScanGreaterToken(); - let newPrecedence = getBinaryOperatorPrecedence(); + const newPrecedence = getBinaryOperatorPrecedence(); // Check the precedence to see if we should "take" this operator // - For left associative operator (all operator but **), consume the operator, @@ -3140,7 +3140,7 @@ namespace ts { } function makeBinaryExpression(left: Expression, operatorToken: Node, right: Expression): BinaryExpression { - let node = createNode(SyntaxKind.BinaryExpression, left.pos); + const node = createNode(SyntaxKind.BinaryExpression, left.pos); node.left = left; node.operatorToken = operatorToken; node.right = right; @@ -3148,14 +3148,14 @@ namespace ts { } function makeAsExpression(left: Expression, right: TypeNode): AsExpression { - let node = createNode(SyntaxKind.AsExpression, left.pos); + const node = createNode(SyntaxKind.AsExpression, left.pos); node.expression = left; node.type = right; return finishNode(node); } function parsePrefixUnaryExpression() { - let node = createNode(SyntaxKind.PrefixUnaryExpression); + const node = createNode(SyntaxKind.PrefixUnaryExpression); node.operator = token; nextToken(); node.operand = parseSimpleUnaryExpression(); @@ -3164,21 +3164,21 @@ namespace ts { } function parseDeleteExpression() { - let node = createNode(SyntaxKind.DeleteExpression); + const node = createNode(SyntaxKind.DeleteExpression); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseTypeOfExpression() { - let node = createNode(SyntaxKind.TypeOfExpression); + const node = createNode(SyntaxKind.TypeOfExpression); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); } function parseVoidExpression() { - let node = createNode(SyntaxKind.VoidExpression); + const node = createNode(SyntaxKind.VoidExpression); nextToken(); node.expression = parseSimpleUnaryExpression(); return finishNode(node); @@ -3217,17 +3217,16 @@ namespace ts { } if (isIncrementExpression()) { - let incrementExpression = parseIncrementExpression(); + const incrementExpression = parseIncrementExpression(); return token === SyntaxKind.AsteriskAsteriskToken ? parseBinaryExpressionRest(getBinaryOperatorPrecedence(), incrementExpression) : incrementExpression; } - let unaryOperator = token; - let simpleUnaryExpression = parseSimpleUnaryExpression(); + const unaryOperator = token; + const simpleUnaryExpression = parseSimpleUnaryExpression(); if (token === SyntaxKind.AsteriskAsteriskToken) { - let diagnostic: Diagnostic; - let start = skipTrivia(sourceText, simpleUnaryExpression.pos); + const start = skipTrivia(sourceText, simpleUnaryExpression.pos); if (simpleUnaryExpression.kind === SyntaxKind.TypeAssertionExpression) { parseErrorAtPosition(start, simpleUnaryExpression.end - start, Diagnostics.A_type_assertion_expression_is_not_allowed_in_the_left_hand_side_of_an_exponentiation_expression_Consider_enclosing_the_expression_in_parentheses); } @@ -3321,7 +3320,7 @@ namespace ts { */ function parseIncrementExpression(): IncrementExpression { if (token === SyntaxKind.PlusPlusToken || token === SyntaxKind.MinusMinusToken) { - let node = createNode(SyntaxKind.PrefixUnaryExpression); + const node = createNode(SyntaxKind.PrefixUnaryExpression); node.operator = token; nextToken(); node.operand = parseLeftHandSideExpressionOrHigher(); @@ -3332,11 +3331,11 @@ namespace ts { return parseJsxElementOrSelfClosingElement(/*inExpressionContext*/ true); } - let expression = parseLeftHandSideExpressionOrHigher(); + const expression = parseLeftHandSideExpressionOrHigher(); Debug.assert(isLeftHandSideExpression(expression)); if ((token === SyntaxKind.PlusPlusToken || token === SyntaxKind.MinusMinusToken) && !scanner.hasPrecedingLineBreak()) { - let node = createNode(SyntaxKind.PostfixUnaryExpression, expression.pos); + const node = createNode(SyntaxKind.PostfixUnaryExpression, expression.pos); node.operand = expression; node.operator = token; nextToken(); @@ -3377,7 +3376,7 @@ namespace ts { // the last two CallExpression productions. Or we have a MemberExpression which either // completes the LeftHandSideExpression, or starts the beginning of the first four // CallExpression productions. - let expression = token === SyntaxKind.SuperKeyword + const expression = token === SyntaxKind.SuperKeyword ? parseSuperExpression() : parseMemberExpressionOrHigher(); @@ -3434,19 +3433,19 @@ namespace ts { // // Because CallExpression and MemberExpression are left recursive, we need to bottom out // of the recursion immediately. So we parse out a primary expression to start with. - let expression = parsePrimaryExpression(); + const expression = parsePrimaryExpression(); return parseMemberExpressionRest(expression); } function parseSuperExpression(): MemberExpression { - let expression = parseTokenNode(); + const expression = parseTokenNode(); if (token === SyntaxKind.OpenParenToken || token === SyntaxKind.DotToken || token === SyntaxKind.OpenBracketToken) { return expression; } // If we have seen "super" it must be followed by '(' or '.'. // If it wasn't then just try to parse out a '.' and report an error. - let node = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); + const node = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); node.expression = expression; node.dotToken = parseExpectedToken(SyntaxKind.DotToken, /*reportAtCurrentPosition*/ false, Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access); node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); @@ -3454,10 +3453,10 @@ namespace ts { } function parseJsxElementOrSelfClosingElement(inExpressionContext: boolean): JsxElement | JsxSelfClosingElement { - let opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); + const opening = parseJsxOpeningOrSelfClosingElement(inExpressionContext); let result: JsxElement | JsxSelfClosingElement; if (opening.kind === SyntaxKind.JsxOpeningElement) { - let node = createNode(SyntaxKind.JsxElement, opening.pos); + const node = createNode(SyntaxKind.JsxElement, opening.pos); node.openingElement = opening; node.children = parseJsxChildren(node.openingElement.tagName); @@ -3478,10 +3477,10 @@ namespace ts { // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios // of one sort or another. if (inExpressionContext && token === SyntaxKind.LessThanToken) { - let invalidElement = tryParse(() => parseJsxElementOrSelfClosingElement(/*inExpressionContext*/true)); + const invalidElement = tryParse(() => parseJsxElementOrSelfClosingElement(/*inExpressionContext*/true)); if (invalidElement) { parseErrorAtCurrentToken(Diagnostics.JSX_expressions_must_have_one_parent_element); - let badNode = createNode(SyntaxKind.BinaryExpression, result.pos); + const badNode = createNode(SyntaxKind.BinaryExpression, result.pos); badNode.end = invalidElement.end; badNode.left = result; badNode.right = invalidElement; @@ -3495,7 +3494,7 @@ namespace ts { } function parseJsxText(): JsxText { - let node = createNode(SyntaxKind.JsxText, scanner.getStartPos()); + const node = createNode(SyntaxKind.JsxText, scanner.getStartPos()); token = scanner.scanJsxToken(); return finishNode(node); } @@ -3513,9 +3512,9 @@ namespace ts { } function parseJsxChildren(openingTagName: EntityName): NodeArray { - let result = >[]; + const result = >[]; result.pos = scanner.getStartPos(); - let saveParsingContext = parsingContext; + const saveParsingContext = parsingContext; parsingContext |= 1 << ParsingContext.JsxChildren; while (true) { @@ -3538,13 +3537,13 @@ namespace ts { } function parseJsxOpeningOrSelfClosingElement(inExpressionContext: boolean): JsxOpeningElement | JsxSelfClosingElement { - let fullStart = scanner.getStartPos(); + const fullStart = scanner.getStartPos(); parseExpected(SyntaxKind.LessThanToken); - let tagName = parseJsxElementName(); + const tagName = parseJsxElementName(); - let attributes = parseList(ParsingContext.JsxAttributes, parseJsxAttribute); + const attributes = parseList(ParsingContext.JsxAttributes, parseJsxAttribute); let node: JsxOpeningLikeElement; if (token === SyntaxKind.GreaterThanToken) { @@ -3577,7 +3576,7 @@ namespace ts { let elementName: EntityName = parseIdentifierName(); while (parseOptional(SyntaxKind.DotToken)) { scanJsxIdentifier(); - let node = createNode(SyntaxKind.QualifiedName, elementName.pos); + const node = createNode(SyntaxKind.QualifiedName, elementName.pos); node.left = elementName; node.right = parseIdentifierName(); elementName = finishNode(node); @@ -3586,7 +3585,7 @@ namespace ts { } function parseJsxExpression(inExpressionContext: boolean): JsxExpression { - let node = createNode(SyntaxKind.JsxExpression); + const node = createNode(SyntaxKind.JsxExpression); parseExpected(SyntaxKind.OpenBraceToken); if (token !== SyntaxKind.CloseBraceToken) { @@ -3609,7 +3608,7 @@ namespace ts { } scanJsxIdentifier(); - let node = createNode(SyntaxKind.JsxAttribute); + const node = createNode(SyntaxKind.JsxAttribute); node.name = parseIdentifierName(); if (parseOptional(SyntaxKind.EqualsToken)) { switch (token) { @@ -3625,7 +3624,7 @@ namespace ts { } function parseJsxSpreadAttribute(): JsxSpreadAttribute { - let node = createNode(SyntaxKind.JsxSpreadAttribute); + const node = createNode(SyntaxKind.JsxSpreadAttribute); parseExpected(SyntaxKind.OpenBraceToken); parseExpected(SyntaxKind.DotDotDotToken); node.expression = parseExpression(); @@ -3634,7 +3633,7 @@ namespace ts { } function parseJsxClosingElement(inExpressionContext: boolean): JsxClosingElement { - let node = createNode(SyntaxKind.JsxClosingElement); + const node = createNode(SyntaxKind.JsxClosingElement); parseExpected(SyntaxKind.LessThanSlashToken); node.tagName = parseJsxElementName(); if (inExpressionContext) { @@ -3648,7 +3647,7 @@ namespace ts { } function parseTypeAssertion(): TypeAssertion { - let node = createNode(SyntaxKind.TypeAssertionExpression); + const node = createNode(SyntaxKind.TypeAssertionExpression); parseExpected(SyntaxKind.LessThanToken); node.type = parseType(); parseExpected(SyntaxKind.GreaterThanToken); @@ -3658,9 +3657,9 @@ namespace ts { function parseMemberExpressionRest(expression: LeftHandSideExpression): MemberExpression { while (true) { - let dotToken = parseOptionalToken(SyntaxKind.DotToken); + const dotToken = parseOptionalToken(SyntaxKind.DotToken); if (dotToken) { - let propertyAccess = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); + const propertyAccess = createNode(SyntaxKind.PropertyAccessExpression, expression.pos); propertyAccess.expression = expression; propertyAccess.dotToken = dotToken; propertyAccess.name = parseRightSideOfDot(/*allowIdentifierNames*/ true); @@ -3670,7 +3669,7 @@ namespace ts { // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName if (!inDecoratorContext() && parseOptional(SyntaxKind.OpenBracketToken)) { - let indexedAccess = createNode(SyntaxKind.ElementAccessExpression, expression.pos); + const indexedAccess = createNode(SyntaxKind.ElementAccessExpression, expression.pos); indexedAccess.expression = expression; // It's not uncommon for a user to write: "new Type[]". @@ -3678,7 +3677,7 @@ namespace ts { if (token !== SyntaxKind.CloseBracketToken) { indexedAccess.argumentExpression = allowInAnd(parseExpression); if (indexedAccess.argumentExpression.kind === SyntaxKind.StringLiteral || indexedAccess.argumentExpression.kind === SyntaxKind.NumericLiteral) { - let literal = indexedAccess.argumentExpression; + const literal = indexedAccess.argumentExpression; literal.text = internIdentifier(literal.text); } } @@ -3689,7 +3688,7 @@ namespace ts { } if (token === SyntaxKind.NoSubstitutionTemplateLiteral || token === SyntaxKind.TemplateHead) { - let tagExpression = createNode(SyntaxKind.TaggedTemplateExpression, expression.pos); + const tagExpression = createNode(SyntaxKind.TaggedTemplateExpression, expression.pos); tagExpression.tag = expression; tagExpression.template = token === SyntaxKind.NoSubstitutionTemplateLiteral ? parseLiteralNode() @@ -3710,12 +3709,12 @@ namespace ts { // keep checking for postfix expressions. Otherwise, it's just a '<' that's // part of an arithmetic expression. Break out so we consume it higher in the // stack. - let typeArguments = tryParse(parseTypeArgumentsInExpression); + const typeArguments = tryParse(parseTypeArgumentsInExpression); if (!typeArguments) { return expression; } - let callExpr = createNode(SyntaxKind.CallExpression, expression.pos); + const callExpr = createNode(SyntaxKind.CallExpression, expression.pos); callExpr.expression = expression; callExpr.typeArguments = typeArguments; callExpr.arguments = parseArgumentList(); @@ -3723,7 +3722,7 @@ namespace ts { continue; } else if (token === SyntaxKind.OpenParenToken) { - let callExpr = createNode(SyntaxKind.CallExpression, expression.pos); + const callExpr = createNode(SyntaxKind.CallExpression, expression.pos); callExpr.expression = expression; callExpr.arguments = parseArgumentList(); expression = finishNode(callExpr); @@ -3736,7 +3735,7 @@ namespace ts { function parseArgumentList() { parseExpected(SyntaxKind.OpenParenToken); - let result = parseDelimitedList(ParsingContext.ArgumentExpressions, parseArgumentExpression); + const result = parseDelimitedList(ParsingContext.ArgumentExpressions, parseArgumentExpression); parseExpected(SyntaxKind.CloseParenToken); return result; } @@ -3746,7 +3745,7 @@ namespace ts { return undefined; } - let typeArguments = parseDelimitedList(ParsingContext.TypeArguments, parseType); + const typeArguments = parseDelimitedList(ParsingContext.TypeArguments, parseType); if (!parseExpected(SyntaxKind.GreaterThanToken)) { // If it doesn't have the closing > then it's definitely not an type argument list. return undefined; @@ -3846,7 +3845,7 @@ namespace ts { } function parseParenthesizedExpression(): ParenthesizedExpression { - let node = createNode(SyntaxKind.ParenthesizedExpression); + const node = createNode(SyntaxKind.ParenthesizedExpression); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); @@ -3854,7 +3853,7 @@ namespace ts { } function parseSpreadElement(): Expression { - let node = createNode(SyntaxKind.SpreadElementExpression); + const node = createNode(SyntaxKind.SpreadElementExpression); parseExpected(SyntaxKind.DotDotDotToken); node.expression = parseAssignmentExpressionOrHigher(); return finishNode(node); @@ -3871,7 +3870,7 @@ namespace ts { } function parseArrayLiteralExpression(): ArrayLiteralExpression { - let node = createNode(SyntaxKind.ArrayLiteralExpression); + const node = createNode(SyntaxKind.ArrayLiteralExpression); parseExpected(SyntaxKind.OpenBracketToken); if (scanner.hasPrecedingLineBreak()) node.flags |= NodeFlags.MultiLine; node.elements = parseDelimitedList(ParsingContext.ArrayLiteralMembers, parseArgumentOrArrayLiteralElement); @@ -3891,22 +3890,22 @@ namespace ts { } function parseObjectLiteralElement(): ObjectLiteralElement { - let fullStart = scanner.getStartPos(); - let decorators = parseDecorators(); - let modifiers = parseModifiers(); + const fullStart = scanner.getStartPos(); + const decorators = parseDecorators(); + const modifiers = parseModifiers(); - let accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + const accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; } - let asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); - let tokenIsIdentifier = isIdentifier(); - let nameToken = token; - let propertyName = parsePropertyName(); + const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); + const tokenIsIdentifier = isIdentifier(); + const nameToken = token; + const propertyName = parsePropertyName(); // Disallowing of optional property assignments happens in the grammar checker. - let questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + const questionToken = parseOptionalToken(SyntaxKind.QuestionToken); if (asteriskToken || token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, propertyName, questionToken); } @@ -3920,7 +3919,7 @@ namespace ts { tokenIsIdentifier && (token === SyntaxKind.CommaToken || token === SyntaxKind.CloseBraceToken || token === SyntaxKind.EqualsToken); if (isShorthandPropertyAssignment) { - let shorthandDeclaration = createNode(SyntaxKind.ShorthandPropertyAssignment, fullStart); + const shorthandDeclaration = createNode(SyntaxKind.ShorthandPropertyAssignment, fullStart); shorthandDeclaration.name = propertyName; shorthandDeclaration.questionToken = questionToken; const equalsToken = parseOptionalToken(SyntaxKind.EqualsToken); @@ -3931,7 +3930,7 @@ namespace ts { return finishNode(shorthandDeclaration); } else { - let propertyAssignment = createNode(SyntaxKind.PropertyAssignment, fullStart); + const propertyAssignment = createNode(SyntaxKind.PropertyAssignment, fullStart); propertyAssignment.name = propertyName; propertyAssignment.questionToken = questionToken; parseExpected(SyntaxKind.ColonToken); @@ -3941,7 +3940,7 @@ namespace ts { } function parseObjectLiteralExpression(): ObjectLiteralExpression { - let node = createNode(SyntaxKind.ObjectLiteralExpression); + const node = createNode(SyntaxKind.ObjectLiteralExpression); parseExpected(SyntaxKind.OpenBraceToken); if (scanner.hasPrecedingLineBreak()) { node.flags |= NodeFlags.MultiLine; @@ -3958,18 +3957,18 @@ namespace ts { // // FunctionExpression: // function BindingIdentifier[opt](FormalParameters){ FunctionBody } - let saveDecoratorContext = inDecoratorContext(); + const saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { setDecoratorContext(false); } - let node = createNode(SyntaxKind.FunctionExpression); + const node = createNode(SyntaxKind.FunctionExpression); setModifiers(node, parseModifiers()); parseExpected(SyntaxKind.FunctionKeyword); node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); - let isGenerator = !!node.asteriskToken; - let isAsync = !!(node.flags & NodeFlags.Async); + const isGenerator = !!node.asteriskToken; + const isAsync = !!(node.flags & NodeFlags.Async); node.name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalIdentifier) : isGenerator ? doInYieldContext(parseOptionalIdentifier) : @@ -3991,7 +3990,7 @@ namespace ts { } function parseNewExpression(): NewExpression { - let node = createNode(SyntaxKind.NewExpression); + const node = createNode(SyntaxKind.NewExpression); parseExpected(SyntaxKind.NewKeyword); node.expression = parseMemberExpressionOrHigher(); node.typeArguments = tryParse(parseTypeArgumentsInExpression); @@ -4004,7 +4003,7 @@ namespace ts { // STATEMENTS function parseBlock(ignoreMissingOpenBrace: boolean, diagnosticMessage?: DiagnosticMessage): Block { - let node = createNode(SyntaxKind.Block); + const node = createNode(SyntaxKind.Block); if (parseExpected(SyntaxKind.OpenBraceToken, diagnosticMessage) || ignoreMissingOpenBrace) { node.statements = parseList(ParsingContext.BlockStatements, parseStatement); parseExpected(SyntaxKind.CloseBraceToken); @@ -4016,20 +4015,20 @@ namespace ts { } function parseFunctionBlock(allowYield: boolean, allowAwait: boolean, ignoreMissingOpenBrace: boolean, diagnosticMessage?: DiagnosticMessage): Block { - let savedYieldContext = inYieldContext(); + const savedYieldContext = inYieldContext(); setYieldContext(allowYield); - let savedAwaitContext = inAwaitContext(); + const savedAwaitContext = inAwaitContext(); setAwaitContext(allowAwait); // We may be in a [Decorator] context when parsing a function expression or // arrow function. The body of the function is not in [Decorator] context. - let saveDecoratorContext = inDecoratorContext(); + const saveDecoratorContext = inDecoratorContext(); if (saveDecoratorContext) { setDecoratorContext(false); } - let block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); + const block = parseBlock(ignoreMissingOpenBrace, diagnosticMessage); if (saveDecoratorContext) { setDecoratorContext(true); @@ -4042,13 +4041,13 @@ namespace ts { } function parseEmptyStatement(): Statement { - let node = createNode(SyntaxKind.EmptyStatement); + const node = createNode(SyntaxKind.EmptyStatement); parseExpected(SyntaxKind.SemicolonToken); return finishNode(node); } function parseIfStatement(): IfStatement { - let node = createNode(SyntaxKind.IfStatement); + const node = createNode(SyntaxKind.IfStatement); parseExpected(SyntaxKind.IfKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); @@ -4059,7 +4058,7 @@ namespace ts { } function parseDoStatement(): DoStatement { - let node = createNode(SyntaxKind.DoStatement); + const node = createNode(SyntaxKind.DoStatement); parseExpected(SyntaxKind.DoKeyword); node.statement = parseStatement(); parseExpected(SyntaxKind.WhileKeyword); @@ -4076,7 +4075,7 @@ namespace ts { } function parseWhileStatement(): WhileStatement { - let node = createNode(SyntaxKind.WhileStatement); + const node = createNode(SyntaxKind.WhileStatement); parseExpected(SyntaxKind.WhileKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); @@ -4086,7 +4085,7 @@ namespace ts { } function parseForOrForInOrForOfStatement(): Statement { - let pos = getNodePos(); + const pos = getNodePos(); parseExpected(SyntaxKind.ForKeyword); parseExpected(SyntaxKind.OpenParenToken); @@ -4101,21 +4100,21 @@ namespace ts { } let forOrForInOrForOfStatement: IterationStatement; if (parseOptional(SyntaxKind.InKeyword)) { - let forInStatement = createNode(SyntaxKind.ForInStatement, pos); + const forInStatement = createNode(SyntaxKind.ForInStatement, pos); forInStatement.initializer = initializer; forInStatement.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); forOrForInOrForOfStatement = forInStatement; } else if (parseOptional(SyntaxKind.OfKeyword)) { - let forOfStatement = createNode(SyntaxKind.ForOfStatement, pos); + const forOfStatement = createNode(SyntaxKind.ForOfStatement, pos); forOfStatement.initializer = initializer; forOfStatement.expression = allowInAnd(parseAssignmentExpressionOrHigher); parseExpected(SyntaxKind.CloseParenToken); forOrForInOrForOfStatement = forOfStatement; } else { - let forStatement = createNode(SyntaxKind.ForStatement, pos); + const forStatement = createNode(SyntaxKind.ForStatement, pos); forStatement.initializer = initializer; parseExpected(SyntaxKind.SemicolonToken); if (token !== SyntaxKind.SemicolonToken && token !== SyntaxKind.CloseParenToken) { @@ -4135,7 +4134,7 @@ namespace ts { } function parseBreakOrContinueStatement(kind: SyntaxKind): BreakOrContinueStatement { - let node = createNode(kind); + const node = createNode(kind); parseExpected(kind === SyntaxKind.BreakStatement ? SyntaxKind.BreakKeyword : SyntaxKind.ContinueKeyword); if (!canParseSemicolon()) { @@ -4147,7 +4146,7 @@ namespace ts { } function parseReturnStatement(): ReturnStatement { - let node = createNode(SyntaxKind.ReturnStatement); + const node = createNode(SyntaxKind.ReturnStatement); parseExpected(SyntaxKind.ReturnKeyword); if (!canParseSemicolon()) { @@ -4159,7 +4158,7 @@ namespace ts { } function parseWithStatement(): WithStatement { - let node = createNode(SyntaxKind.WithStatement); + const node = createNode(SyntaxKind.WithStatement); parseExpected(SyntaxKind.WithKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); @@ -4169,7 +4168,7 @@ namespace ts { } function parseCaseClause(): CaseClause { - let node = createNode(SyntaxKind.CaseClause); + const node = createNode(SyntaxKind.CaseClause); parseExpected(SyntaxKind.CaseKeyword); node.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.ColonToken); @@ -4178,7 +4177,7 @@ namespace ts { } function parseDefaultClause(): DefaultClause { - let node = createNode(SyntaxKind.DefaultClause); + const node = createNode(SyntaxKind.DefaultClause); parseExpected(SyntaxKind.DefaultKeyword); parseExpected(SyntaxKind.ColonToken); node.statements = parseList(ParsingContext.SwitchClauseStatements, parseStatement); @@ -4190,12 +4189,12 @@ namespace ts { } function parseSwitchStatement(): SwitchStatement { - let node = createNode(SyntaxKind.SwitchStatement); + const node = createNode(SyntaxKind.SwitchStatement); parseExpected(SyntaxKind.SwitchKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = allowInAnd(parseExpression); parseExpected(SyntaxKind.CloseParenToken); - let caseBlock = createNode(SyntaxKind.CaseBlock, scanner.getStartPos()); + const caseBlock = createNode(SyntaxKind.CaseBlock, scanner.getStartPos()); parseExpected(SyntaxKind.OpenBraceToken); caseBlock.clauses = parseList(ParsingContext.SwitchClauses, parseCaseOrDefaultClause); parseExpected(SyntaxKind.CloseBraceToken); @@ -4212,7 +4211,7 @@ namespace ts { // directly as that might consume an expression on the following line. // We just return 'undefined' in that case. The actual error will be reported in the // grammar walker. - let node = createNode(SyntaxKind.ThrowStatement); + const node = createNode(SyntaxKind.ThrowStatement); parseExpected(SyntaxKind.ThrowKeyword); node.expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression); parseSemicolon(); @@ -4221,7 +4220,7 @@ namespace ts { // TODO: Review for error recovery function parseTryStatement(): TryStatement { - let node = createNode(SyntaxKind.TryStatement); + const node = createNode(SyntaxKind.TryStatement); parseExpected(SyntaxKind.TryKeyword); node.tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false); @@ -4238,7 +4237,7 @@ namespace ts { } function parseCatchClause(): CatchClause { - let result = createNode(SyntaxKind.CatchClause); + const result = createNode(SyntaxKind.CatchClause); parseExpected(SyntaxKind.CatchKeyword); if (parseExpected(SyntaxKind.OpenParenToken)) { result.variableDeclaration = parseVariableDeclaration(); @@ -4250,7 +4249,7 @@ namespace ts { } function parseDebuggerStatement(): Statement { - let node = createNode(SyntaxKind.DebuggerStatement); + const node = createNode(SyntaxKind.DebuggerStatement); parseExpected(SyntaxKind.DebuggerKeyword); parseSemicolon(); return finishNode(node); @@ -4260,17 +4259,17 @@ namespace ts { // Avoiding having to do the lookahead for a labeled statement by just trying to parse // out an expression, seeing if it is identifier and then seeing if it is followed by // a colon. - let fullStart = scanner.getStartPos(); - let expression = allowInAnd(parseExpression); + const fullStart = scanner.getStartPos(); + const expression = allowInAnd(parseExpression); if (expression.kind === SyntaxKind.Identifier && parseOptional(SyntaxKind.ColonToken)) { - let labeledStatement = createNode(SyntaxKind.LabeledStatement, fullStart); + const labeledStatement = createNode(SyntaxKind.LabeledStatement, fullStart); labeledStatement.label = expression; labeledStatement.statement = parseStatement(); return finishNode(labeledStatement); } else { - let expressionStatement = createNode(SyntaxKind.ExpressionStatement, fullStart); + const expressionStatement = createNode(SyntaxKind.ExpressionStatement, fullStart); expressionStatement.expression = expression; parseSemicolon(); return finishNode(expressionStatement); @@ -4504,9 +4503,9 @@ namespace ts { } function parseDeclaration(): Statement { - let fullStart = getNodePos(); - let decorators = parseDecorators(); - let modifiers = parseModifiers(); + const fullStart = getNodePos(); + const decorators = parseDecorators(); + const modifiers = parseModifiers(); switch (token) { case SyntaxKind.VarKeyword: case SyntaxKind.LetKeyword: @@ -4536,7 +4535,7 @@ namespace ts { if (decorators || modifiers) { // We reached this point because we encountered decorators and/or modifiers and assumed a declaration // would follow. For recovery and error reporting purposes, return an incomplete declaration. - let node = createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); + const node = createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); node.pos = fullStart; node.decorators = decorators; setModifiers(node, modifiers); @@ -4565,7 +4564,7 @@ namespace ts { if (token === SyntaxKind.CommaToken) { return createNode(SyntaxKind.OmittedExpression); } - let node = createNode(SyntaxKind.BindingElement); + const node = createNode(SyntaxKind.BindingElement); node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken); node.name = parseIdentifierOrPattern(); node.initializer = parseBindingElementInitializer(/*inParameter*/ false); @@ -4573,10 +4572,10 @@ namespace ts { } function parseObjectBindingElement(): BindingElement { - let node = createNode(SyntaxKind.BindingElement); + const node = createNode(SyntaxKind.BindingElement); // TODO(andersh): Handle computed properties - let tokenIsIdentifier = isIdentifier(); - let propertyName = parsePropertyName(); + const tokenIsIdentifier = isIdentifier(); + const propertyName = parsePropertyName(); if (tokenIsIdentifier && token !== SyntaxKind.ColonToken) { node.name = propertyName; } @@ -4590,7 +4589,7 @@ namespace ts { } function parseObjectBindingPattern(): BindingPattern { - let node = createNode(SyntaxKind.ObjectBindingPattern); + const node = createNode(SyntaxKind.ObjectBindingPattern); parseExpected(SyntaxKind.OpenBraceToken); node.elements = parseDelimitedList(ParsingContext.ObjectBindingElements, parseObjectBindingElement); parseExpected(SyntaxKind.CloseBraceToken); @@ -4598,7 +4597,7 @@ namespace ts { } function parseArrayBindingPattern(): BindingPattern { - let node = createNode(SyntaxKind.ArrayBindingPattern); + const node = createNode(SyntaxKind.ArrayBindingPattern); parseExpected(SyntaxKind.OpenBracketToken); node.elements = parseDelimitedList(ParsingContext.ArrayBindingElements, parseArrayBindingElement); parseExpected(SyntaxKind.CloseBracketToken); @@ -4620,7 +4619,7 @@ namespace ts { } function parseVariableDeclaration(): VariableDeclaration { - let node = createNode(SyntaxKind.VariableDeclaration); + const node = createNode(SyntaxKind.VariableDeclaration); node.name = parseIdentifierOrPattern(); node.type = parseTypeAnnotation(); if (!isInOrOfKeyword(token)) { @@ -4630,7 +4629,7 @@ namespace ts { } function parseVariableDeclarationList(inForStatementInitializer: boolean): VariableDeclarationList { - let node = createNode(SyntaxKind.VariableDeclarationList); + const node = createNode(SyntaxKind.VariableDeclarationList); switch (token) { case SyntaxKind.VarKeyword: @@ -4660,7 +4659,7 @@ namespace ts { node.declarations = createMissingList(); } else { - let savedDisallowIn = inDisallowInContext(); + const savedDisallowIn = inDisallowInContext(); setDisallowInContext(inForStatementInitializer); node.declarations = parseDelimitedList(ParsingContext.VariableDeclarations, parseVariableDeclaration); @@ -4676,7 +4675,7 @@ namespace ts { } function parseVariableStatement(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): VariableStatement { - let node = createNode(SyntaxKind.VariableStatement, fullStart); + const node = createNode(SyntaxKind.VariableStatement, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false); @@ -4685,21 +4684,21 @@ namespace ts { } function parseFunctionDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): FunctionDeclaration { - let node = createNode(SyntaxKind.FunctionDeclaration, fullStart); + const node = createNode(SyntaxKind.FunctionDeclaration, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.FunctionKeyword); node.asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); node.name = node.flags & NodeFlags.Default ? parseOptionalIdentifier() : parseIdentifier(); - let isGenerator = !!node.asteriskToken; - let isAsync = !!(node.flags & NodeFlags.Async); + const isGenerator = !!node.asteriskToken; + const isAsync = !!(node.flags & NodeFlags.Async); fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, node); node.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, Diagnostics.or_expected); return finishNode(node); } function parseConstructorDeclaration(pos: number, decorators: NodeArray, modifiers: ModifiersArray): ConstructorDeclaration { - let node = createNode(SyntaxKind.Constructor, pos); + const node = createNode(SyntaxKind.Constructor, pos); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.ConstructorKeyword); @@ -4709,21 +4708,21 @@ namespace ts { } function parseMethodDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, asteriskToken: Node, name: DeclarationName, questionToken: Node, diagnosticMessage?: DiagnosticMessage): MethodDeclaration { - let method = createNode(SyntaxKind.MethodDeclaration, fullStart); + const method = createNode(SyntaxKind.MethodDeclaration, fullStart); method.decorators = decorators; setModifiers(method, modifiers); method.asteriskToken = asteriskToken; method.name = name; method.questionToken = questionToken; - let isGenerator = !!asteriskToken; - let isAsync = !!(method.flags & NodeFlags.Async); + const isGenerator = !!asteriskToken; + const isAsync = !!(method.flags & NodeFlags.Async); fillSignature(SyntaxKind.ColonToken, /*yieldContext*/ isGenerator, /*awaitContext*/ isAsync, /*requireCompleteParameterList*/ false, method); method.body = parseFunctionBlockOrSemicolon(isGenerator, isAsync, diagnosticMessage); return finishNode(method); } function parsePropertyDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, name: DeclarationName, questionToken: Node): ClassElement { - let property = createNode(SyntaxKind.PropertyDeclaration, fullStart); + const property = createNode(SyntaxKind.PropertyDeclaration, fullStart); property.decorators = decorators; setModifiers(property, modifiers); property.name = name; @@ -4748,12 +4747,12 @@ namespace ts { } function parsePropertyOrMethodDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): ClassElement { - let asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); - let name = parsePropertyName(); + const asteriskToken = parseOptionalToken(SyntaxKind.AsteriskToken); + const name = parsePropertyName(); // Note: this is not legal as per the grammar. But we allow it in the parser and // report an error in the grammar checker. - let questionToken = parseOptionalToken(SyntaxKind.QuestionToken); + const questionToken = parseOptionalToken(SyntaxKind.QuestionToken); if (asteriskToken || token === SyntaxKind.OpenParenToken || token === SyntaxKind.LessThanToken) { return parseMethodDeclaration(fullStart, decorators, modifiers, asteriskToken, name, questionToken, Diagnostics.or_expected); } @@ -4767,7 +4766,7 @@ namespace ts { } function parseAccessorDeclaration(kind: SyntaxKind, fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): AccessorDeclaration { - let node = createNode(kind, fullStart); + const node = createNode(kind, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.name = parsePropertyName(); @@ -4859,7 +4858,7 @@ namespace ts { function parseDecorators(): NodeArray { let decorators: NodeArray; while (true) { - let decoratorStart = getNodePos(); + const decoratorStart = getNodePos(); if (!parseOptional(SyntaxKind.AtToken)) { break; } @@ -4869,7 +4868,7 @@ namespace ts { decorators.pos = scanner.getStartPos(); } - let decorator = createNode(SyntaxKind.Decorator, decoratorStart); + const decorator = createNode(SyntaxKind.Decorator, decoratorStart); decorator.expression = doInDecoratorContext(parseLeftHandSideExpressionOrHigher); decorators.push(finishNode(decorator)); } @@ -4883,8 +4882,8 @@ namespace ts { let flags = 0; let modifiers: ModifiersArray; while (true) { - let modifierStart = scanner.getStartPos(); - let modifierKind = token; + const modifierStart = scanner.getStartPos(); + const modifierKind = token; if (!parseAnyContextualModifier()) { break; @@ -4909,8 +4908,8 @@ namespace ts { let flags = 0; let modifiers: ModifiersArray; if (token === SyntaxKind.AsyncKeyword) { - let modifierStart = scanner.getStartPos(); - let modifierKind = token; + const modifierStart = scanner.getStartPos(); + const modifierKind = token; nextToken(); modifiers = []; modifiers.pos = modifierStart; @@ -4925,16 +4924,16 @@ namespace ts { function parseClassElement(): ClassElement { if (token === SyntaxKind.SemicolonToken) { - let result = createNode(SyntaxKind.SemicolonClassElement); + const result = createNode(SyntaxKind.SemicolonClassElement); nextToken(); return finishNode(result); } - let fullStart = getNodePos(); - let decorators = parseDecorators(); - let modifiers = parseModifiers(); + const fullStart = getNodePos(); + const decorators = parseDecorators(); + const modifiers = parseModifiers(); - let accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); + const accessor = tryParseAccessorDeclaration(fullStart, decorators, modifiers); if (accessor) { return accessor; } @@ -4960,7 +4959,7 @@ namespace ts { if (decorators || modifiers) { // treat this as a property declaration with a missing name. - let name = createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); + const name = createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected); return parsePropertyDeclaration(fullStart, decorators, modifiers, name, /*questionToken*/ undefined); } @@ -4981,7 +4980,7 @@ namespace ts { } function parseClassDeclarationOrExpression(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, kind: SyntaxKind): ClassLikeDeclaration { - let node = createNode(kind, fullStart); + const node = createNode(kind, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.ClassKeyword); @@ -5034,7 +5033,7 @@ namespace ts { function parseHeritageClause() { if (token === SyntaxKind.ExtendsKeyword || token === SyntaxKind.ImplementsKeyword) { - let node = createNode(SyntaxKind.HeritageClause); + const node = createNode(SyntaxKind.HeritageClause); node.token = token; nextToken(); node.types = parseDelimitedList(ParsingContext.HeritageClauseElement, parseExpressionWithTypeArguments); @@ -5045,7 +5044,7 @@ namespace ts { } function parseExpressionWithTypeArguments(): ExpressionWithTypeArguments { - let node = createNode(SyntaxKind.ExpressionWithTypeArguments); + const node = createNode(SyntaxKind.ExpressionWithTypeArguments); node.expression = parseLeftHandSideExpressionOrHigher(); if (token === SyntaxKind.LessThanToken) { node.typeArguments = parseBracketedList(ParsingContext.TypeArguments, parseType, SyntaxKind.LessThanToken, SyntaxKind.GreaterThanToken); @@ -5063,7 +5062,7 @@ namespace ts { } function parseInterfaceDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): InterfaceDeclaration { - let node = createNode(SyntaxKind.InterfaceDeclaration, fullStart); + const node = createNode(SyntaxKind.InterfaceDeclaration, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.InterfaceKeyword); @@ -5075,7 +5074,7 @@ namespace ts { } function parseTypeAliasDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): TypeAliasDeclaration { - let node = createNode(SyntaxKind.TypeAliasDeclaration, fullStart); + const node = createNode(SyntaxKind.TypeAliasDeclaration, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.TypeKeyword); @@ -5092,14 +5091,14 @@ namespace ts { // ConstantEnumMemberSection, which starts at the beginning of an enum declaration // or any time an integer literal initializer is encountered. function parseEnumMember(): EnumMember { - let node = createNode(SyntaxKind.EnumMember, scanner.getStartPos()); + const node = createNode(SyntaxKind.EnumMember, scanner.getStartPos()); node.name = parsePropertyName(); node.initializer = allowInAnd(parseNonParameterInitializer); return finishNode(node); } function parseEnumDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): EnumDeclaration { - let node = createNode(SyntaxKind.EnumDeclaration, fullStart); + const node = createNode(SyntaxKind.EnumDeclaration, fullStart); node.decorators = decorators; setModifiers(node, modifiers); parseExpected(SyntaxKind.EnumKeyword); @@ -5115,7 +5114,7 @@ namespace ts { } function parseModuleBlock(): ModuleBlock { - let node = createNode(SyntaxKind.ModuleBlock, scanner.getStartPos()); + const node = createNode(SyntaxKind.ModuleBlock, scanner.getStartPos()); if (parseExpected(SyntaxKind.OpenBraceToken)) { node.statements = parseList(ParsingContext.BlockStatements, parseStatement); parseExpected(SyntaxKind.CloseBraceToken); @@ -5127,10 +5126,10 @@ namespace ts { } function parseModuleOrNamespaceDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray, flags: NodeFlags): ModuleDeclaration { - let node = createNode(SyntaxKind.ModuleDeclaration, fullStart); + const node = createNode(SyntaxKind.ModuleDeclaration, fullStart); // If we are parsing a dotted namespace name, we want to // propagate the 'Namespace' flag across the names if set. - let namespaceFlag = flags & NodeFlags.Namespace; + const namespaceFlag = flags & NodeFlags.Namespace; node.decorators = decorators; setModifiers(node, modifiers); node.flags |= flags; @@ -5142,7 +5141,7 @@ namespace ts { } function parseAmbientExternalModuleDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): ModuleDeclaration { - let node = createNode(SyntaxKind.ModuleDeclaration, fullStart); + const node = createNode(SyntaxKind.ModuleDeclaration, fullStart); node.decorators = decorators; setModifiers(node, modifiers); node.name = parseLiteralNode(/*internName*/ true); @@ -5185,7 +5184,7 @@ namespace ts { function parseImportDeclarationOrImportEqualsDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): ImportEqualsDeclaration | ImportDeclaration { parseExpected(SyntaxKind.ImportKeyword); - let afterImportPos = scanner.getStartPos(); + const afterImportPos = scanner.getStartPos(); let identifier: Identifier; if (isIdentifier()) { @@ -5194,7 +5193,7 @@ namespace ts { // ImportEquals declaration of type: // import x = require("mod"); or // import x = M.x; - let importEqualsDeclaration = createNode(SyntaxKind.ImportEqualsDeclaration, fullStart); + const importEqualsDeclaration = createNode(SyntaxKind.ImportEqualsDeclaration, fullStart); importEqualsDeclaration.decorators = decorators; setModifiers(importEqualsDeclaration, modifiers); importEqualsDeclaration.name = identifier; @@ -5206,7 +5205,7 @@ namespace ts { } // Import statement - let importDeclaration = createNode(SyntaxKind.ImportDeclaration, fullStart); + const importDeclaration = createNode(SyntaxKind.ImportDeclaration, fullStart); importDeclaration.decorators = decorators; setModifiers(importDeclaration, modifiers); @@ -5233,7 +5232,7 @@ namespace ts { // ImportedDefaultBinding, NameSpaceImport // ImportedDefaultBinding, NamedImports - let importClause = createNode(SyntaxKind.ImportClause, fullStart); + const importClause = createNode(SyntaxKind.ImportClause, fullStart); if (identifier) { // ImportedDefaultBinding: // ImportedBinding @@ -5257,7 +5256,7 @@ namespace ts { } function parseExternalModuleReference() { - let node = createNode(SyntaxKind.ExternalModuleReference); + const node = createNode(SyntaxKind.ExternalModuleReference); parseExpected(SyntaxKind.RequireKeyword); parseExpected(SyntaxKind.OpenParenToken); node.expression = parseModuleSpecifier(); @@ -5269,7 +5268,7 @@ namespace ts { // We allow arbitrary expressions here, even though the grammar only allows string // literals. We check to ensure that it is only a string literal later in the grammar // walker. - let result = parseExpression(); + const result = parseExpression(); // Ensure the string being required is in our 'identifier' table. This will ensure // that features like 'find refs' will look inside this file when search for its name. if (result.kind === SyntaxKind.StringLiteral) { @@ -5281,7 +5280,7 @@ namespace ts { function parseNamespaceImport(): NamespaceImport { // NameSpaceImport: // * as ImportedBinding - let namespaceImport = createNode(SyntaxKind.NamespaceImport); + const namespaceImport = createNode(SyntaxKind.NamespaceImport); parseExpected(SyntaxKind.AsteriskToken); parseExpected(SyntaxKind.AsKeyword); namespaceImport.name = parseIdentifier(); @@ -5289,7 +5288,7 @@ namespace ts { } function parseNamedImportsOrExports(kind: SyntaxKind): NamedImportsOrExports { - let node = createNode(kind); + const node = createNode(kind); // NamedImports: // { } @@ -5314,7 +5313,7 @@ namespace ts { } function parseImportOrExportSpecifier(kind: SyntaxKind): ImportOrExportSpecifier { - let node = createNode(kind); + const node = createNode(kind); // ImportSpecifier: // BindingIdentifier // IdentifierName as BindingIdentifier @@ -5324,7 +5323,7 @@ namespace ts { let checkIdentifierIsKeyword = isKeyword(token) && !isIdentifier(); let checkIdentifierStart = scanner.getTokenPos(); let checkIdentifierEnd = scanner.getTextPos(); - let identifierName = parseIdentifierName(); + const identifierName = parseIdentifierName(); if (token === SyntaxKind.AsKeyword) { node.propertyName = identifierName; parseExpected(SyntaxKind.AsKeyword); @@ -5344,7 +5343,7 @@ namespace ts { } function parseExportDeclaration(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): ExportDeclaration { - let node = createNode(SyntaxKind.ExportDeclaration, fullStart); + const node = createNode(SyntaxKind.ExportDeclaration, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(SyntaxKind.AsteriskToken)) { @@ -5367,7 +5366,7 @@ namespace ts { } function parseExportAssignment(fullStart: number, decorators: NodeArray, modifiers: ModifiersArray): ExportAssignment { - let node = createNode(SyntaxKind.ExportAssignment, fullStart); + const node = createNode(SyntaxKind.ExportAssignment, fullStart); node.decorators = decorators; setModifiers(node, modifiers); if (parseOptional(SyntaxKind.EqualsToken)) { @@ -5382,16 +5381,16 @@ namespace ts { } function processReferenceComments(sourceFile: SourceFile): void { - let triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/false, LanguageVariant.Standard, sourceText); - let referencedFiles: FileReference[] = []; - let amdDependencies: { path: string; name: string }[] = []; + const triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/false, LanguageVariant.Standard, sourceText); + const referencedFiles: FileReference[] = []; + const amdDependencies: { path: string; name: string }[] = []; let amdModuleName: string; // Keep scanning all the leading trivia in the file until we get to something that // isn't trivia. Any single line comment will be analyzed to see if it is a // reference comment. while (true) { - let kind = triviaScanner.scan(); + const kind = triviaScanner.scan(); if (kind === SyntaxKind.WhitespaceTrivia || kind === SyntaxKind.NewLineTrivia || kind === SyntaxKind.MultiLineCommentTrivia) { continue; } @@ -5399,14 +5398,14 @@ namespace ts { break; } - let range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() }; + const range = { pos: triviaScanner.getTokenPos(), end: triviaScanner.getTextPos(), kind: triviaScanner.getToken() }; - let comment = sourceText.substring(range.pos, range.end); - let referencePathMatchResult = getFileReferenceFromReferencePath(comment, range); + const comment = sourceText.substring(range.pos, range.end); + const referencePathMatchResult = getFileReferenceFromReferencePath(comment, range); if (referencePathMatchResult) { - let fileReference = referencePathMatchResult.fileReference; + const fileReference = referencePathMatchResult.fileReference; sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib; - let diagnosticMessage = referencePathMatchResult.diagnosticMessage; + const diagnosticMessage = referencePathMatchResult.diagnosticMessage; if (fileReference) { referencedFiles.push(fileReference); } @@ -5415,8 +5414,8 @@ namespace ts { } } else { - let amdModuleNameRegEx = /^\/\/\/\s*createNode(SyntaxKind.JSDocTypeExpression); + const result = createNode(SyntaxKind.JSDocTypeExpression); parseExpected(SyntaxKind.OpenBraceToken); result.type = parseJSDocTopLevelType(); @@ -5541,13 +5540,13 @@ namespace ts { function parseJSDocTopLevelType(): JSDocType { let type = parseJSDocType(); if (token === SyntaxKind.BarToken) { - let unionType = createNode(SyntaxKind.JSDocUnionType, type.pos); + const unionType = createNode(SyntaxKind.JSDocUnionType, type.pos); unionType.types = parseJSDocTypeList(type); type = finishNode(unionType); } if (token === SyntaxKind.EqualsToken) { - let optionalType = createNode(SyntaxKind.JSDocOptionalType, type.pos); + const optionalType = createNode(SyntaxKind.JSDocOptionalType, type.pos); nextToken(); optionalType.type = type; type = finishNode(optionalType); @@ -5561,7 +5560,7 @@ namespace ts { while (true) { if (token === SyntaxKind.OpenBracketToken) { - let arrayType = createNode(SyntaxKind.JSDocArrayType, type.pos); + const arrayType = createNode(SyntaxKind.JSDocArrayType, type.pos); arrayType.elementType = type; nextToken(); @@ -5570,14 +5569,14 @@ namespace ts { type = finishNode(arrayType); } else if (token === SyntaxKind.QuestionToken) { - let nullableType = createNode(SyntaxKind.JSDocNullableType, type.pos); + const nullableType = createNode(SyntaxKind.JSDocNullableType, type.pos); nullableType.type = type; nextToken(); type = finishNode(nullableType); } else if (token === SyntaxKind.ExclamationToken) { - let nonNullableType = createNode(SyntaxKind.JSDocNonNullableType, type.pos); + const nonNullableType = createNode(SyntaxKind.JSDocNonNullableType, type.pos); nonNullableType.type = type; nextToken(); @@ -5626,7 +5625,7 @@ namespace ts { } function parseJSDocThisType(): JSDocThisType { - let result = createNode(SyntaxKind.JSDocThisType); + const result = createNode(SyntaxKind.JSDocThisType); nextToken(); parseExpected(SyntaxKind.ColonToken); result.type = parseJSDocType(); @@ -5634,7 +5633,7 @@ namespace ts { } function parseJSDocConstructorType(): JSDocConstructorType { - let result = createNode(SyntaxKind.JSDocConstructorType); + const result = createNode(SyntaxKind.JSDocConstructorType); nextToken(); parseExpected(SyntaxKind.ColonToken); result.type = parseJSDocType(); @@ -5642,14 +5641,14 @@ namespace ts { } function parseJSDocVariadicType(): JSDocVariadicType { - let result = createNode(SyntaxKind.JSDocVariadicType); + const result = createNode(SyntaxKind.JSDocVariadicType); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocFunctionType(): JSDocFunctionType { - let result = createNode(SyntaxKind.JSDocFunctionType); + const result = createNode(SyntaxKind.JSDocFunctionType); nextToken(); parseExpected(SyntaxKind.OpenParenToken); @@ -5666,20 +5665,20 @@ namespace ts { } function parseJSDocParameter(): ParameterDeclaration { - let parameter = createNode(SyntaxKind.Parameter); + const parameter = createNode(SyntaxKind.Parameter); parameter.type = parseJSDocType(); return finishNode(parameter); } function parseJSDocOptionalType(type: JSDocType): JSDocOptionalType { - let result = createNode(SyntaxKind.JSDocOptionalType, type.pos); + const result = createNode(SyntaxKind.JSDocOptionalType, type.pos); nextToken(); result.type = type; return finishNode(result); } function parseJSDocTypeReference(): JSDocTypeReference { - let result = createNode(SyntaxKind.JSDocTypeReference); + const result = createNode(SyntaxKind.JSDocTypeReference); result.name = parseSimplePropertyName(); while (parseOptional(SyntaxKind.DotToken)) { @@ -5698,7 +5697,7 @@ namespace ts { function parseTypeArguments() { // Move past the < nextToken(); - let typeArguments = parseDelimitedList(ParsingContext.JSDocTypeArguments, parseJSDocType); + const typeArguments = parseDelimitedList(ParsingContext.JSDocTypeArguments, parseJSDocType); checkForTrailingComma(typeArguments); checkForEmptyTypeArgumentList(typeArguments); parseExpected(SyntaxKind.GreaterThanToken); @@ -5708,14 +5707,14 @@ namespace ts { function checkForEmptyTypeArgumentList(typeArguments: NodeArray) { if (parseDiagnostics.length === 0 && typeArguments && typeArguments.length === 0) { - let start = typeArguments.pos - "<".length; - let end = skipTrivia(sourceText, typeArguments.end) + ">".length; + const start = typeArguments.pos - "<".length; + const end = skipTrivia(sourceText, typeArguments.end) + ">".length; return parseErrorAtPosition(start, end - start, Diagnostics.Type_argument_list_cannot_be_empty); } } function parseQualifiedName(left: EntityName): QualifiedName { - let result = createNode(SyntaxKind.QualifiedName, left.pos); + const result = createNode(SyntaxKind.QualifiedName, left.pos); result.left = left; result.right = parseIdentifierName(); @@ -5723,7 +5722,7 @@ namespace ts { } function parseJSDocRecordType(): JSDocRecordType { - let result = createNode(SyntaxKind.JSDocRecordType); + const result = createNode(SyntaxKind.JSDocRecordType); nextToken(); result.members = parseDelimitedList(ParsingContext.JSDocRecordMembers, parseJSDocRecordMember); checkForTrailingComma(result.members); @@ -5732,7 +5731,7 @@ namespace ts { } function parseJSDocRecordMember(): JSDocRecordMember { - let result = createNode(SyntaxKind.JSDocRecordMember); + const result = createNode(SyntaxKind.JSDocRecordMember); result.name = parseSimplePropertyName(); if (token === SyntaxKind.ColonToken) { @@ -5744,14 +5743,14 @@ namespace ts { } function parseJSDocNonNullableType(): JSDocNonNullableType { - let result = createNode(SyntaxKind.JSDocNonNullableType); + const result = createNode(SyntaxKind.JSDocNonNullableType); nextToken(); result.type = parseJSDocType(); return finishNode(result); } function parseJSDocTupleType(): JSDocTupleType { - let result = createNode(SyntaxKind.JSDocTupleType); + const result = createNode(SyntaxKind.JSDocTupleType); nextToken(); result.types = parseDelimitedList(ParsingContext.JSDocTupleTypes, parseJSDocType); checkForTrailingComma(result.types); @@ -5762,13 +5761,13 @@ namespace ts { function checkForTrailingComma(list: NodeArray) { if (parseDiagnostics.length === 0 && list.hasTrailingComma) { - let start = list.end - ",".length; + const start = list.end - ",".length; parseErrorAtPosition(start, ",".length, Diagnostics.Trailing_comma_not_allowed); } } function parseJSDocUnionType(): JSDocUnionType { - let result = createNode(SyntaxKind.JSDocUnionType); + const result = createNode(SyntaxKind.JSDocUnionType); nextToken(); result.types = parseJSDocTypeList(parseJSDocType()); @@ -5780,7 +5779,7 @@ namespace ts { function parseJSDocTypeList(firstType: JSDocType) { Debug.assert(!!firstType); - let types = >[]; + const types = >[]; types.pos = firstType.pos; types.push(firstType); @@ -5793,13 +5792,13 @@ namespace ts { } function parseJSDocAllType(): JSDocAllType { - let result = createNode(SyntaxKind.JSDocAllType); + const result = createNode(SyntaxKind.JSDocAllType); nextToken(); return finishNode(result); } function parseJSDocUnknownOrNullableType(): JSDocUnknownType | JSDocNullableType { - let pos = scanner.getStartPos(); + const pos = scanner.getStartPos(); // skip the ? nextToken(); @@ -5820,11 +5819,11 @@ namespace ts { token === SyntaxKind.EqualsToken || token === SyntaxKind.BarToken) { - let result = createNode(SyntaxKind.JSDocUnknownType, pos); + const result = createNode(SyntaxKind.JSDocUnknownType, pos); return finishNode(result); } else { - let result = createNode(SyntaxKind.JSDocNullableType, pos); + const result = createNode(SyntaxKind.JSDocNullableType, pos); result.type = parseJSDocType(); return finishNode(result); } @@ -5832,15 +5831,15 @@ namespace ts { export function parseIsolatedJSDocComment(content: string, start: number, length: number) { initializeState("file.js", content, ScriptTarget.Latest, /*_syntaxCursor:*/ undefined); - let jsDocComment = parseJSDocComment(/*parent:*/ undefined, start, length); - let diagnostics = parseDiagnostics; + const jsDocComment = parseJSDocComment(/*parent:*/ undefined, start, length); + const diagnostics = parseDiagnostics; clearState(); return jsDocComment ? { jsDocComment, diagnostics } : undefined; } export function parseJSDocComment(parent: Node, start: number, length: number): JSDocComment { - let comment = parseJSDocCommentWorker(start, length); + const comment = parseJSDocCommentWorker(start, length); if (comment) { fixupParentReferences(comment); comment.parent = parent; @@ -5850,9 +5849,9 @@ namespace ts { } export function parseJSDocCommentWorker(start: number, length: number): JSDocComment { - let content = sourceText; + const content = sourceText; start = start || 0; - let end = length === undefined ? content.length : start + length; + const end = length === undefined ? content.length : start + length; length = end - start; Debug.assert(start >= 0); @@ -5879,7 +5878,7 @@ namespace ts { let seenAsterisk = true; for (pos = start + "/**".length; pos < end; ) { - let ch = content.charCodeAt(pos); + const ch = content.charCodeAt(pos); pos++; if (ch === CharacterCodes.at && canParseTag) { @@ -5929,7 +5928,7 @@ namespace ts { return undefined; } - let result = createNode(SyntaxKind.JSDocComment, start); + const result = createNode(SyntaxKind.JSDocComment, start); result.tags = tags; return finishNode(result, end); } @@ -5942,15 +5941,15 @@ namespace ts { function parseTag(): void { Debug.assert(content.charCodeAt(pos - 1) === CharacterCodes.at); - let atToken = createNode(SyntaxKind.AtToken, pos - 1); + const atToken = createNode(SyntaxKind.AtToken, pos - 1); atToken.end = pos; - let tagName = scanIdentifier(); + const tagName = scanIdentifier(); if (!tagName) { return; } - let tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); + const tag = handleTag(atToken, tagName) || handleUnknownTag(atToken, tagName); addTag(tag); } @@ -5973,7 +5972,7 @@ namespace ts { } function handleUnknownTag(atToken: Node, tagName: Identifier) { - let result = createNode(SyntaxKind.JSDocTag, atToken.pos); + const result = createNode(SyntaxKind.JSDocTag, atToken.pos); result.atToken = atToken; result.tagName = tagName; return finishNode(result, pos); @@ -5998,7 +5997,7 @@ namespace ts { return undefined; } - let typeExpression = parseJSDocTypeExpression(pos, end - pos); + const typeExpression = parseJSDocTypeExpression(pos, end - pos); pos = typeExpression.end; return typeExpression; } @@ -6035,7 +6034,7 @@ namespace ts { typeExpression = tryParseTypeExpression(); } - let result = createNode(SyntaxKind.JSDocParameterTag, atToken.pos); + const result = createNode(SyntaxKind.JSDocParameterTag, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.preParameterName = preName; @@ -6050,7 +6049,7 @@ namespace ts { parseErrorAtPosition(tagName.pos, pos - tagName.pos, Diagnostics._0_tag_already_specified, tagName.text); } - let result = createNode(SyntaxKind.JSDocReturnTag, atToken.pos); + const result = createNode(SyntaxKind.JSDocReturnTag, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); @@ -6062,7 +6061,7 @@ namespace ts { parseErrorAtPosition(tagName.pos, pos - tagName.pos, Diagnostics._0_tag_already_specified, tagName.text); } - let result = createNode(SyntaxKind.JSDocTypeTag, atToken.pos); + const result = createNode(SyntaxKind.JSDocTypeTag, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeExpression = tryParseTypeExpression(); @@ -6074,20 +6073,20 @@ namespace ts { parseErrorAtPosition(tagName.pos, pos - tagName.pos, Diagnostics._0_tag_already_specified, tagName.text); } - let typeParameters = >[]; + const typeParameters = >[]; typeParameters.pos = pos; while (true) { skipWhitespace(); - let startPos = pos; - let name = scanIdentifier(); + const startPos = pos; + const name = scanIdentifier(); if (!name) { parseErrorAtPosition(startPos, 0, Diagnostics.Identifier_expected); return undefined; } - let typeParameter = createNode(SyntaxKind.TypeParameter, name.pos); + const typeParameter = createNode(SyntaxKind.TypeParameter, name.pos); typeParameter.name = name; finishNode(typeParameter, pos); @@ -6103,7 +6102,7 @@ namespace ts { typeParameters.end = pos; - let result = createNode(SyntaxKind.JSDocTemplateTag, atToken.pos); + const result = createNode(SyntaxKind.JSDocTemplateTag, atToken.pos); result.atToken = atToken; result.tagName = tagName; result.typeParameters = typeParameters; @@ -6111,9 +6110,9 @@ namespace ts { } function scanIdentifier(): Identifier { - let startPos = pos; + const startPos = pos; for (; pos < end; pos++) { - let ch = content.charCodeAt(pos); + const ch = content.charCodeAt(pos); if (pos === startPos && isIdentifierStart(ch, ScriptTarget.Latest)) { continue; } @@ -6128,7 +6127,7 @@ namespace ts { return undefined; } - let result = createNode(SyntaxKind.Identifier, startPos); + const result = createNode(SyntaxKind.Identifier, startPos); result.text = content.substring(startPos, pos); return finishNode(result, pos); } @@ -6158,16 +6157,16 @@ namespace ts { // This is because we do incremental parsing in-place. i.e. we take nodes from the old // tree and give them new positions and parents. From that point on, trusting the old // tree at all is not possible as far too much of it may violate invariants. - let incrementalSourceFile = sourceFile; + const incrementalSourceFile = sourceFile; Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed); incrementalSourceFile.hasBeenIncrementallyParsed = true; - let oldText = sourceFile.text; - let syntaxCursor = createSyntaxCursor(sourceFile); + const oldText = sourceFile.text; + const syntaxCursor = createSyntaxCursor(sourceFile); // Make the actual change larger so that we know to reparse anything whose lookahead // might have intersected the change. - let changeRange = extendToAffectedRange(sourceFile, textChangeRange); + const changeRange = extendToAffectedRange(sourceFile, textChangeRange); checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks); // Ensure that extending the affected range only moved the start of the change range @@ -6179,7 +6178,7 @@ namespace ts { // The is the amount the nodes after the edit range need to be adjusted. It can be // positive (if the edit added characters), negative (if the edit deleted characters) // or zero (if this was a pure overwrite with nothing added/removed). - let delta = textChangeRangeNewSpan(changeRange).length - changeRange.span.length; + const delta = textChangeRangeNewSpan(changeRange).length - changeRange.span.length; // If we added or removed characters during the edit, then we need to go and adjust all // the nodes after the edit. Those nodes may move forward (if we inserted chars) or they @@ -6213,7 +6212,7 @@ namespace ts { // inconsistent tree. Setting the parents on the new tree should be very fast. We // will immediately bail out of walking any subtrees when we can see that their parents // are already correct. - let result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true); + const result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /* setParentNode */ true); return result; } @@ -6259,7 +6258,7 @@ namespace ts { array.pos += delta; array.end += delta; - for (let node of array) { + for (const node of array) { visitNode(node); } } @@ -6387,7 +6386,7 @@ namespace ts { // Check if the element intersects the change range. If it does, then it is not // reusable. Also, we'll need to recurse to see what constituent portions we may // be able to use. - let fullEnd = child.end; + const fullEnd = child.end; if (fullEnd >= changeStart) { child.intersectsChange = true; child._children = undefined; @@ -6416,14 +6415,14 @@ namespace ts { // Check if the element intersects the change range. If it does, then it is not // reusable. Also, we'll need to recurse to see what constituent portions we may // be able to use. - let fullEnd = array.end; + const fullEnd = array.end; if (fullEnd >= changeStart) { array.intersectsChange = true; array._children = undefined; // Adjust the pos or end (or both) of the intersecting array accordingly. adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta); - for (let node of array) { + for (const node of array) { visitNode(node); } return; @@ -6445,7 +6444,7 @@ namespace ts { // (as it does not intersect the actual original change range). Because an edit may // change the token touching it, we actually need to look back *at least* one token so // that the prior token sees that change. - let maxLookahead = 1; + const maxLookahead = 1; let start = changeRange.span.start; @@ -6453,15 +6452,15 @@ namespace ts { // the left by maxLookahead tokens. We only need to do this as long as we're not at the // start of the tree. for (let i = 0; start > 0 && i <= maxLookahead; i++) { - let nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); + const nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start); Debug.assert(nearestNode.pos <= start); - let position = nearestNode.pos; + const position = nearestNode.pos; start = Math.max(0, position - 1); } - let finalSpan = createTextSpanFromBounds(start, textSpanEnd(changeRange.span)); - let finalLength = changeRange.newLength + (changeRange.span.start - start); + const finalSpan = createTextSpanFromBounds(start, textSpanEnd(changeRange.span)); + const finalLength = changeRange.newLength + (changeRange.span.start - start); return createTextChangeRange(finalSpan, finalLength); } @@ -6473,7 +6472,7 @@ namespace ts { forEachChild(sourceFile, visit); if (lastNodeEntirelyBeforePosition) { - let lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); + const lastChildOfLastEntireNodeBeforePosition = getLastChild(lastNodeEntirelyBeforePosition); if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) { bestResult = lastChildOfLastEntireNodeBeforePosition; } @@ -6483,7 +6482,7 @@ namespace ts { function getLastChild(node: Node): Node { while (true) { - let lastChild = getLastChildWorker(node); + const lastChild = getLastChildWorker(node); if (lastChild) { node = lastChild; } @@ -6562,17 +6561,17 @@ namespace ts { } function checkChangeRange(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks: boolean) { - let oldText = sourceFile.text; + const oldText = sourceFile.text; if (textChangeRange) { Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length); if (aggressiveChecks || Debug.shouldAssert(AssertionLevel.VeryAggressive)) { - let oldTextPrefix = oldText.substr(0, textChangeRange.span.start); - let newTextPrefix = newText.substr(0, textChangeRange.span.start); + const oldTextPrefix = oldText.substr(0, textChangeRange.span.start); + const newTextPrefix = newText.substr(0, textChangeRange.span.start); Debug.assert(oldTextPrefix === newTextPrefix); - let oldTextSuffix = oldText.substring(textSpanEnd(textChangeRange.span), oldText.length); - let newTextSuffix = newText.substring(textSpanEnd(textChangeRangeNewSpan(textChangeRange)), newText.length); + const oldTextSuffix = oldText.substring(textSpanEnd(textChangeRange.span), oldText.length); + const newTextSuffix = newText.substring(textSpanEnd(textChangeRangeNewSpan(textChangeRange)), newText.length); Debug.assert(oldTextSuffix === newTextSuffix); } } @@ -6674,7 +6673,7 @@ namespace ts { // position was in this array. Search through this array to see if we find a // viable element. for (let i = 0, n = array.length; i < n; i++) { - let child = array[i]; + const child = array[i]; if (child) { if (child.pos === position) { // Found the right node. We're done. diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 254f6b1fe3b..8f807ed7b86 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -10,7 +10,7 @@ namespace ts { /** The version of the TypeScript compiler release */ - let emptyArray: any[] = []; + const emptyArray: any[] = []; export const version = "1.8.0"; @@ -20,7 +20,7 @@ namespace ts { if (fileExists(fileName)) { return fileName; } - let parentPath = getDirectoryPath(searchPath); + const parentPath = getDirectoryPath(searchPath); if (parentPath === searchPath) { break; } @@ -31,13 +31,13 @@ namespace ts { } export function resolveTripleslashReference(moduleName: string, containingFile: string): string { - let basePath = getDirectoryPath(containingFile); - let referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName); + const basePath = getDirectoryPath(containingFile); + const referencedFileName = isRootedDiskPath(moduleName) ? moduleName : combinePaths(basePath, moduleName); return normalizePath(referencedFileName); } export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { - let moduleResolution = compilerOptions.moduleResolution !== undefined + const moduleResolution = compilerOptions.moduleResolution !== undefined ? compilerOptions.moduleResolution : compilerOptions.module === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic; @@ -48,11 +48,11 @@ namespace ts { } export function nodeModuleNameResolver(moduleName: string, containingFile: string, supportedExtensions: string[], host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { - let containingDirectory = getDirectoryPath(containingFile); + const containingDirectory = getDirectoryPath(containingFile); if (getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) { - let failedLookupLocations: string[] = []; - let candidate = normalizePath(combinePaths(containingDirectory, moduleName)); + const failedLookupLocations: string[] = []; + const candidate = normalizePath(combinePaths(containingDirectory, moduleName)); let resolvedFileName = loadNodeModuleFromFile(candidate, supportedExtensions, failedLookupLocations, host); if (resolvedFileName) { @@ -73,7 +73,7 @@ namespace ts { return forEach(supportedExtensions, tryLoad); function tryLoad(ext: string): string { - let fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext; + const fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext; if (host.fileExists(fileName)) { return fileName; } @@ -85,13 +85,13 @@ namespace ts { } function loadNodeModuleFromDirectory(candidate: string, supportedExtensions: string[], failedLookupLocation: string[], host: ModuleResolutionHost): string { - let packageJsonPath = combinePaths(candidate, "package.json"); + const packageJsonPath = combinePaths(candidate, "package.json"); if (host.fileExists(packageJsonPath)) { let jsonContent: { typings?: string }; try { - let jsonText = host.readFile(packageJsonPath); + const jsonText = host.readFile(packageJsonPath); jsonContent = jsonText ? <{ typings?: string }>JSON.parse(jsonText) : { typings: undefined }; } catch (e) { @@ -100,7 +100,7 @@ namespace ts { } if (jsonContent.typings) { - let result = loadNodeModuleFromFile(normalizePath(combinePaths(candidate, jsonContent.typings)), supportedExtensions, failedLookupLocation, host); + const result = loadNodeModuleFromFile(normalizePath(combinePaths(candidate, jsonContent.typings)), supportedExtensions, failedLookupLocation, host); if (result) { return result; } @@ -115,13 +115,13 @@ namespace ts { } function loadModuleFromNodeModules(moduleName: string, directory: string, supportedExtensions: string[], host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations { - let failedLookupLocations: string[] = []; + const failedLookupLocations: string[] = []; directory = normalizeSlashes(directory); while (true) { - let baseName = getBaseFileName(directory); + const baseName = getBaseFileName(directory); if (baseName !== "node_modules") { - let nodeModulesFolder = combinePaths(directory, "node_modules"); - let candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName)); + const nodeModulesFolder = combinePaths(directory, "node_modules"); + const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName)); let result = loadNodeModuleFromFile(candidate, supportedExtensions, failedLookupLocations, host); if (result) { return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations }; @@ -133,7 +133,7 @@ namespace ts { } } - let parentPath = getDirectoryPath(directory); + const parentPath = getDirectoryPath(directory); if (parentPath === directory) { break; } @@ -145,7 +145,7 @@ namespace ts { } function nameStartsWithDotSlashOrDotDotSlash(name: string) { - let i = name.lastIndexOf("./", 1); + const i = name.lastIndexOf("./", 1); return i === 0 || (i === 1 && name.charCodeAt(0) === CharacterCodes.dot); } @@ -159,7 +159,7 @@ namespace ts { let searchPath = getDirectoryPath(containingFile); let searchName: string; - let failedLookupLocations: string[] = []; + const failedLookupLocations: string[] = []; let referencedSourceFile: string; while (true) { @@ -171,7 +171,7 @@ namespace ts { return undefined; } - let candidate = searchName + extension; + const candidate = searchName + extension; if (host.fileExists(candidate)) { return candidate; } @@ -184,7 +184,7 @@ namespace ts { break; } - let parentPath = getDirectoryPath(searchPath); + const parentPath = getDirectoryPath(searchPath); if (parentPath === searchPath) { break; } @@ -199,15 +199,13 @@ namespace ts { /* @internal */ export const defaultInitCompilerOptions: CompilerOptions = { module: ModuleKind.CommonJS, - target: ScriptTarget.ES3, + target: ScriptTarget.ES5, noImplicitAny: false, - outDir: "built", - rootDir: ".", sourceMap: false, }; export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost { - let existingDirectories: Map = {}; + const existingDirectories: Map = {}; function getCanonicalFileName(fileName: string): string { // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. @@ -216,12 +214,12 @@ namespace ts { } // returned by CScript sys environment - let unsupportedFileEncodingErrorCode = -2147024809; + const unsupportedFileEncodingErrorCode = -2147024809; function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile { let text: string; try { - let start = new Date().getTime(); + const start = new Date().getTime(); text = sys.readFile(fileName, options.charset); ioReadTime += new Date().getTime() - start; } @@ -250,7 +248,7 @@ namespace ts { function ensureDirectoriesExist(directoryPath: string) { if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) { - let parentDirectory = getDirectoryPath(directoryPath); + const parentDirectory = getDirectoryPath(directoryPath); ensureDirectoriesExist(parentDirectory); sys.createDirectory(directoryPath); } @@ -258,7 +256,7 @@ namespace ts { function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) { try { - let start = new Date().getTime(); + const start = new Date().getTime(); ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName))); sys.writeFile(fileName, data, writeByteOrderMark); ioWriteTime += new Date().getTime() - start; @@ -286,7 +284,7 @@ namespace ts { } export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[] { - let diagnostics = program.getOptionsDiagnostics().concat( + let diagnostics = program.getOptionsDiagnostics(cancellationToken).concat( program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); @@ -328,8 +326,8 @@ namespace ts { let program: Program; let files: SourceFile[] = []; let fileProcessingDiagnostics = createDiagnosticCollection(); - let programDiagnostics = createDiagnosticCollection(); - let emitBlockingDiagnostics = createDiagnosticCollection(); + const programDiagnostics = createDiagnosticCollection(); + const emitBlockingDiagnostics = createDiagnosticCollection(); let commonSourceDirectory: string; let diagnosticsProducingTypeChecker: TypeChecker; @@ -337,28 +335,28 @@ namespace ts { let classifiableNames: Map; let skipDefaultLib = options.noLib; - let supportedExtensions = getSupportedExtensions(options); + const supportedExtensions = getSupportedExtensions(options); - let start = new Date().getTime(); + const start = new Date().getTime(); host = host || createCompilerHost(options); // Map storing if there is emit blocking diagnostics for given input - let hasEmitBlockingDiagnostics = createFileMap(!host.useCaseSensitiveFileNames() ? key => key.toLocaleLowerCase() : undefined); + const hasEmitBlockingDiagnostics = createFileMap(!host.useCaseSensitiveFileNames() ? key => key.toLocaleLowerCase() : undefined); const currentDirectory = host.getCurrentDirectory(); const resolveModuleNamesWorker = host.resolveModuleNames ? ((moduleNames: string[], containingFile: string) => host.resolveModuleNames(moduleNames, containingFile)) : ((moduleNames: string[], containingFile: string) => map(moduleNames, moduleName => resolveModuleName(moduleName, containingFile, options, host).resolvedModule)); - let filesByName = createFileMap(); + const filesByName = createFileMap(); // stores 'filename -> file association' ignoring case // used to track cases when two file names differ only in casing - let filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createFileMap(fileName => fileName.toLowerCase()) : undefined; + const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createFileMap(fileName => fileName.toLowerCase()) : undefined; if (oldProgram) { // check properties that can affect structure of the program or module resolution strategy // if any of these properties has changed - structure cannot be reused - let oldOptions = oldProgram.getCompilerOptions(); + const oldOptions = oldProgram.getCompilerOptions(); if ((oldOptions.module !== options.module) || (oldOptions.noResolve !== options.noResolve) || (oldOptions.target !== options.target) || @@ -418,7 +416,7 @@ namespace ts { getTypeChecker(); classifiableNames = {}; - for (let sourceFile of files) { + for (const sourceFile of files) { copyMap(sourceFile.classifiableNames, classifiableNames); } } @@ -434,17 +432,17 @@ namespace ts { Debug.assert(!oldProgram.structureIsReused); // there is an old program, check if we can reuse its structure - let oldRootNames = oldProgram.getRootFileNames(); + const oldRootNames = oldProgram.getRootFileNames(); if (!arrayIsEqualTo(oldRootNames, rootNames)) { return false; } // check if program source files has changed in the way that can affect structure of the program - let newSourceFiles: SourceFile[] = []; - let filePaths: Path[] = []; - let modifiedSourceFiles: SourceFile[] = []; + const newSourceFiles: SourceFile[] = []; + const filePaths: Path[] = []; + const modifiedSourceFiles: SourceFile[] = []; - for (let oldSourceFile of oldProgram.getSourceFiles()) { + for (const oldSourceFile of oldProgram.getSourceFiles()) { let newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target); if (!newSourceFile) { return false; @@ -474,13 +472,13 @@ namespace ts { } if (resolveModuleNamesWorker) { - let moduleNames = map(newSourceFile.imports, name => name.text); - let resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); + const moduleNames = map(newSourceFile.imports, name => name.text); + const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory)); // ensure that module resolution results are still correct for (let i = 0; i < moduleNames.length; ++i) { - let newResolution = resolutions[i]; - let oldResolution = getResolvedModule(oldSourceFile, moduleNames[i]); - let resolutionChanged = oldResolution + const newResolution = resolutions[i]; + const oldResolution = getResolvedModule(oldSourceFile, moduleNames[i]); + const resolutionChanged = oldResolution ? !newResolution || oldResolution.resolvedFileName !== newResolution.resolvedFileName || !!oldResolution.isExternalLibraryImport !== !!newResolution.isExternalLibraryImport @@ -512,7 +510,7 @@ namespace ts { files = newSourceFiles; fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics(); - for (let modifiedFile of modifiedSourceFiles) { + for (const modifiedFile of modifiedSourceFiles) { fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile); } oldProgram.structureIsReused = true; @@ -567,11 +565,11 @@ namespace ts { // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. - let emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); + const emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); - let start = new Date().getTime(); + const start = new Date().getTime(); - let emitResult = emitFiles( + const emitResult = emitFiles( emitResolver, getEmitHost(writeFileCallback), sourceFile); @@ -592,7 +590,7 @@ namespace ts { return getDiagnostics(sourceFile, cancellationToken); } - let allDiagnostics: Diagnostic[] = []; + const allDiagnostics: Diagnostic[] = []; forEach(program.getSourceFiles(), sourceFile => { if (cancellationToken) { cancellationToken.throwIfCancellationRequested(); @@ -651,13 +649,13 @@ namespace ts { } return runWithCancellationToken(() => { - let typeChecker = getDiagnosticsProducingTypeChecker(); + const typeChecker = getDiagnosticsProducingTypeChecker(); Debug.assert(!!sourceFile.bindDiagnostics); - let bindDiagnostics = sourceFile.bindDiagnostics; - let checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); - let fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); - let programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); + const bindDiagnostics = sourceFile.bindDiagnostics; + const checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken); + const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName); + const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName); return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile); }); @@ -665,7 +663,7 @@ namespace ts { function getJavaScriptSemanticDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { - let diagnostics: Diagnostic[] = []; + const diagnostics: Diagnostic[] = []; walk(sourceFile); return diagnostics; @@ -714,7 +712,7 @@ namespace ts { case SyntaxKind.FunctionDeclaration: case SyntaxKind.ArrowFunction: case SyntaxKind.FunctionDeclaration: - let functionDeclaration = node; + const functionDeclaration = node; if (checkModifiers(functionDeclaration.modifiers) || checkTypeParameters(functionDeclaration.typeParameters) || checkTypeAnnotation(functionDeclaration.type)) { @@ -722,31 +720,31 @@ namespace ts { } break; case SyntaxKind.VariableStatement: - let variableStatement = node; + const variableStatement = node; if (checkModifiers(variableStatement.modifiers)) { return true; } break; case SyntaxKind.VariableDeclaration: - let variableDeclaration = node; + const variableDeclaration = node; if (checkTypeAnnotation(variableDeclaration.type)) { return true; } break; case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: - let expression = node; + const expression = node; if (expression.typeArguments && expression.typeArguments.length > 0) { - let start = expression.typeArguments.pos; + const start = expression.typeArguments.pos; diagnostics.push(createFileDiagnostic(sourceFile, start, expression.typeArguments.end - start, Diagnostics.type_arguments_can_only_be_used_in_a_ts_file)); return true; } break; case SyntaxKind.Parameter: - let parameter = node; + const parameter = node; if (parameter.modifiers) { - let start = parameter.modifiers.pos; + const start = parameter.modifiers.pos; diagnostics.push(createFileDiagnostic(sourceFile, start, parameter.modifiers.end - start, Diagnostics.parameter_modifiers_can_only_be_used_in_a_ts_file)); return true; @@ -780,7 +778,7 @@ namespace ts { function checkTypeParameters(typeParameters: NodeArray): boolean { if (typeParameters) { - let start = typeParameters.pos; + const start = typeParameters.pos; diagnostics.push(createFileDiagnostic(sourceFile, start, typeParameters.end - start, Diagnostics.type_parameter_declarations_can_only_be_used_in_a_ts_file)); return true; } @@ -798,7 +796,7 @@ namespace ts { function checkModifiers(modifiers: ModifiersArray): boolean { if (modifiers) { - for (let modifier of modifiers) { + for (const modifier of modifiers) { switch (modifier.kind) { case SyntaxKind.PublicKeyword: case SyntaxKind.PrivateKeyword: @@ -825,16 +823,16 @@ namespace ts { function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { if (!isDeclarationFile(sourceFile)) { - let resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); + const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); // Don't actually write any files since we're just getting diagnostics. - let writeFile: WriteFileCallback = () => { }; + const writeFile: WriteFileCallback = () => { }; return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); } }); } function getOptionsDiagnostics(): Diagnostic[] { - let allDiagnostics: Diagnostic[] = []; + const allDiagnostics: Diagnostic[] = []; addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics()); addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics()); addRange(allDiagnostics, emitBlockingDiagnostics.getGlobalDiagnostics()); @@ -842,7 +840,7 @@ namespace ts { } function getGlobalDiagnostics(): Diagnostic[] { - let allDiagnostics: Diagnostic[] = []; + const allDiagnostics: Diagnostic[] = []; addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics()); return sortAndDeduplicateDiagnostics(allDiagnostics); } @@ -869,7 +867,7 @@ namespace ts { } let imports: LiteralExpression[]; - for (let node of file.statements) { + for (const node of file.statements) { collect(node, /* allowRelativeModuleNames */ true); } @@ -929,7 +927,7 @@ namespace ts { } } else { - let nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); + const nonTsFile: SourceFile = options.allowNonTsExtensions && findSourceFile(fileName, toPath(fileName, currentDirectory, getCanonicalFileName), isDefaultLib, refFile, refPos, refEnd); if (!nonTsFile) { if (options.allowNonTsExtensions) { diagnostic = Diagnostics.File_0_not_found; @@ -978,7 +976,7 @@ namespace ts { } // We haven't looked for this file, do so now and cache result - let file = host.getSourceFile(fileName, options.target, hostErrorMessage => { + const file = host.getSourceFile(fileName, options.target, hostErrorMessage => { if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) { fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage)); @@ -1005,7 +1003,7 @@ namespace ts { skipDefaultLib = skipDefaultLib || file.hasNoDefaultLib; - let basePath = getDirectoryPath(fileName); + const basePath = getDirectoryPath(fileName); if (!options.noResolve) { processReferencedFiles(file, basePath); } @@ -1027,7 +1025,7 @@ namespace ts { function processReferencedFiles(file: SourceFile, basePath: string) { forEach(file.referencedFiles, ref => { - let referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); + const referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName); processSourceFile(referencedFileName, /* isDefaultLib */ false, file, ref.pos, ref.end); }); } @@ -1040,21 +1038,21 @@ namespace ts { collectExternalModuleReferences(file); if (file.imports.length) { file.resolvedModules = {}; - let moduleNames = map(file.imports, name => name.text); - let resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory)); + const moduleNames = map(file.imports, name => name.text); + const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory)); for (let i = 0; i < file.imports.length; ++i) { - let resolution = resolutions[i]; + const resolution = resolutions[i]; setResolvedModule(file, moduleNames[i], resolution); if (resolution && !options.noResolve) { const importedFile = findSourceFile(resolution.resolvedFileName, toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /* isDefaultLib */ false, file, skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); if (importedFile && resolution.isExternalLibraryImport) { if (!isExternalModule(importedFile)) { - let start = getTokenPosOfNode(file.imports[i], file); + const start = getTokenPosOfNode(file.imports[i], file); fileProcessingDiagnostics.add(createFileDiagnostic(file, start, file.imports[i].end - start, Diagnostics.Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_the_package_definition, importedFile.fileName)); } else if (importedFile.referencedFiles.length) { - let firstRef = importedFile.referencedFiles[0]; + const firstRef = importedFile.referencedFiles[0]; fileProcessingDiagnostics.add(createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition)); } } @@ -1076,7 +1074,7 @@ namespace ts { return; } - let sourcePathComponents = getNormalizedPathComponents(sourceFile.fileName, currentDirectory); + const sourcePathComponents = getNormalizedPathComponents(sourceFile.fileName, currentDirectory); sourcePathComponents.pop(); // The base file name is not part of the common directory path if (!commonPathComponents) { @@ -1110,11 +1108,11 @@ namespace ts { function checkSourceFilesBelongToPath(sourceFiles: SourceFile[], rootDirectory: string): boolean { let allFilesBelongToPath = true; if (sourceFiles) { - let absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory)); + const absoluteRootDirectoryPath = host.getCanonicalFileName(getNormalizedAbsolutePath(rootDirectory, currentDirectory)); for (var sourceFile of sourceFiles) { if (!isDeclarationFile(sourceFile)) { - let absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); + const absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir)); allFilesBelongToPath = false; @@ -1179,24 +1177,24 @@ namespace ts { return; } - let languageVersion = options.target || ScriptTarget.ES3; - let outFile = options.outFile || options.out; + const languageVersion = options.target || ScriptTarget.ES3; + const outFile = options.outFile || options.out; - let firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined); + const firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined); if (options.isolatedModules) { if (!options.module && languageVersion < ScriptTarget.ES6) { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher)); } - let firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); + const firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined); if (firstNonExternalModuleSourceFile) { - let span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); + const span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile); programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided)); } } else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && !options.module) { // We cannot use createDiagnosticFromNode because nodes do not have parents yet - let span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); + const span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator); programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided)); } @@ -1257,8 +1255,8 @@ namespace ts { // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files if (!options.noEmit) { - let emitHost = getEmitHost(); - let emitFilesSeen = createFileMap(!host.useCaseSensitiveFileNames() ? key => key.toLocaleLowerCase() : undefined); + const emitHost = getEmitHost(); + const emitFilesSeen = createFileMap(!host.useCaseSensitiveFileNames() ? key => key.toLocaleLowerCase() : undefined); forEachExpectedEmitFile(emitHost, (emitFileNames, sourceFiles, isBundledEmit) => { verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen); verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen); @@ -1268,7 +1266,7 @@ namespace ts { // Verify that all the emit files are unique and dont overwrite input files function verifyEmitFilePath(emitFileName: string, emitFilesSeen: FileMap) { if (emitFileName) { - let emitFilePath = toPath(emitFileName, currentDirectory, getCanonicalFileName); + const emitFilePath = toPath(emitFileName, currentDirectory, getCanonicalFileName); // Report error if the output overwrites input file if (forEach(files, file => toPath(file.fileName, currentDirectory, getCanonicalFileName) === emitFilePath)) { createEmitBlockingDiagnostics(emitFileName, Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file); diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.ts index a827d755302..4e11e0d6b99 100644 --- a/src/compiler/scanner.ts +++ b/src/compiler/scanner.ts @@ -49,7 +49,7 @@ namespace ts { tryScan(callback: () => T): T; } - let textToToken: Map = { + const textToToken: Map = { "abstract": SyntaxKind.AbstractKeyword, "any": SyntaxKind.AnyKeyword, "as": SyntaxKind.AsKeyword, @@ -191,8 +191,8 @@ namespace ts { Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at: http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt */ - let unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; - let unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + const unicodeES3IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1610, 1649, 1747, 1749, 1749, 1765, 1766, 1786, 1788, 1808, 1808, 1810, 1836, 1920, 1957, 2309, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2784, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3294, 3294, 3296, 3297, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3424, 3425, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3805, 3840, 3840, 3904, 3911, 3913, 3946, 3976, 3979, 4096, 4129, 4131, 4135, 4137, 4138, 4176, 4181, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6067, 6176, 6263, 6272, 6312, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8319, 8319, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12346, 12353, 12436, 12445, 12446, 12449, 12538, 12540, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65138, 65140, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + const unicodeES3IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 543, 546, 563, 592, 685, 688, 696, 699, 705, 720, 721, 736, 740, 750, 750, 768, 846, 864, 866, 890, 890, 902, 902, 904, 906, 908, 908, 910, 929, 931, 974, 976, 983, 986, 1011, 1024, 1153, 1155, 1158, 1164, 1220, 1223, 1224, 1227, 1228, 1232, 1269, 1272, 1273, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1441, 1443, 1465, 1467, 1469, 1471, 1471, 1473, 1474, 1476, 1476, 1488, 1514, 1520, 1522, 1569, 1594, 1600, 1621, 1632, 1641, 1648, 1747, 1749, 1756, 1759, 1768, 1770, 1773, 1776, 1788, 1808, 1836, 1840, 1866, 1920, 1968, 2305, 2307, 2309, 2361, 2364, 2381, 2384, 2388, 2392, 2403, 2406, 2415, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2492, 2494, 2500, 2503, 2504, 2507, 2509, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2562, 2562, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2649, 2652, 2654, 2654, 2662, 2676, 2689, 2691, 2693, 2699, 2701, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2784, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2870, 2873, 2876, 2883, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2913, 2918, 2927, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 2997, 2999, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3031, 3031, 3047, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3134, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3168, 3169, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3262, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3297, 3302, 3311, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3368, 3370, 3385, 3390, 3395, 3398, 3400, 3402, 3405, 3415, 3415, 3424, 3425, 3430, 3439, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3805, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3946, 3953, 3972, 3974, 3979, 3984, 3991, 3993, 4028, 4038, 4038, 4096, 4129, 4131, 4135, 4137, 4138, 4140, 4146, 4150, 4153, 4160, 4169, 4176, 4185, 4256, 4293, 4304, 4342, 4352, 4441, 4447, 4514, 4520, 4601, 4608, 4614, 4616, 4678, 4680, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4742, 4744, 4744, 4746, 4749, 4752, 4782, 4784, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4814, 4816, 4822, 4824, 4846, 4848, 4878, 4880, 4880, 4882, 4885, 4888, 4894, 4896, 4934, 4936, 4954, 4969, 4977, 5024, 5108, 5121, 5740, 5743, 5750, 5761, 5786, 5792, 5866, 6016, 6099, 6112, 6121, 6160, 6169, 6176, 6263, 6272, 6313, 7680, 7835, 7840, 7929, 7936, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8255, 8256, 8319, 8319, 8400, 8412, 8417, 8417, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8497, 8499, 8505, 8544, 8579, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12346, 12353, 12436, 12441, 12442, 12445, 12446, 12449, 12542, 12549, 12588, 12593, 12686, 12704, 12727, 13312, 19893, 19968, 40869, 40960, 42124, 44032, 55203, 63744, 64045, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65056, 65059, 65075, 65076, 65101, 65103, 65136, 65138, 65140, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65381, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; /* As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers @@ -216,8 +216,8 @@ namespace ts { Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at: http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt */ - let unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; - let unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + const unicodeES5IdentifierStart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 880, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1488, 1514, 1520, 1522, 1568, 1610, 1646, 1647, 1649, 1747, 1749, 1749, 1765, 1766, 1774, 1775, 1786, 1788, 1791, 1791, 1808, 1808, 1810, 1839, 1869, 1957, 1969, 1969, 1994, 2026, 2036, 2037, 2042, 2042, 2048, 2069, 2074, 2074, 2084, 2084, 2088, 2088, 2112, 2136, 2208, 2208, 2210, 2220, 2308, 2361, 2365, 2365, 2384, 2384, 2392, 2401, 2417, 2423, 2425, 2431, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2493, 2493, 2510, 2510, 2524, 2525, 2527, 2529, 2544, 2545, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2649, 2652, 2654, 2654, 2674, 2676, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2749, 2749, 2768, 2768, 2784, 2785, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2877, 2877, 2908, 2909, 2911, 2913, 2929, 2929, 2947, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3024, 3024, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3133, 3160, 3161, 3168, 3169, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3261, 3261, 3294, 3294, 3296, 3297, 3313, 3314, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3389, 3406, 3406, 3424, 3425, 3450, 3455, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3585, 3632, 3634, 3635, 3648, 3654, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3760, 3762, 3763, 3773, 3773, 3776, 3780, 3782, 3782, 3804, 3807, 3840, 3840, 3904, 3911, 3913, 3948, 3976, 3980, 4096, 4138, 4159, 4159, 4176, 4181, 4186, 4189, 4193, 4193, 4197, 4198, 4206, 4208, 4213, 4225, 4238, 4238, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5905, 5920, 5937, 5952, 5969, 5984, 5996, 5998, 6000, 6016, 6067, 6103, 6103, 6108, 6108, 6176, 6263, 6272, 6312, 6314, 6314, 6320, 6389, 6400, 6428, 6480, 6509, 6512, 6516, 6528, 6571, 6593, 6599, 6656, 6678, 6688, 6740, 6823, 6823, 6917, 6963, 6981, 6987, 7043, 7072, 7086, 7087, 7098, 7141, 7168, 7203, 7245, 7247, 7258, 7293, 7401, 7404, 7406, 7409, 7413, 7414, 7424, 7615, 7680, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8305, 8305, 8319, 8319, 8336, 8348, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11502, 11506, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11648, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11823, 11823, 12293, 12295, 12321, 12329, 12337, 12341, 12344, 12348, 12353, 12438, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42527, 42538, 42539, 42560, 42606, 42623, 42647, 42656, 42735, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43009, 43011, 43013, 43015, 43018, 43020, 43042, 43072, 43123, 43138, 43187, 43250, 43255, 43259, 43259, 43274, 43301, 43312, 43334, 43360, 43388, 43396, 43442, 43471, 43471, 43520, 43560, 43584, 43586, 43588, 43595, 43616, 43638, 43642, 43642, 43648, 43695, 43697, 43697, 43701, 43702, 43705, 43709, 43712, 43712, 43714, 43714, 43739, 43741, 43744, 43754, 43762, 43764, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44002, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64285, 64287, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65136, 65140, 65142, 65276, 65313, 65338, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; + const unicodeES5IdentifierPart = [170, 170, 181, 181, 186, 186, 192, 214, 216, 246, 248, 705, 710, 721, 736, 740, 748, 748, 750, 750, 768, 884, 886, 887, 890, 893, 902, 902, 904, 906, 908, 908, 910, 929, 931, 1013, 1015, 1153, 1155, 1159, 1162, 1319, 1329, 1366, 1369, 1369, 1377, 1415, 1425, 1469, 1471, 1471, 1473, 1474, 1476, 1477, 1479, 1479, 1488, 1514, 1520, 1522, 1552, 1562, 1568, 1641, 1646, 1747, 1749, 1756, 1759, 1768, 1770, 1788, 1791, 1791, 1808, 1866, 1869, 1969, 1984, 2037, 2042, 2042, 2048, 2093, 2112, 2139, 2208, 2208, 2210, 2220, 2276, 2302, 2304, 2403, 2406, 2415, 2417, 2423, 2425, 2431, 2433, 2435, 2437, 2444, 2447, 2448, 2451, 2472, 2474, 2480, 2482, 2482, 2486, 2489, 2492, 2500, 2503, 2504, 2507, 2510, 2519, 2519, 2524, 2525, 2527, 2531, 2534, 2545, 2561, 2563, 2565, 2570, 2575, 2576, 2579, 2600, 2602, 2608, 2610, 2611, 2613, 2614, 2616, 2617, 2620, 2620, 2622, 2626, 2631, 2632, 2635, 2637, 2641, 2641, 2649, 2652, 2654, 2654, 2662, 2677, 2689, 2691, 2693, 2701, 2703, 2705, 2707, 2728, 2730, 2736, 2738, 2739, 2741, 2745, 2748, 2757, 2759, 2761, 2763, 2765, 2768, 2768, 2784, 2787, 2790, 2799, 2817, 2819, 2821, 2828, 2831, 2832, 2835, 2856, 2858, 2864, 2866, 2867, 2869, 2873, 2876, 2884, 2887, 2888, 2891, 2893, 2902, 2903, 2908, 2909, 2911, 2915, 2918, 2927, 2929, 2929, 2946, 2947, 2949, 2954, 2958, 2960, 2962, 2965, 2969, 2970, 2972, 2972, 2974, 2975, 2979, 2980, 2984, 2986, 2990, 3001, 3006, 3010, 3014, 3016, 3018, 3021, 3024, 3024, 3031, 3031, 3046, 3055, 3073, 3075, 3077, 3084, 3086, 3088, 3090, 3112, 3114, 3123, 3125, 3129, 3133, 3140, 3142, 3144, 3146, 3149, 3157, 3158, 3160, 3161, 3168, 3171, 3174, 3183, 3202, 3203, 3205, 3212, 3214, 3216, 3218, 3240, 3242, 3251, 3253, 3257, 3260, 3268, 3270, 3272, 3274, 3277, 3285, 3286, 3294, 3294, 3296, 3299, 3302, 3311, 3313, 3314, 3330, 3331, 3333, 3340, 3342, 3344, 3346, 3386, 3389, 3396, 3398, 3400, 3402, 3406, 3415, 3415, 3424, 3427, 3430, 3439, 3450, 3455, 3458, 3459, 3461, 3478, 3482, 3505, 3507, 3515, 3517, 3517, 3520, 3526, 3530, 3530, 3535, 3540, 3542, 3542, 3544, 3551, 3570, 3571, 3585, 3642, 3648, 3662, 3664, 3673, 3713, 3714, 3716, 3716, 3719, 3720, 3722, 3722, 3725, 3725, 3732, 3735, 3737, 3743, 3745, 3747, 3749, 3749, 3751, 3751, 3754, 3755, 3757, 3769, 3771, 3773, 3776, 3780, 3782, 3782, 3784, 3789, 3792, 3801, 3804, 3807, 3840, 3840, 3864, 3865, 3872, 3881, 3893, 3893, 3895, 3895, 3897, 3897, 3902, 3911, 3913, 3948, 3953, 3972, 3974, 3991, 3993, 4028, 4038, 4038, 4096, 4169, 4176, 4253, 4256, 4293, 4295, 4295, 4301, 4301, 4304, 4346, 4348, 4680, 4682, 4685, 4688, 4694, 4696, 4696, 4698, 4701, 4704, 4744, 4746, 4749, 4752, 4784, 4786, 4789, 4792, 4798, 4800, 4800, 4802, 4805, 4808, 4822, 4824, 4880, 4882, 4885, 4888, 4954, 4957, 4959, 4992, 5007, 5024, 5108, 5121, 5740, 5743, 5759, 5761, 5786, 5792, 5866, 5870, 5872, 5888, 5900, 5902, 5908, 5920, 5940, 5952, 5971, 5984, 5996, 5998, 6000, 6002, 6003, 6016, 6099, 6103, 6103, 6108, 6109, 6112, 6121, 6155, 6157, 6160, 6169, 6176, 6263, 6272, 6314, 6320, 6389, 6400, 6428, 6432, 6443, 6448, 6459, 6470, 6509, 6512, 6516, 6528, 6571, 6576, 6601, 6608, 6617, 6656, 6683, 6688, 6750, 6752, 6780, 6783, 6793, 6800, 6809, 6823, 6823, 6912, 6987, 6992, 7001, 7019, 7027, 7040, 7155, 7168, 7223, 7232, 7241, 7245, 7293, 7376, 7378, 7380, 7414, 7424, 7654, 7676, 7957, 7960, 7965, 7968, 8005, 8008, 8013, 8016, 8023, 8025, 8025, 8027, 8027, 8029, 8029, 8031, 8061, 8064, 8116, 8118, 8124, 8126, 8126, 8130, 8132, 8134, 8140, 8144, 8147, 8150, 8155, 8160, 8172, 8178, 8180, 8182, 8188, 8204, 8205, 8255, 8256, 8276, 8276, 8305, 8305, 8319, 8319, 8336, 8348, 8400, 8412, 8417, 8417, 8421, 8432, 8450, 8450, 8455, 8455, 8458, 8467, 8469, 8469, 8473, 8477, 8484, 8484, 8486, 8486, 8488, 8488, 8490, 8493, 8495, 8505, 8508, 8511, 8517, 8521, 8526, 8526, 8544, 8584, 11264, 11310, 11312, 11358, 11360, 11492, 11499, 11507, 11520, 11557, 11559, 11559, 11565, 11565, 11568, 11623, 11631, 11631, 11647, 11670, 11680, 11686, 11688, 11694, 11696, 11702, 11704, 11710, 11712, 11718, 11720, 11726, 11728, 11734, 11736, 11742, 11744, 11775, 11823, 11823, 12293, 12295, 12321, 12335, 12337, 12341, 12344, 12348, 12353, 12438, 12441, 12442, 12445, 12447, 12449, 12538, 12540, 12543, 12549, 12589, 12593, 12686, 12704, 12730, 12784, 12799, 13312, 19893, 19968, 40908, 40960, 42124, 42192, 42237, 42240, 42508, 42512, 42539, 42560, 42607, 42612, 42621, 42623, 42647, 42655, 42737, 42775, 42783, 42786, 42888, 42891, 42894, 42896, 42899, 42912, 42922, 43000, 43047, 43072, 43123, 43136, 43204, 43216, 43225, 43232, 43255, 43259, 43259, 43264, 43309, 43312, 43347, 43360, 43388, 43392, 43456, 43471, 43481, 43520, 43574, 43584, 43597, 43600, 43609, 43616, 43638, 43642, 43643, 43648, 43714, 43739, 43741, 43744, 43759, 43762, 43766, 43777, 43782, 43785, 43790, 43793, 43798, 43808, 43814, 43816, 43822, 43968, 44010, 44012, 44013, 44016, 44025, 44032, 55203, 55216, 55238, 55243, 55291, 63744, 64109, 64112, 64217, 64256, 64262, 64275, 64279, 64285, 64296, 64298, 64310, 64312, 64316, 64318, 64318, 64320, 64321, 64323, 64324, 64326, 64433, 64467, 64829, 64848, 64911, 64914, 64967, 65008, 65019, 65024, 65039, 65056, 65062, 65075, 65076, 65101, 65103, 65136, 65140, 65142, 65276, 65296, 65305, 65313, 65338, 65343, 65343, 65345, 65370, 65382, 65470, 65474, 65479, 65482, 65487, 65490, 65495, 65498, 65500, ]; function lookupInUnicodeMap(code: number, map: number[]): boolean { // Bail out quickly if it couldn't possibly be in the map. @@ -262,8 +262,8 @@ namespace ts { } function makeReverseMap(source: Map): string[] { - let result: string[] = []; - for (let name in source) { + const result: string[] = []; + for (const name in source) { if (source.hasOwnProperty(name)) { result[source[name]] = name; } @@ -271,7 +271,7 @@ namespace ts { return result; } - let tokenStrings = makeReverseMap(textToToken); + const tokenStrings = makeReverseMap(textToToken); export function tokenToString(t: SyntaxKind): string { return tokenStrings[t]; @@ -284,11 +284,11 @@ namespace ts { /* @internal */ export function computeLineStarts(text: string): number[] { - let result: number[] = new Array(); + const result: number[] = new Array(); let pos = 0; let lineStart = 0; while (pos < text.length) { - let ch = text.charCodeAt(pos++); + const ch = text.charCodeAt(pos++); switch (ch) { case CharacterCodes.carriageReturn: if (text.charCodeAt(pos) === CharacterCodes.lineFeed) { @@ -352,7 +352,7 @@ namespace ts { return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position); } - let hasOwnProperty = Object.prototype.hasOwnProperty; + const hasOwnProperty = Object.prototype.hasOwnProperty; export function isWhiteSpace(ch: number): boolean { // Note: nextLine is in the Zs space, and should be considered to be a whitespace. @@ -400,7 +400,7 @@ namespace ts { export function couldStartTrivia(text: string, pos: number): boolean { // Keep in sync with skipTrivia - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); switch (ch) { case CharacterCodes.carriageReturn: case CharacterCodes.lineFeed: @@ -427,7 +427,7 @@ namespace ts { export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number { // Keep in sync with couldStartTrivia while (true) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); switch (ch) { case CharacterCodes.carriageReturn: if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) { @@ -498,14 +498,14 @@ namespace ts { // All conflict markers consist of the same character repeated seven times. If it is // a <<<<<<< or >>>>>>> marker then it is also followd by a space. - let mergeConflictMarkerLength = "<<<<<<<".length; + const mergeConflictMarkerLength = "<<<<<<<".length; function isConflictMarkerTrivia(text: string, pos: number) { Debug.assert(pos >= 0); // Conflict markers must be at the start of a line. if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); if ((pos + mergeConflictMarkerLength) < text.length) { for (let i = 0, n = mergeConflictMarkerLength; i < n; i++) { @@ -527,8 +527,8 @@ namespace ts { error(Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength); } - let ch = text.charCodeAt(pos); - let len = text.length; + const ch = text.charCodeAt(pos); + const len = text.length; if (ch === CharacterCodes.lessThan || ch === CharacterCodes.greaterThan) { while (pos < len && !isLineBreak(text.charCodeAt(pos))) { @@ -540,7 +540,7 @@ namespace ts { // Consume everything from the start of the mid-conlict marker to the start of the next // end-conflict marker. while (pos < len) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); if (ch === CharacterCodes.greaterThan && isConflictMarkerTrivia(text, pos)) { break; } @@ -561,7 +561,7 @@ namespace ts { } function scanShebangTrivia(text: string, pos: number) { - let shebang = shebangTriviaRegex.exec(text)[0]; + const shebang = shebangTriviaRegex.exec(text)[0]; pos = pos + shebang.length; return pos; } @@ -581,7 +581,7 @@ namespace ts { let result: CommentRange[]; let collecting = trailing || pos === 0; while (true) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); switch (ch) { case CharacterCodes.carriageReturn: if (text.charCodeAt(pos + 1) === CharacterCodes.lineFeed) { @@ -607,8 +607,8 @@ namespace ts { let nextChar = text.charCodeAt(pos + 1); let hasTrailingNewLine = false; if (nextChar === CharacterCodes.slash || nextChar === CharacterCodes.asterisk) { - let kind = nextChar === CharacterCodes.slash ? SyntaxKind.SingleLineCommentTrivia : SyntaxKind.MultiLineCommentTrivia; - let startPos = pos; + const kind = nextChar === CharacterCodes.slash ? SyntaxKind.SingleLineCommentTrivia : SyntaxKind.MultiLineCommentTrivia; + const startPos = pos; pos += 2; if (nextChar === CharacterCodes.slash) { while (pos < text.length) { @@ -742,7 +742,7 @@ namespace ts { } function scanNumber(): number { - let start = pos; + const start = pos; while (isDigit(text.charCodeAt(pos))) pos++; if (text.charCodeAt(pos) === CharacterCodes.dot) { pos++; @@ -765,7 +765,7 @@ namespace ts { } function scanOctalDigits(): number { - let start = pos; + const start = pos; while (isOctalDigit(text.charCodeAt(pos))) { pos++; } @@ -792,7 +792,7 @@ namespace ts { let digits = 0; let value = 0; while (digits < minCount || scanAsManyAsPossible) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); if (ch >= CharacterCodes._0 && ch <= CharacterCodes._9) { value = value * 16 + ch - CharacterCodes._0; } @@ -815,7 +815,7 @@ namespace ts { } function scanString(): string { - let quote = text.charCodeAt(pos++); + const quote = text.charCodeAt(pos++); let result = ""; let start = pos; while (true) { @@ -825,7 +825,7 @@ namespace ts { error(Diagnostics.Unterminated_string_literal); break; } - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); if (ch === quote) { result += text.substring(start, pos); pos++; @@ -853,7 +853,7 @@ namespace ts { * a literal component of a TemplateExpression. */ function scanTemplateAndSetTokenValue(): SyntaxKind { - let startedWithBacktick = text.charCodeAt(pos) === CharacterCodes.backtick; + const startedWithBacktick = text.charCodeAt(pos) === CharacterCodes.backtick; pos++; let start = pos; @@ -869,7 +869,7 @@ namespace ts { break; } - let currChar = text.charCodeAt(pos); + const currChar = text.charCodeAt(pos); // '`' if (currChar === CharacterCodes.backtick) { @@ -925,7 +925,7 @@ namespace ts { error(Diagnostics.Unexpected_end_of_text); return ""; } - let ch = text.charCodeAt(pos++); + const ch = text.charCodeAt(pos++); switch (ch) { case CharacterCodes._0: return "\0"; @@ -977,7 +977,7 @@ namespace ts { } function scanHexadecimalEscape(numDigits: number): string { - let escapedValue = scanExactNumberOfHexDigits(numDigits); + const escapedValue = scanExactNumberOfHexDigits(numDigits); if (escapedValue >= 0) { return String.fromCharCode(escapedValue); @@ -989,7 +989,7 @@ namespace ts { } function scanExtendedUnicodeEscape(): string { - let escapedValue = scanMinimumNumberOfHexDigits(1); + const escapedValue = scanMinimumNumberOfHexDigits(1); let isInvalidExtendedEscape = false; // Validate the value of the digit @@ -1030,8 +1030,8 @@ namespace ts { return String.fromCharCode(codePoint); } - let codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; - let codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; + const codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800; + const codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00; return String.fromCharCode(codeUnit1, codeUnit2); } @@ -1040,9 +1040,9 @@ namespace ts { // and return code point value if valid Unicode escape is found. Otherwise return -1. function peekUnicodeEscape(): number { if (pos + 5 < end && text.charCodeAt(pos + 1) === CharacterCodes.u) { - let start = pos; + const start = pos; pos += 2; - let value = scanExactNumberOfHexDigits(4); + const value = scanExactNumberOfHexDigits(4); pos = start; return value; } @@ -1078,9 +1078,9 @@ namespace ts { function getIdentifierToken(): SyntaxKind { // Reserved words are between 2 and 11 characters long and start with a lowercase letter - let len = tokenValue.length; + const len = tokenValue.length; if (len >= 2 && len <= 11) { - let ch = tokenValue.charCodeAt(0); + const ch = tokenValue.charCodeAt(0); if (ch >= CharacterCodes.a && ch <= CharacterCodes.z && hasOwnProperty.call(textToToken, tokenValue)) { return token = textToToken[tokenValue]; } @@ -1096,8 +1096,8 @@ namespace ts { // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. let numberOfDigits = 0; while (true) { - let ch = text.charCodeAt(pos); - let valueOfCh = ch - CharacterCodes._0; + const ch = text.charCodeAt(pos); + const valueOfCh = ch - CharacterCodes._0; if (!isDigit(ch) || valueOfCh >= base) { break; } @@ -1262,7 +1262,7 @@ namespace ts { let commentClosed = false; while (pos < end) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); if (ch === CharacterCodes.asterisk && text.charCodeAt(pos + 1) === CharacterCodes.slash) { pos += 2; @@ -1504,7 +1504,7 @@ namespace ts { break; } - let ch = text.charCodeAt(p); + const ch = text.charCodeAt(p); if (isLineBreak(ch)) { tokenIsUnterminated = true; error(Diagnostics.Unterminated_regular_expression_literal); @@ -1594,9 +1594,9 @@ namespace ts { // they allow dashes function scanJsxIdentifier(): SyntaxKind { if (tokenIsIdentifierOrKeyword(token)) { - let firstCharPosition = pos; + const firstCharPosition = pos; while (pos < end) { - let ch = text.charCodeAt(pos); + const ch = text.charCodeAt(pos); if (ch === CharacterCodes.minus || ((firstCharPosition === pos) ? isIdentifierStart(ch, languageVersion) : isIdentifierPart(ch, languageVersion))) { pos++; } @@ -1610,13 +1610,13 @@ namespace ts { } function speculationHelper(callback: () => T, isLookahead: boolean): T { - let savePos = pos; - let saveStartPos = startPos; - let saveTokenPos = tokenPos; - let saveToken = token; - let saveTokenValue = tokenValue; - let savePrecedingLineBreak = precedingLineBreak; - let result = callback(); + const savePos = pos; + const saveStartPos = startPos; + const saveTokenPos = tokenPos; + const saveToken = token; + const saveTokenValue = tokenValue; + const savePrecedingLineBreak = precedingLineBreak; + const result = callback(); // If our callback returned something 'falsy' or we're just looking ahead, // then unconditionally restore us to where we were. diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 3eeb126c065..3a90ca42fa1 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -51,15 +51,15 @@ namespace ts { function getWScriptSystem(): System { - let fso = new ActiveXObject("Scripting.FileSystemObject"); + const fso = new ActiveXObject("Scripting.FileSystemObject"); - let fileStream = new ActiveXObject("ADODB.Stream"); + const fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2 /*text*/; - let binaryStream = new ActiveXObject("ADODB.Stream"); + const binaryStream = new ActiveXObject("ADODB.Stream"); binaryStream.Type = 1 /*binary*/; - let args: string[] = []; + const args: string[] = []; for (let i = 0; i < WScript.Arguments.length; i++) { args[i] = WScript.Arguments.Item(i); } @@ -78,7 +78,7 @@ namespace ts { // Load file and read the first two bytes into a string with no interpretation fileStream.Charset = "x-ansi"; fileStream.LoadFromFile(fileName); - let bom = fileStream.ReadText(2) || ""; + const bom = fileStream.ReadText(2) || ""; // Position must be at 0 before encoding can be changed fileStream.Position = 0; // [0xFF,0xFE] and [0xFE,0xFF] mean utf-16 (little or big endian), otherwise default to utf-8 @@ -124,7 +124,7 @@ namespace ts { } function getNames(collection: any): string[] { - let result: string[] = []; + const result: string[] = []; for (let e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { result.push(e.item().Name); } @@ -132,22 +132,22 @@ namespace ts { } function readDirectory(path: string, extension?: string, exclude?: string[]): string[] { - let result: string[] = []; + const result: string[] = []; exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s))); visitDirectory(path); return result; function visitDirectory(path: string) { - let folder = fso.GetFolder(path || "."); - let files = getNames(folder.files); - for (let current of files) { - let name = combinePaths(path, current); + const folder = fso.GetFolder(path || "."); + const files = getNames(folder.files); + for (const current of files) { + const name = combinePaths(path, current); if ((!extension || fileExtensionIs(name, extension)) && !contains(exclude, getCanonicalPath(name))) { result.push(name); } } - let subfolders = getNames(folder.subfolders); - for (let current of subfolders) { - let name = combinePaths(path, current); + const subfolders = getNames(folder.subfolders); + for (const current of subfolders) { + const name = combinePaths(path, current); if (!contains(exclude, getCanonicalPath(name))) { visitDirectory(name); } @@ -198,6 +198,7 @@ namespace ts { const _fs = require("fs"); const _path = require("path"); const _os = require("os"); + const _tty = require("tty"); // average async stat takes about 30 microseconds // set chunk size to do 30 files in < 1 millisecond @@ -211,7 +212,7 @@ namespace ts { } function poll(checkedIndex: number) { - let watchedFile = watchedFiles[checkedIndex]; + const watchedFile = watchedFiles[checkedIndex]; if (!watchedFile) { return; } @@ -251,7 +252,7 @@ namespace ts { } function addFile(fileName: string, callback: (fileName: string, removed?: boolean) => void): WatchedFile { - let file: WatchedFile = { + const file: WatchedFile = { fileName, callback, mtime: getModifiedTime(fileName) @@ -290,7 +291,7 @@ namespace ts { // changes for large reference sets? If so, do we want // to increase the chunk size or decrease the interval // time dynamically to match the large reference set? - let watchedFileSet = createWatchedFileSet(); + const watchedFileSet = createWatchedFileSet(); function isNode4OrLater(): Boolean { return parseInt(process.version.charAt(1)) >= 4; @@ -304,14 +305,14 @@ namespace ts { if (!_fs.existsSync(fileName)) { return undefined; } - let buffer = _fs.readFileSync(fileName); + const buffer = _fs.readFileSync(fileName); let len = buffer.length; if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) { // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js, // flip all byte pairs and treat as little endian. len &= ~1; for (let i = 0; i < len; i += 2) { - let temp = buffer[i]; + const temp = buffer[i]; buffer[i] = buffer[i + 1]; buffer[i + 1] = temp; } @@ -335,7 +336,17 @@ namespace ts { data = "\uFEFF" + data; } - _fs.writeFileSync(fileName, data, "utf8"); + let fd: number; + + try { + fd = _fs.openSync(fileName, "w"); + _fs.writeSync(fd, data, undefined, "utf8"); + } + finally { + if (fd !== undefined) { + _fs.closeSync(fd); + } + } } function getCanonicalPath(path: string): string { @@ -343,17 +354,17 @@ namespace ts { } function readDirectory(path: string, extension?: string, exclude?: string[]): string[] { - let result: string[] = []; + const result: string[] = []; exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s))); visitDirectory(path); return result; function visitDirectory(path: string) { - let files = _fs.readdirSync(path || ".").sort(); - let directories: string[] = []; - for (let current of files) { - let name = combinePaths(path, current); + const files = _fs.readdirSync(path || ".").sort(); + const directories: string[] = []; + for (const current of files) { + const name = combinePaths(path, current); if (!contains(exclude, getCanonicalPath(name))) { - let stat = _fs.statSync(name); + const stat = _fs.statSync(name); if (stat.isFile()) { if (!extension || fileExtensionIs(name, extension)) { result.push(name); @@ -364,7 +375,7 @@ namespace ts { } } } - for (let current of directories) { + for (const current of directories) { visitDirectory(current); } } @@ -375,15 +386,7 @@ namespace ts { newLine: _os.EOL, useCaseSensitiveFileNames: useCaseSensitiveFileNames, write(s: string): void { - const buffer = new Buffer(s, "utf8"); - let offset = 0; - let toWrite: number = buffer.length; - let written = 0; - // 1 is a standard descriptor for stdout - while ((written = _fs.writeSync(1, buffer, offset, toWrite)) < toWrite) { - offset += written; - toWrite -= written; - } + process.stdout.write(s); }, readFile, writeFile, @@ -397,7 +400,7 @@ namespace ts { return _fs.watch(fileName, (eventName: string, relativeFileName: string) => callback(fileName)); } - let watchedFile = watchedFileSet.addFile(fileName, callback); + const watchedFile = watchedFileSet.addFile(fileName, callback); return { close: () => watchedFileSet.removeFile(watchedFile) }; diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index 9489e995766..a89f4c0b5fd 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -6,20 +6,28 @@ namespace ts { fileWatcher?: FileWatcher; } + let reportDiagnostic = reportDiagnosticSimply; + + function reportDiagnostics(diagnostics: Diagnostic[], host: CompilerHost): void { + for (const diagnostic of diagnostics) { + reportDiagnostic(diagnostic, host); + } + } + /** * Checks to see if the locale is in the appropriate format, * and if it is, attempts to set the appropriate language. */ function validateLocaleAndSetLanguage(locale: string, errors: Diagnostic[]): boolean { - let matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); + const matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); if (!matchResult) { errors.push(createCompilerDiagnostic(Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp")); return false; } - let language = matchResult[1]; - let territory = matchResult[3]; + const language = matchResult[1]; + const territory = matchResult[3]; // First try the entire locale, then fall back to just language if that's all we have. if (!trySetLanguageAndTerritory(language, territory, errors) && @@ -33,8 +41,8 @@ namespace ts { } function trySetLanguageAndTerritory(language: string, territory: string, errors: Diagnostic[]): boolean { - let compilerFilePath = normalizePath(sys.getExecutingFilePath()); - let containingDirectoryPath = getDirectoryPath(compilerFilePath); + const compilerFilePath = normalizePath(sys.getExecutingFilePath()); + const containingDirectoryPath = getDirectoryPath(compilerFilePath); let filePath = combinePaths(containingDirectoryPath, language); @@ -77,39 +85,122 @@ namespace ts { } function getDiagnosticText(message: DiagnosticMessage, ...args: any[]): string { - let diagnostic = createCompilerDiagnostic.apply(undefined, arguments); + const diagnostic = createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - function reportDiagnostic(diagnostic: Diagnostic, host: CompilerHost) { + function getRelativeFileName(fileName: string, host: CompilerHost): string { + return host ? convertToRelativePath(fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName)) : fileName; + } + + function reportDiagnosticSimply(diagnostic: Diagnostic, host: CompilerHost): void { let output = ""; if (diagnostic.file) { - let loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); - const relativeFileName = host - ? convertToRelativePath(diagnostic.file.fileName, host.getCurrentDirectory(), fileName => host.getCanonicalFileName(fileName)) - : diagnostic.file.fileName; - - output += `${ relativeFileName }(${ loc.line + 1 },${ loc.character + 1 }): `; + const { line, character } = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); + const relativeFileName = getRelativeFileName(diagnostic.file.fileName, host); + output += `${ relativeFileName }(${ line + 1 },${ character + 1 }): `; } - let category = DiagnosticCategory[diagnostic.category].toLowerCase(); + const category = DiagnosticCategory[diagnostic.category].toLowerCase(); output += `${ category } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine) }${ sys.newLine }`; sys.write(output); } - function reportDiagnostics(diagnostics: Diagnostic[], host: CompilerHost) { - for (let i = 0; i < diagnostics.length; i++) { - reportDiagnostic(diagnostics[i], host); + + const redForegroundEscapeSequence = "\u001b[91m"; + const yellowForegroundEscapeSequence = "\u001b[93m"; + const blueForegroundEscapeSequence = "\u001b[93m"; + const gutterStyleSequence = "\u001b[100;30m"; + const gutterSeparator = " "; + const resetEscapeSequence = "\u001b[0m"; + const elipsis = "..."; + const categoryFormatMap: Map = { + [DiagnosticCategory.Warning]: yellowForegroundEscapeSequence, + [DiagnosticCategory.Error]: redForegroundEscapeSequence, + [DiagnosticCategory.Message]: blueForegroundEscapeSequence, + }; + + function formatAndReset(text: string, formatStyle: string) { + return formatStyle + text + resetEscapeSequence; + } + + function reportDiagnosticWithColorAndContext(diagnostic: Diagnostic, host: CompilerHost): void { + let output = ""; + + if (diagnostic.file) { + const { start, length, file } = diagnostic; + const { line: firstLine, character: firstLineChar } = getLineAndCharacterOfPosition(file, start); + const { line: lastLine, character: lastLineChar } = getLineAndCharacterOfPosition(file, start + length); + const lastLineInFile = getLineAndCharacterOfPosition(file, file.text.length).line; + const relativeFileName = getRelativeFileName(file.fileName, host); + + const hasMoreThanFiveLines = (lastLine - firstLine) >= 4; + let gutterWidth = (lastLine + 1 + "").length; + if (hasMoreThanFiveLines) { + gutterWidth = Math.max(elipsis.length, gutterWidth); + } + + output += sys.newLine; + for (let i = firstLine; i <= lastLine; i++) { + // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines, + // so we'll skip ahead to the second-to-last line. + if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) { + output += formatAndReset(padLeft(elipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + sys.newLine; + i = lastLine - 1; + } + + const lineStart = getPositionOfLineAndCharacter(file, i, 0); + const lineEnd = i < lastLineInFile ? getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length; + let lineContent = file.text.slice(lineStart, lineEnd); + lineContent = lineContent.replace(/\s+$/g, ""); // trim from end + lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces + + // Output the gutter and the actual contents of the line. + output += formatAndReset(padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += lineContent + sys.newLine; + + // Output the gutter and the error span for the line using tildes. + output += formatAndReset(padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator; + output += redForegroundEscapeSequence; + if (i === firstLine) { + // If we're on the last line, then limit it to the last character of the last line. + // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position. + const lastCharForLine = i === lastLine ? lastLineChar : undefined; + + output += lineContent.slice(0, firstLineChar).replace(/\S/g, " "); + output += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~"); + } + else if (i === lastLine) { + output += lineContent.slice(0, lastLineChar).replace(/./g, "~"); + } + else { + // Squiggle the entire line. + output += lineContent.replace(/./g, "~"); + } + output += resetEscapeSequence; + + output += sys.newLine; + } + + output += sys.newLine; + output += `${ relativeFileName }(${ firstLine + 1 },${ firstLineChar + 1 }): `; } + + const categoryColor = categoryFormatMap[diagnostic.category]; + const category = DiagnosticCategory[diagnostic.category].toLowerCase(); + output += `${ formatAndReset(category, categoryColor) } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine) }`; + output += sys.newLine + sys.newLine; + + sys.write(output); } function reportWatchDiagnostic(diagnostic: Diagnostic) { let output = new Date().toLocaleTimeString() + " - "; if (diagnostic.file) { - let loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); + const loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); output += `${ diagnostic.file.fileName }(${ loc.line + 1 },${ loc.character + 1 }): `; } @@ -150,7 +241,7 @@ namespace ts { } export function executeCommandLine(args: string[]): void { - let commandLine = parseCommandLine(args); + const commandLine = parseCommandLine(args); let configFileName: string; // Configuration file name (if any) let cachedConfigFileText: string; // Cached configuration file text, used for reparsing (if any) let configFileWatcher: FileWatcher; // Configuration file watcher @@ -211,7 +302,7 @@ namespace ts { } } else if (commandLine.fileNames.length === 0 && isJSONSupported()) { - let searchPath = normalizePath(sys.getCurrentDirectory()); + const searchPath = normalizePath(sys.getCurrentDirectory()); configFileName = findConfigFile(searchPath, sys.fileExists); } @@ -231,7 +322,7 @@ namespace ts { configFileWatcher = sys.watchFile(configFileName, configFileChanged); } if (sys.watchDirectory && configFileName) { - let directory = ts.getDirectoryPath(configFileName); + const directory = ts.getDirectoryPath(configFileName); directoryWatcher = sys.watchDirectory( // When the configFileName is just "tsconfig.json", the watched directory should be // the current direcotry; if there is a given "project" parameter, then the configFileName @@ -249,16 +340,16 @@ namespace ts { cachedConfigFileText = sys.readFile(configFileName); } catch (e) { - let error = createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); + const error = createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); reportWatchDiagnostic(error); sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); return; } } - let result = parseConfigFileTextToJson(configFileName, cachedConfigFileText); - let configObject = result.config; - let configParseResult = parseJsonConfigFileContent(configObject, sys, getDirectoryPath(configFileName), commandLine.options); + const result = parseConfigFileTextToJson(configFileName, cachedConfigFileText); + const configObject = result.config; + const configParseResult = parseJsonConfigFileContent(configObject, sys, getDirectoryPath(configFileName), commandLine.options); if (configParseResult.errors.length > 0) { reportDiagnostics(configParseResult.errors, /* compilerHost */ undefined); sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); @@ -272,7 +363,7 @@ namespace ts { if (!cachedProgram) { if (configFileName) { - let configParseResult = parseConfigFile(); + const configParseResult = parseConfigFile(); rootFileNames = configParseResult.fileNames; compilerOptions = configParseResult.options; } @@ -288,10 +379,14 @@ namespace ts { compilerHost.fileExists = cachedFileExists; } + if (compilerOptions.pretty) { + reportDiagnostic = reportDiagnosticWithColorAndContext; + } + // reset the cache of existing files cachedExistingFiles = {}; - let compileResult = compile(rootFileNames, compilerOptions, compilerHost); + const compileResult = compile(rootFileNames, compilerOptions, compilerHost); if (!compilerOptions.watch) { return sys.exit(compileResult.exitStatus); @@ -311,14 +406,14 @@ namespace ts { function getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void) { // Return existing SourceFile object if one is available if (cachedProgram) { - let sourceFile = cachedProgram.getSourceFile(fileName); + const sourceFile = cachedProgram.getSourceFile(fileName); // A modified source file has no watcher and should not be reused if (sourceFile && sourceFile.fileWatcher) { return sourceFile; } } // Use default host function - let sourceFile = hostGetSourceFile(fileName, languageVersion, onError); + const sourceFile = hostGetSourceFile(fileName, languageVersion, onError); if (sourceFile && compilerOptions.watch) { // Attach a file watcher sourceFile.fileWatcher = sys.watchFile(sourceFile.fileName, (fileName: string, removed?: boolean) => sourceFileChanged(sourceFile, removed)); @@ -329,7 +424,7 @@ namespace ts { // Change cached program to the given program function setCachedProgram(program: Program) { if (cachedProgram) { - let newSourceFiles = program ? program.getSourceFiles() : undefined; + const newSourceFiles = program ? program.getSourceFiles() : undefined; forEach(cachedProgram.getSourceFiles(), sourceFile => { if (!(newSourceFiles && contains(newSourceFiles, sourceFile))) { if (sourceFile.fileWatcher) { @@ -347,7 +442,7 @@ namespace ts { sourceFile.fileWatcher.close(); sourceFile.fileWatcher = undefined; if (removed) { - let index = rootFileNames.indexOf(sourceFile.fileName); + const index = rootFileNames.indexOf(sourceFile.fileName); if (index >= 0) { rootFileNames.splice(index, 1); } @@ -378,9 +473,9 @@ namespace ts { } function directoryChangeHandler() { - let parsedCommandLine = parseConfigFile(); - let newFileNames = ts.map(parsedCommandLine.fileNames, compilerHost.getCanonicalFileName); - let canonicalRootFileNames = ts.map(rootFileNames, compilerHost.getCanonicalFileName); + const parsedCommandLine = parseConfigFile(); + const newFileNames = ts.map(parsedCommandLine.fileNames, compilerHost.getCanonicalFileName); + const canonicalRootFileNames = ts.map(rootFileNames, compilerHost.getCanonicalFileName); // We check if the project file list has changed. If so, we just throw away the old program and start fresh. if (!arrayIsEqualTo(newFileNames && newFileNames.sort(), canonicalRootFileNames && canonicalRootFileNames.sort())) { @@ -414,8 +509,8 @@ namespace ts { checkTime = 0; emitTime = 0; - let program = createProgram(fileNames, compilerOptions, compilerHost); - let exitStatus = compileProgram(); + const program = createProgram(fileNames, compilerOptions, compilerHost); + const exitStatus = compileProgram(); if (compilerOptions.listFiles) { forEach(program.getSourceFiles(), file => { @@ -424,7 +519,7 @@ namespace ts { } if (compilerOptions.diagnostics) { - let memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1; + const memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1; reportCountStatistic("Files", program.getSourceFiles().length); reportCountStatistic("Lines", countLines(program)); reportCountStatistic("Nodes", program.getNodeCount()); @@ -477,7 +572,7 @@ namespace ts { } // Otherwise, emit and report any errors we ran into. - let emitOutput = program.emit(); + const emitOutput = program.emit(); reportDiagnostics(emitOutput.diagnostics, compilerHost); // If the emitter didn't emit anything, then pass that value along. @@ -503,8 +598,8 @@ namespace ts { let output = ""; // We want to align our "syntax" and "examples" commands to a certain margin. - let syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length; - let examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length; + const syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length; + const examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length; let marginLength = Math.max(syntaxLength, examplesLength); // Build up the syntactic skeleton. @@ -515,7 +610,7 @@ namespace ts { output += sys.newLine + sys.newLine; // Build up the list of examples. - let padding = makePadding(marginLength); + const padding = makePadding(marginLength); output += getDiagnosticText(Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + sys.newLine; output += padding + "tsc --out file.js file.ts" + sys.newLine; output += padding + "tsc @args.txt" + sys.newLine; @@ -524,17 +619,17 @@ namespace ts { output += getDiagnosticText(Diagnostics.Options_Colon) + sys.newLine; // Sort our options by their names, (e.g. "--noImplicitAny" comes before "--watch") - let optsList = filter(optionDeclarations.slice(), v => !v.experimental); + const optsList = filter(optionDeclarations.slice(), v => !v.experimental); optsList.sort((a, b) => compareValues(a.name.toLowerCase(), b.name.toLowerCase())); // We want our descriptions to align at the same column in our output, // so we keep track of the longest option usage string. marginLength = 0; - let usageColumn: string[] = []; // Things like "-d, --declaration" go in here. - let descriptionColumn: string[] = []; + const usageColumn: string[] = []; // Things like "-d, --declaration" go in here. + const descriptionColumn: string[] = []; for (let i = 0; i < optsList.length; i++) { - let option = optsList[i]; + const option = optsList[i]; // If an option lacks a description, // it is not officially supported. @@ -560,15 +655,15 @@ namespace ts { } // Special case that can't fit in the loop. - let usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">"; + const usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">"; usageColumn.push(usageText); descriptionColumn.push(getDiagnosticText(Diagnostics.Insert_command_line_options_and_files_from_a_file)); marginLength = Math.max(usageText.length, marginLength); // Print out each row, aligning all the descriptions on the same column. for (let i = 0; i < usageColumn.length; i++) { - let usage = usageColumn[i]; - let description = descriptionColumn[i]; + const usage = usageColumn[i]; + const description = descriptionColumn[i]; output += usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine; } @@ -588,14 +683,14 @@ namespace ts { } function writeConfigFile(options: CompilerOptions, fileNames: string[]) { - let currentDirectory = sys.getCurrentDirectory(); - let file = normalizePath(combinePaths(currentDirectory, "tsconfig.json")); + const currentDirectory = sys.getCurrentDirectory(); + const file = normalizePath(combinePaths(currentDirectory, "tsconfig.json")); if (sys.fileExists(file)) { reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file), /* compilerHost */ undefined); } else { - let compilerOptions = extend(options, defaultInitCompilerOptions); - let configurations: any = { + const compilerOptions = extend(options, defaultInitCompilerOptions); + const configurations: any = { compilerOptions: serializeCompilerOptions(compilerOptions), exclude: ["node_modules"] }; @@ -612,12 +707,12 @@ namespace ts { return; function serializeCompilerOptions(options: CompilerOptions): Map { - let result: Map = {}; - let optionsNameMap = getOptionNameMap().optionNameMap; + const result: Map = {}; + const optionsNameMap = getOptionNameMap().optionNameMap; - for (let name in options) { + for (const name in options) { if (hasProperty(options, name)) { - let value = options[name]; + const value = options[name]; switch (name) { case "init": case "watch": @@ -634,8 +729,8 @@ namespace ts { } else { // Enum - let typeMap = >optionDefinition.type; - for (let key in typeMap) { + const typeMap = >optionDefinition.type; + for (const key in typeMap) { if (hasProperty(typeMap, key)) { if (typeMap[key] === value) result[name] = key; diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index fd541a8ca80..ca297c087cf 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -11,6 +11,7 @@ "core.ts", "sys.ts", "types.ts", + "diagnosticInformationMap.generated.ts", "scanner.ts", "parser.ts", "utilities.ts", @@ -19,7 +20,6 @@ "emitter.ts", "program.ts", "commandLineParser.ts", - "tsc.ts", - "diagnosticInformationMap.generated.ts" + "tsc.ts" ] } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 4295a179132..98729f01ab3 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -367,28 +367,31 @@ namespace ts { export const enum NodeFlags { None = 0, - Export = 0x00000001, // Declarations - Ambient = 0x00000002, // Declarations - Public = 0x00000010, // Property/Method - Private = 0x00000020, // Property/Method - Protected = 0x00000040, // Property/Method - Static = 0x00000080, // Property/Method - Abstract = 0x00000100, // Class/Method/ConstructSignature - Async = 0x00000200, // Property/Method/Function - Default = 0x00000400, // Function/Class (export default declaration) - MultiLine = 0x00000800, // Multi-line array or object literal - Synthetic = 0x00001000, // Synthetic node (for full fidelity) - DeclarationFile = 0x00002000, // Node is a .d.ts file - Let = 0x00004000, // Variable declaration - Const = 0x00008000, // Variable declaration - OctalLiteral = 0x00010000, // Octal numeric literal - Namespace = 0x00020000, // Namespace declaration - ExportContext = 0x00040000, // Export context (initialized by binding) - ContainsThis = 0x00080000, // Interface contains references to "this" - + Export = 1 << 1, // Declarations + Ambient = 1 << 2, // Declarations + Public = 1 << 3, // Property/Method + Private = 1 << 4, // Property/Method + Protected = 1 << 5, // Property/Method + Static = 1 << 6, // Property/Method + Abstract = 1 << 7, // Class/Method/ConstructSignature + Async = 1 << 8, // Property/Method/Function + Default = 1 << 9, // Function/Class (export default declaration) + MultiLine = 1 << 10, // Multi-line array or object literal + Synthetic = 1 << 11, // Synthetic node (for full fidelity) + DeclarationFile = 1 << 12, // Node is a .d.ts file + Let = 1 << 13, // Variable declaration + Const = 1 << 14, // Variable declaration + OctalLiteral = 1 << 15, // Octal numeric literal + Namespace = 1 << 16, // Namespace declaration + ExportContext = 1 << 17, // Export context (initialized by binding) + ContainsThis = 1 << 18, // Interface contains references to "this" + HasImplicitReturn = 1 << 19, // If function implicitly returns on one of codepaths (initialized by binding) + HasExplicitReturn = 1 << 20, // If function has explicit reachable return on one of codepaths (initialized by binding) Modifier = Export | Ambient | Public | Private | Protected | Static | Abstract | Default | Async, AccessibilityModifier = Public | Private | Protected, - BlockScoped = Let | Const + BlockScoped = Let | Const, + + ReachabilityCheckFlags = HasImplicitReturn | HasExplicitReturn } /* @internal */ @@ -2084,6 +2087,7 @@ namespace ts { outFile?: string; outDir?: string; preserveConstEnums?: boolean; + /* @internal */ pretty?: DiagnosticStyle; project?: string; removeComments?: boolean; rootDir?: string; @@ -2098,6 +2102,10 @@ namespace ts { experimentalDecorators?: boolean; emitDecoratorMetadata?: boolean; moduleResolution?: ModuleResolutionKind; + allowUnusedLabels?: boolean; + allowUnreachableCode?: boolean; + noImplicitReturns?: boolean; + noFallthroughCasesInSwitch?: boolean; forceConsistentCasingInFileNames?: boolean; allowJs?: boolean; /* @internal */ stripInternal?: boolean; @@ -2150,6 +2158,12 @@ namespace ts { JSX, } + /* @internal */ + export const enum DiagnosticStyle { + Simple, + Pretty, + } + export interface ParsedCommandLine { options: CompilerOptions; fileNames: string[]; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 1af18476e7e..be70e106498 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -16,9 +16,9 @@ namespace ts { } export function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration { - let declarations = symbol.declarations; + const declarations = symbol.declarations; if (declarations) { - for (let declaration of declarations) { + for (const declaration of declarations) { if (declaration.kind === kind) { return declaration; } @@ -45,12 +45,12 @@ namespace ts { } // Pool writers to avoid needing to allocate them for every symbol we write. - let stringWriters: StringSymbolWriter[] = []; + const stringWriters: StringSymbolWriter[] = []; export function getSingleLineStringWriter(): StringSymbolWriter { if (stringWriters.length === 0) { let str = ""; - let writeText: (text: string) => void = text => str += text; + const writeText: (text: string) => void = text => str += text; return { string: () => str, writeKeyword: writeText, @@ -94,7 +94,7 @@ namespace ts { } for (let i = 0; i < array1.length; ++i) { - let equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; + const equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i]; if (!equals) { return false; } @@ -130,7 +130,7 @@ namespace ts { // A node is considered to contain a parse error if: // a) the parser explicitly marked that it had an error // b) any of it's children reported that it had an error. - let thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & ParserContextFlags.ThisNodeHasError) !== 0) || + const thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & ParserContextFlags.ThisNodeHasError) !== 0) || forEachChild(node, containsParseError); // If so, mark ourselves accordingly. @@ -159,8 +159,8 @@ namespace ts { // This is a useful function for debugging purposes. export function nodePosToString(node: Node): string { - let file = getSourceFileOfNode(node); - let loc = getLineAndCharacterOfPosition(file, node.pos); + const file = getSourceFileOfNode(node); + const loc = getLineAndCharacterOfPosition(file, node.pos); return `${ file.fileName }(${ loc.line + 1 },${ loc.character + 1 })`; } @@ -215,7 +215,7 @@ namespace ts { return ""; } - let text = sourceFile.text; + const text = sourceFile.text; return text.substring(includeTrivia ? node.pos : skipTrivia(text, node.pos), node.end); } @@ -296,14 +296,14 @@ namespace ts { } export function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): Diagnostic { - let sourceFile = getSourceFileOfNode(node); - let span = getErrorSpanForNode(sourceFile, node); + const sourceFile = getSourceFileOfNode(node); + const span = getErrorSpanForNode(sourceFile, node); return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2); } export function createDiagnosticForNodeFromMessageChain(node: Node, messageChain: DiagnosticMessageChain): Diagnostic { - let sourceFile = getSourceFileOfNode(node); - let span = getErrorSpanForNode(sourceFile, node); + const sourceFile = getSourceFileOfNode(node); + const span = getErrorSpanForNode(sourceFile, node); return { file: sourceFile, start: span.start, @@ -315,9 +315,9 @@ namespace ts { } export function getSpanOfTokenAtPosition(sourceFile: SourceFile, pos: number): TextSpan { - let scanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos); + const scanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos); scanner.scan(); - let start = scanner.getTokenPos(); + const start = scanner.getTokenPos(); return createTextSpanFromBounds(start, scanner.getTextPos()); } @@ -353,7 +353,7 @@ namespace ts { return getSpanOfTokenAtPosition(sourceFile, node.pos); } - let pos = nodeIsMissing(errorNode) + const pos = nodeIsMissing(errorNode) ? errorNode.pos : skipTrivia(sourceFile.text, errorNode.pos); @@ -424,7 +424,7 @@ namespace ts { } export function getJsDocComments(node: Node, sourceFileOfNode: SourceFile) { - let commentRanges = (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) ? + const commentRanges = (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) ? concatenate(getTrailingCommentRanges(sourceFileOfNode.text, node.pos), getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) : getLeadingCommentRangesOfNode(node, sourceFileOfNode); @@ -581,7 +581,7 @@ namespace ts { return; default: if (isFunctionLike(node)) { - let name = (node).name; + const name = (node).name; if (name && name.kind === SyntaxKind.ComputedPropertyName) { // Note that we will not include methods/accessors of a class because they would require // first descending into the class. This is by design. @@ -624,25 +624,26 @@ namespace ts { } export function isFunctionLike(node: Node): node is FunctionLikeDeclaration { - if (node) { - switch (node.kind) { - case SyntaxKind.Constructor: - case SyntaxKind.FunctionExpression: - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.ArrowFunction: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - case SyntaxKind.CallSignature: - case SyntaxKind.ConstructSignature: - case SyntaxKind.IndexSignature: - case SyntaxKind.FunctionType: - case SyntaxKind.ConstructorType: - return true; - } + return node && isFunctionLikeKind(node.kind); + } + + export function isFunctionLikeKind(kind: SyntaxKind): boolean { + switch (kind) { + case SyntaxKind.Constructor: + case SyntaxKind.FunctionExpression: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.ArrowFunction: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.CallSignature: + case SyntaxKind.ConstructSignature: + case SyntaxKind.IndexSignature: + case SyntaxKind.FunctionType: + case SyntaxKind.ConstructorType: + return true; } - return false; } export function introducesArgumentsExoticObject(node: Node) { @@ -1031,7 +1032,7 @@ namespace ts { } export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean) { - let moduleState = getModuleInstanceState(node); + const moduleState = getModuleInstanceState(node); return moduleState === ModuleInstanceState.Instantiated || (preserveConstEnums && moduleState === ModuleInstanceState.ConstEnumOnly); } @@ -1054,7 +1055,7 @@ namespace ts { return (node).moduleSpecifier; } if (node.kind === SyntaxKind.ImportEqualsDeclaration) { - let reference = (node).moduleReference; + const reference = (node).moduleReference; if (reference.kind === SyntaxKind.ExternalModuleReference) { return (reference).expression; } @@ -1089,7 +1090,7 @@ namespace ts { function getJSDocTag(node: Node, kind: SyntaxKind): JSDocTag { if (node && node.jsDocComment) { - for (let tag of node.jsDocComment.tags) { + for (const tag of node.jsDocComment.tags) { if (tag.kind === kind) { return tag; } @@ -1113,14 +1114,14 @@ namespace ts { if (parameter.name && parameter.name.kind === SyntaxKind.Identifier) { // If it's a parameter, see if the parent has a jsdoc comment with an @param // annotation. - let parameterName = (parameter.name).text; + const parameterName = (parameter.name).text; - let docComment = parameter.parent.jsDocComment; + const docComment = parameter.parent.jsDocComment; if (docComment) { return forEach(docComment.tags, t => { if (t.kind === SyntaxKind.JSDocParameterTag) { - let parameterTag = t; - let name = parameterTag.preParameterName || parameterTag.postParameterName; + const parameterTag = t; + const name = parameterTag.preParameterName || parameterTag.postParameterName; if (name.text === parameterName) { return t; } @@ -1141,7 +1142,7 @@ namespace ts { return true; } - let paramTag = getCorrespondingJSDocParameterTag(node); + const paramTag = getCorrespondingJSDocParameterTag(node); if (paramTag && paramTag.typeExpression) { return paramTag.typeExpression.type.kind === SyntaxKind.JSDocVariadicType; } @@ -1169,6 +1170,14 @@ namespace ts { return !!node && (node.kind === SyntaxKind.ArrayBindingPattern || node.kind === SyntaxKind.ObjectBindingPattern); } + export function isNodeDescendentOf(node: Node, ancestor: Node): boolean { + while (node) { + if (node === ancestor) return true; + node = node.parent; + } + return false; + } + export function isInAmbientContext(node: Node): boolean { while (node) { if (node.flags & (NodeFlags.Ambient | NodeFlags.DeclarationFile)) { @@ -1230,7 +1239,7 @@ namespace ts { case SyntaxKind.LabeledStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.SwitchStatement: - case SyntaxKind.ThrowKeyword: + case SyntaxKind.ThrowStatement: case SyntaxKind.TryStatement: case SyntaxKind.VariableStatement: case SyntaxKind.WhileStatement: @@ -1263,7 +1272,7 @@ namespace ts { return false; } - let parent = name.parent; + const parent = name.parent; if (parent.kind === SyntaxKind.ImportSpecifier || parent.kind === SyntaxKind.ExportSpecifier) { if ((parent).propertyName) { return true; @@ -1330,23 +1339,23 @@ namespace ts { } export function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration) { - let heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); + const heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined; } export function getClassImplementsHeritageClauseElements(node: ClassLikeDeclaration) { - let heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ImplementsKeyword); + const heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ImplementsKeyword); return heritageClause ? heritageClause.types : undefined; } export function getInterfaceBaseTypeNodes(node: InterfaceDeclaration) { - let heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); + const heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ExtendsKeyword); return heritageClause ? heritageClause.types : undefined; } export function getHeritageClause(clauses: NodeArray, kind: SyntaxKind) { if (clauses) { - for (let clause of clauses) { + for (const clause of clauses) { if (clause.token === kind) { return clause; } @@ -1358,7 +1367,7 @@ namespace ts { export function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference) { if (!host.getCompilerOptions().noResolve) { - let referenceFileName = isRootedDiskPath(reference.fileName) ? reference.fileName : combinePaths(getDirectoryPath(sourceFile.fileName), reference.fileName); + const referenceFileName = isRootedDiskPath(reference.fileName) ? reference.fileName : combinePaths(getDirectoryPath(sourceFile.fileName), reference.fileName); return host.getSourceFile(referenceFileName); } } @@ -1374,8 +1383,8 @@ namespace ts { } export function getFileReferenceFromReferencePath(comment: string, commentRange: CommentRange): ReferencePathMatchResult { - let simpleReferenceRegEx = /^\/\/\/\s*/gim; + const simpleReferenceRegEx = /^\/\/\/\s*/gim; if (simpleReferenceRegEx.exec(comment)) { if (isNoDefaultLibRegEx.exec(comment)) { return { @@ -1383,10 +1392,10 @@ namespace ts { }; } else { - let matchResult = fullTripleSlashReferencePathRegEx.exec(comment); + const matchResult = fullTripleSlashReferencePathRegEx.exec(comment); if (matchResult) { - let start = commentRange.pos; - let end = commentRange.end; + const start = commentRange.pos; + const end = commentRange.end; return { fileReference: { pos: start, @@ -1447,9 +1456,9 @@ namespace ts { return (name).text; } if (name.kind === SyntaxKind.ComputedPropertyName) { - let nameExpression = (name).expression; + const nameExpression = (name).expression; if (isWellKnownSymbolSyntactically(nameExpression)) { - let rightHandSideName = (nameExpression).name.text; + const rightHandSideName = (nameExpression).name.text; return getPropertyNameForKnownSymbolName(rightHandSideName); } } @@ -1486,7 +1495,7 @@ namespace ts { } export function isParameterDeclaration(node: VariableLikeDeclaration) { - let root = getRootDeclaration(node); + const root = getRootDeclaration(node); return root.kind === SyntaxKind.Parameter; } @@ -1503,12 +1512,12 @@ namespace ts { export function cloneEntityName(node: EntityName): EntityName { if (node.kind === SyntaxKind.Identifier) { - let clone = createSynthesizedNode(SyntaxKind.Identifier); + const clone = createSynthesizedNode(SyntaxKind.Identifier); clone.text = (node).text; return clone; } else { - let clone = createSynthesizedNode(SyntaxKind.QualifiedName); + const clone = createSynthesizedNode(SyntaxKind.QualifiedName); clone.left = cloneEntityName((node).left); clone.left.parent = clone; clone.right = cloneEntityName((node).right); @@ -1522,13 +1531,13 @@ namespace ts { } export function createSynthesizedNode(kind: SyntaxKind, startsOnNewLine?: boolean): Node { - let node = createNode(kind, /* pos */ -1, /* end */ -1); + const node = createNode(kind, /* pos */ -1, /* end */ -1); node.startsOnNewLine = startsOnNewLine; return node; } export function createSynthesizedNodeArray(): NodeArray { - let array = >[]; + const array = >[]; array.pos = -1; array.end = -1; return array; @@ -1536,7 +1545,7 @@ namespace ts { export function createDiagnosticCollection(): DiagnosticCollection { let nonFileDiagnostics: Diagnostic[] = []; - let fileDiagnostics: Map = {}; + const fileDiagnostics: Map = {}; let diagnosticsModified = false; let modificationCount = 0; @@ -1558,7 +1567,7 @@ namespace ts { return; } - for (let diagnostic of fileDiagnostics[newFile.fileName]) { + for (const diagnostic of fileDiagnostics[newFile.fileName]) { diagnostic.file = newFile; } } @@ -1592,14 +1601,14 @@ namespace ts { return fileDiagnostics[fileName] || []; } - let allDiagnostics: Diagnostic[] = []; + const allDiagnostics: Diagnostic[] = []; function pushDiagnostic(d: Diagnostic) { allDiagnostics.push(d); } forEach(nonFileDiagnostics, pushDiagnostic); - for (let key in fileDiagnostics) { + for (const key in fileDiagnostics) { if (hasProperty(fileDiagnostics, key)) { forEach(fileDiagnostics[key], pushDiagnostic); } @@ -1616,7 +1625,7 @@ namespace ts { diagnosticsModified = false; nonFileDiagnostics = sortAndDeduplicateDiagnostics(nonFileDiagnostics); - for (let key in fileDiagnostics) { + for (const key in fileDiagnostics) { if (hasProperty(fileDiagnostics, key)) { fileDiagnostics[key] = sortAndDeduplicateDiagnostics(fileDiagnostics[key]); } @@ -1629,8 +1638,8 @@ namespace ts { // the language service. These characters should be escaped when printing, and if any characters are added, // the map below must be updated. Note that this regexp *does not* include the 'delete' character. // There is no reason for this other than that JSON.stringify does not handle it either. - let escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; - let escapedCharsMap: Map = { + const escapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g; + const escapedCharsMap: Map = { "\0": "\\0", "\t": "\\t", "\v": "\\v", @@ -1661,17 +1670,17 @@ namespace ts { } export function isIntrinsicJsxName(name: string) { - let ch = name.substr(0, 1); + const ch = name.substr(0, 1); return ch.toLowerCase() === ch; } function get16BitUnicodeEscapeSequence(charCode: number): string { - let hexCharCode = charCode.toString(16).toUpperCase(); - let paddedHexCode = ("0000" + hexCharCode).slice(-4); + const hexCharCode = charCode.toString(16).toUpperCase(); + const paddedHexCode = ("0000" + hexCharCode).slice(-4); return "\\u" + paddedHexCode; } - let nonAsciiCharacters = /[^\u0000-\u007F]/g; + const nonAsciiCharacters = /[^\u0000-\u007F]/g; export function escapeNonAsciiCharacters(s: string): string { // Replace non-ASCII characters with '\uNNNN' escapes if any exist. // Otherwise just return the original string. @@ -1695,7 +1704,7 @@ namespace ts { getIndent(): number; } - let indentStrings: string[] = ["", " "]; + const indentStrings: string[] = ["", " "]; export function getIndentString(level: number) { if (indentStrings[level] === undefined) { indentStrings[level] = getIndentString(level - 1) + indentStrings[1]; @@ -1736,7 +1745,7 @@ namespace ts { function writeLiteral(s: string) { if (s && s.length) { write(s); - let lineStartsOfS = computeLineStarts(s); + const lineStartsOfS = computeLineStarts(s); if (lineStartsOfS.length > 1) { lineCount = lineCount + lineStartsOfS.length - 1; linePos = output.length - s.length + lastOrUndefined(lineStartsOfS); @@ -1774,7 +1783,7 @@ namespace ts { } export function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string) { - let compilerOptions = host.getCompilerOptions(); + const compilerOptions = host.getCompilerOptions(); let emitOutputFilePathWithoutExtension: string; if (compilerOptions.outDir) { emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir)); @@ -1795,7 +1804,7 @@ namespace ts { export function forEachExpectedEmitFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean) => void, targetSourceFile?: SourceFile) { - let options = host.getCompilerOptions(); + const options = host.getCompilerOptions(); if (targetSourceFile === undefined) { // Emit on each source file forEach(host.getSourceFiles(), sourceFile => { @@ -1819,9 +1828,9 @@ namespace ts { } function onSingleFileEmit(host: EmitHost, sourceFile: SourceFile) { - let jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, + const jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, sourceFile.languageVariant === LanguageVariant.JSX && options.jsx === JsxEmit.Preserve ? ".jsx" : ".js"); - let emitFileNames: EmitFileNames = { + const emitFileNames: EmitFileNames = { jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: !isJavaScript(sourceFile.fileName) ? getDeclarationEmitFilePath(jsFilePath, options) : undefined @@ -1830,10 +1839,10 @@ namespace ts { } function onBundledEmit(host: EmitHost) { - let bundledSources = filter(host.getSourceFiles(), + const bundledSources = filter(host.getSourceFiles(), sourceFile => !shouldEmitToOwnFile(sourceFile, options) && !isDeclarationFile(sourceFile)); - let jsFilePath = options.outFile || options.out; - let emitFileNames: EmitFileNames = { + const jsFilePath = options.outFile || options.out; + const emitFileNames: EmitFileNames = { jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: getDeclarationEmitFilePath(jsFilePath, options) @@ -1914,8 +1923,8 @@ namespace ts { forEach(declarations, (member: Declaration) => { if ((member.kind === SyntaxKind.GetAccessor || member.kind === SyntaxKind.SetAccessor) && (member.flags & NodeFlags.Static) === (accessor.flags & NodeFlags.Static)) { - let memberName = getPropertyNameForPropertyNameNode(member.name); - let accessorName = getPropertyNameForPropertyNameNode(accessor.name); + const memberName = getPropertyNameForPropertyNameNode(member.name); + const accessorName = getPropertyNameForPropertyNameNode(accessor.name); if (memberName === accessorName) { if (!firstAccessor) { firstAccessor = member; @@ -1973,13 +1982,81 @@ namespace ts { }); } + /** + * Detached comment is a comment at the top of file or function body that is separated from + * the next statement by space. + */ + export function emitDetachedComments(currentSourceFile: SourceFile, writer: EmitTextWriter, + writeComment: (currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string) => void, + node: TextRange, newLine: string, removeComments: boolean) { + let leadingComments: CommentRange[]; + let currentDetachedCommentInfo: {nodePos: number, detachedCommentEndPos: number}; + if (removeComments) { + // removeComments is true, only reserve pinned comment at the top of file + // For example: + // /*! Pinned Comment */ + // + // var x = 10; + if (node.pos === 0) { + leadingComments = filter(getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment); + } + } + else { + // removeComments is false, just get detached as normal and bypass the process to filter comment + leadingComments = getLeadingCommentRanges(currentSourceFile.text, node.pos); + } + + if (leadingComments) { + const detachedComments: CommentRange[] = []; + let lastComment: CommentRange; + + for (const comment of leadingComments) { + if (lastComment) { + const lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end); + const commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos); + + if (commentLine >= lastCommentLine + 2) { + // There was a blank line between the last comment and this comment. This + // comment is not part of the copyright comments. Return what we have so + // far. + break; + } + } + + detachedComments.push(comment); + lastComment = comment; + } + + if (detachedComments.length) { + // All comments look like they could have been part of the copyright header. Make + // sure there is at least one blank line between it and the node. If not, it's not + // a copyright header. + const lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastOrUndefined(detachedComments).end); + const nodeLine = getLineOfLocalPosition(currentSourceFile, skipTrivia(currentSourceFile.text, node.pos)); + if (nodeLine >= lastCommentLine + 2) { + // Valid detachedComments + emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); + emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment); + currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: lastOrUndefined(detachedComments).end }; + } + } + } + + return currentDetachedCommentInfo; + + function isPinnedComment(comment: CommentRange) { + return currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk && + currentSourceFile.text.charCodeAt(comment.pos + 2) === CharacterCodes.exclamation; + } + } + export function writeCommentRange(currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string) { if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk) { - let firstCommentLineAndCharacter = getLineAndCharacterOfPosition(currentSourceFile, comment.pos); - let lineCount = getLineStarts(currentSourceFile).length; + const firstCommentLineAndCharacter = getLineAndCharacterOfPosition(currentSourceFile, comment.pos); + const lineCount = getLineStarts(currentSourceFile).length; let firstCommentLineIndent: number; for (let pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { - let nextLineStart = (currentLine + 1) === lineCount + const nextLineStart = (currentLine + 1) === lineCount ? currentSourceFile.text.length + 1 : getStartPositionOfLine(currentLine + 1, currentSourceFile); @@ -1990,7 +2067,7 @@ namespace ts { } // These are number of spaces writer is going to write at current indent - let currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); + const currentWriterIndentSpacing = writer.getIndent() * getIndentSize(); // Number of spaces we want to be writing // eg: Assume writer indent @@ -2006,10 +2083,10 @@ namespace ts { // More right indented comment */ --4 = 8 - 4 + 11 // class c { } // } - let spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); + const spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart); if (spacesToEmit > 0) { let numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize(); - let indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); + const indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize()); // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces writer.rawWrite(indentSizeSpaceString); @@ -2038,8 +2115,8 @@ namespace ts { } function writeTrimmedCurrentLine(pos: number, nextLineStart: number) { - let end = Math.min(comment.end, nextLineStart - 1); - let currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ""); + const end = Math.min(comment.end, nextLineStart - 1); + const currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, ""); if (currentLineText) { // trimmed forward and ending spaces text writer.write(currentLineText); @@ -2153,7 +2230,7 @@ namespace ts { } export function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean { - let kind = expression.kind; + const kind = expression.kind; if (kind === SyntaxKind.ObjectLiteralExpression) { return (expression).properties.length === 0; } @@ -2181,11 +2258,11 @@ namespace ts { * representing the UTF-8 encoding of the character, and return the expanded char code list. */ function getExpandedCharCodes(input: string): number[] { - let output: number[] = []; - let length = input.length; + const output: number[] = []; + const length = input.length; for (let i = 0; i < length; i++) { - let charCode = input.charCodeAt(i); + const charCode = input.charCodeAt(i); // handel utf8 if (charCode < 0x80) { @@ -2221,9 +2298,9 @@ namespace ts { */ export function convertToBase64(input: string): string { let result = ""; - let charCodes = getExpandedCharCodes(input); + const charCodes = getExpandedCharCodes(input); let i = 0; - let length = charCodes.length; + const length = charCodes.length; let byte1: number, byte2: number, byte3: number, byte4: number; while (i < length) { @@ -2297,14 +2374,14 @@ namespace ts { } export function textSpanOverlapsWith(span: TextSpan, other: TextSpan) { - let overlapStart = Math.max(span.start, other.start); - let overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); + const overlapStart = Math.max(span.start, other.start); + const overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other)); return overlapStart < overlapEnd; } export function textSpanOverlap(span1: TextSpan, span2: TextSpan) { - let overlapStart = Math.max(span1.start, span2.start); - let overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + const overlapStart = Math.max(span1.start, span2.start); + const overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); if (overlapStart < overlapEnd) { return createTextSpanFromBounds(overlapStart, overlapEnd); } @@ -2316,13 +2393,13 @@ namespace ts { } export function textSpanIntersectsWith(span: TextSpan, start: number, length: number) { - let end = start + length; + const end = start + length; return start <= textSpanEnd(span) && end >= span.start; } export function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number) { - let end1 = start1 + length1; - let end2 = start2 + length2; + const end1 = start1 + length1; + const end2 = start2 + length2; return start2 <= end1 && end2 >= start1; } @@ -2331,8 +2408,8 @@ namespace ts { } export function textSpanIntersection(span1: TextSpan, span2: TextSpan) { - let intersectStart = Math.max(span1.start, span2.start); - let intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); + const intersectStart = Math.max(span1.start, span2.start); + const intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2)); if (intersectStart <= intersectEnd) { return createTextSpanFromBounds(intersectStart, intersectEnd); } @@ -2391,14 +2468,14 @@ namespace ts { // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd } // as it makes things much easier to reason about. - let change0 = changes[0]; + const change0 = changes[0]; let oldStartN = change0.span.start; let oldEndN = textSpanEnd(change0.span); let newEndN = oldStartN + change0.newLength; for (let i = 1; i < changes.length; i++) { - let nextChange = changes[i]; + const nextChange = changes[i]; // Consider the following case: // i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting @@ -2480,13 +2557,13 @@ namespace ts { // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) // } - let oldStart1 = oldStartN; - let oldEnd1 = oldEndN; - let newEnd1 = newEndN; + const oldStart1 = oldStartN; + const oldEnd1 = oldEndN; + const newEnd1 = newEndN; - let oldStart2 = nextChange.span.start; - let oldEnd2 = textSpanEnd(nextChange.span); - let newEnd2 = oldStart2 + nextChange.newLength; + const oldStart2 = nextChange.span.start; + const oldEnd2 = textSpanEnd(nextChange.span); + const newEnd2 = oldStart2 + nextChange.newLength; oldStartN = Math.min(oldStart1, oldStart2); oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)); diff --git a/src/harness/compilerRunner.ts b/src/harness/compilerRunner.ts index 11c1b9a8029..84999302bb7 100644 --- a/src/harness/compilerRunner.ts +++ b/src/harness/compilerRunner.ts @@ -140,7 +140,7 @@ class CompilerBaselineRunner extends RunnerBase { it("Correct sourcemap content for " + fileName, () => { if (options.sourceMap || options.inlineSourceMap) { Harness.Baseline.runBaseline("Correct sourcemap content for " + fileName, justName.replace(/\.tsx?$/, ".sourcemap.txt"), () => { - let record = result.getSourceMapRecord(); + const record = result.getSourceMapRecord(); if (options.noEmitOnError && result.errors.length !== 0 && record === undefined) { // Because of the noEmitOnError option no files are created. We need to return null because baselining isn"t required. return null; @@ -159,7 +159,7 @@ class CompilerBaselineRunner extends RunnerBase { // check js output Harness.Baseline.runBaseline("Correct JS output for " + fileName, justName.replace(/\.tsx?/, ".js"), () => { let tsCode = ""; - let tsSources = otherFiles.concat(toBeCompiled); + const tsSources = otherFiles.concat(toBeCompiled); if (tsSources.length > 1) { tsCode += "//// [" + fileName + "] ////\r\n\r\n"; } @@ -184,7 +184,7 @@ class CompilerBaselineRunner extends RunnerBase { } } - let declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) { + const declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) { harnessCompiler.setCompilerSettings(tcSettings); }, options); @@ -257,15 +257,15 @@ class CompilerBaselineRunner extends RunnerBase { // These types are equivalent, but depend on what order the compiler observed // certain parts of the program. - let allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName)); + const allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName)); - let fullWalker = new TypeWriterWalker(program, /*fullTypeCheck:*/ true); - let pullWalker = new TypeWriterWalker(program, /*fullTypeCheck:*/ false); + const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck:*/ true); + const pullWalker = new TypeWriterWalker(program, /*fullTypeCheck:*/ false); - let fullResults: ts.Map = {}; - let pullResults: ts.Map = {}; + const fullResults: ts.Map = {}; + const pullResults: ts.Map = {}; - for (let sourceFile of allFiles) { + for (const sourceFile of allFiles) { fullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName); pullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName); } @@ -294,11 +294,11 @@ class CompilerBaselineRunner extends RunnerBase { return; function checkBaseLines(isSymbolBaseLine: boolean) { - let fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine); - let pullBaseLine = generateBaseLine(pullResults, isSymbolBaseLine); + const fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine); + const pullBaseLine = generateBaseLine(pullResults, isSymbolBaseLine); - let fullExtension = isSymbolBaseLine ? ".symbols" : ".types"; - let pullExtension = isSymbolBaseLine ? ".symbols.pull" : ".types.pull"; + const fullExtension = isSymbolBaseLine ? ".symbols" : ".types"; + const pullExtension = isSymbolBaseLine ? ".symbols.pull" : ".types.pull"; if (fullBaseLine !== pullBaseLine) { Harness.Baseline.runBaseline("Correct full information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine); @@ -310,24 +310,24 @@ class CompilerBaselineRunner extends RunnerBase { } function generateBaseLine(typeWriterResults: ts.Map, isSymbolBaseline: boolean): string { - let typeLines: string[] = []; - let typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {}; + const typeLines: string[] = []; + const typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {}; allFiles.forEach(file => { - let codeLines = file.content.split("\n"); + const codeLines = file.content.split("\n"); typeWriterResults[file.unitName].forEach(result => { if (isSymbolBaseline && !result.symbol) { return; } - let typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type; - let formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString; + const typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type; + const formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString; if (!typeMap[file.unitName]) { typeMap[file.unitName] = {}; } let typeInfo = [formattedLine]; - let existingTypeInfo = typeMap[file.unitName][result.line]; + const existingTypeInfo = typeMap[file.unitName][result.line]; if (existingTypeInfo) { typeInfo = existingTypeInfo.concat(typeInfo); } @@ -336,10 +336,10 @@ class CompilerBaselineRunner extends RunnerBase { typeLines.push("=== " + file.unitName + " ===\r\n"); for (let i = 0; i < codeLines.length; i++) { - let currentCodeLine = codeLines[i]; + const currentCodeLine = codeLines[i]; typeLines.push(currentCodeLine + "\r\n"); if (typeMap[file.unitName]) { - let typeInfo = typeMap[file.unitName][i]; + const typeInfo = typeMap[file.unitName][i]; if (typeInfo) { typeInfo.forEach(ty => { typeLines.push(">" + ty + "\r\n"); @@ -367,13 +367,13 @@ class CompilerBaselineRunner extends RunnerBase { public initializeTests() { describe(this.testSuiteName + " tests", () => { describe("Setup compiler for compiler baselines", () => { - let harnessCompiler = Harness.Compiler.getCompiler(); + const harnessCompiler = Harness.Compiler.getCompiler(); this.parseOptions(); }); // this will set up a series of describe/it blocks to run between the setup and cleanup phases if (this.tests.length === 0) { - let testFiles = this.enumerateFiles(this.basePath, /\.tsx?$/, { recursive: true }); + const testFiles = this.enumerateFiles(this.basePath, /\.tsx?$/, { recursive: true }); testFiles.forEach(fn => { fn = fn.replace(/\\/g, "/"); this.checkTestCodeOutput(fn); @@ -392,7 +392,7 @@ class CompilerBaselineRunner extends RunnerBase { this.decl = false; this.output = false; - let opts = this.options.split(","); + const opts = this.options.split(","); for (let i = 0; i < opts.length; i++) { switch (opts[i]) { case "error": diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 9bf1ba01843..379b228291c 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -102,7 +102,7 @@ namespace FourSlash { export import IndentStyle = ts.IndentStyle; - let entityMap: ts.Map = { + const entityMap: ts.Map = { "&": "&", "\"": """, "'": "'", @@ -118,7 +118,7 @@ namespace FourSlash { // Name of testcase metadata including ts.CompilerOptions properties that will be used by globalOptions // To add additional option, add property into the testOptMetadataNames, refer the property in either globalMetadataNames or fileMetadataNames // Add cases into convertGlobalOptionsToCompilationsSettings function for the compiler to acknowledge such option from meta data - let metadataOptionNames = { + const metadataOptionNames = { baselineFile: "BaselineFile", emitThisFile: "emitThisFile", // This flag is used for testing getEmitOutput feature. It allows test-cases to indicate what file to be output in multiple files project fileName: "Filename", @@ -126,10 +126,10 @@ namespace FourSlash { }; // List of allowed metadata names - let fileMetadataNames = [metadataOptionNames.fileName, metadataOptionNames.emitThisFile, metadataOptionNames.resolveReference]; + const fileMetadataNames = [metadataOptionNames.fileName, metadataOptionNames.emitThisFile, metadataOptionNames.resolveReference]; function convertGlobalOptionsToCompilerOptions(globalOptions: Harness.TestCaseParser.CompilerSettings): ts.CompilerOptions { - let settings: ts.CompilerOptions = { target: ts.ScriptTarget.ES5 }; + const settings: ts.CompilerOptions = { target: ts.ScriptTarget.ES5 }; Harness.Compiler.setCompilerOptionsFromHarnessSetting(globalOptions, settings); return settings; } @@ -224,7 +224,7 @@ namespace FourSlash { // Add input file which has matched file name with the given reference-file path. // This is necessary when resolveReference flag is specified private addMatchedInputFile(referenceFilePath: string) { - let inputFile = this.inputFiles[referenceFilePath]; + const inputFile = this.inputFiles[referenceFilePath]; if (inputFile && !Harness.isLibraryFile(referenceFilePath)) { this.languageServiceAdapterHost.addScript(referenceFilePath, inputFile); } @@ -248,8 +248,8 @@ namespace FourSlash { constructor(private basePath: string, private testType: FourSlashTestType, public testData: FourSlashData) { // Create a new Services Adapter this.cancellationToken = new TestCancellationToken(); - let compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions); - let languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions); + const compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions); + const languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions); this.languageServiceAdapterHost = languageServiceAdapter.getHost(); this.languageService = languageServiceAdapter.getLanguageService(); @@ -272,14 +272,14 @@ namespace FourSlash { // Add the entry-point file itself into the languageServiceShimHost this.languageServiceAdapterHost.addScript(startResolveFileRef.fileName, startResolveFileRef.content); - let resolvedResult = languageServiceAdapter.getPreProcessedFileInfo(startResolveFileRef.fileName, startResolveFileRef.content); - let referencedFiles: ts.FileReference[] = resolvedResult.referencedFiles; - let importedFiles: ts.FileReference[] = resolvedResult.importedFiles; + const resolvedResult = languageServiceAdapter.getPreProcessedFileInfo(startResolveFileRef.fileName, startResolveFileRef.content); + const referencedFiles: ts.FileReference[] = resolvedResult.referencedFiles; + const importedFiles: ts.FileReference[] = resolvedResult.importedFiles; // Add triple reference files into language-service host ts.forEach(referencedFiles, referenceFile => { // Fourslash insert tests/cases/fourslash into inputFile.unitName so we will properly append the same base directory to refFile path - let referenceFilePath = this.basePath + "/" + referenceFile.fileName; + const referenceFilePath = this.basePath + "/" + referenceFile.fileName; this.addMatchedInputFile(referenceFilePath); }); @@ -287,7 +287,7 @@ namespace FourSlash { ts.forEach(importedFiles, importedFile => { // Fourslash insert tests/cases/fourslash into inputFile.unitName and import statement doesn't require ".ts" // so convert them before making appropriate comparison - let importedFilePath = this.basePath + "/" + importedFile.fileName + ".ts"; + const importedFilePath = this.basePath + "/" + importedFile.fileName + ".ts"; this.addMatchedInputFile(importedFilePath); }); @@ -324,8 +324,8 @@ namespace FourSlash { }; this.testData.files.forEach(file => { - let fileName = file.fileName.replace(Harness.IO.directoryName(file.fileName), "").substr(1); - let fileNameWithoutExtension = fileName.substr(0, fileName.lastIndexOf(".")); + const fileName = file.fileName.replace(Harness.IO.directoryName(file.fileName), "").substr(1); + const fileNameWithoutExtension = fileName.substr(0, fileName.lastIndexOf(".")); this.scenarioActions.push(""); }); @@ -334,18 +334,18 @@ namespace FourSlash { } private getFileContent(fileName: string): string { - let script = this.languageServiceAdapterHost.getScriptInfo(fileName); + const script = this.languageServiceAdapterHost.getScriptInfo(fileName); return script.content; } // Entry points from fourslash.ts public goToMarker(name = "") { - let marker = this.getMarkerByName(name); + const marker = this.getMarkerByName(name); if (this.activeFile.fileName !== marker.fileName) { this.openFile(marker.fileName); } - let content = this.getFileContent(marker.fileName); + const content = this.getFileContent(marker.fileName); if (marker.position === -1 || marker.position > content.length) { throw new Error(`Marker "${name}" has been invalidated by unrecoverable edits to the file.`); } @@ -356,8 +356,8 @@ namespace FourSlash { public goToPosition(pos: number) { this.currentCaretPosition = pos; - let lineStarts = ts.computeLineStarts(this.getFileContent(this.activeFile.fileName)); - let lineCharPos = ts.computeLineAndCharacterOfPosition(lineStarts, pos); + const lineStarts = ts.computeLineStarts(this.getFileContent(this.activeFile.fileName)); + const lineCharPos = ts.computeLineAndCharacterOfPosition(lineStarts, pos); this.scenarioActions.push(``); } @@ -376,10 +376,10 @@ namespace FourSlash { public openFile(index: number): void; public openFile(name: string): void; public openFile(indexOrName: any) { - let fileToOpen: FourSlashFile = this.findFile(indexOrName); + const fileToOpen: FourSlashFile = this.findFile(indexOrName); fileToOpen.fileName = ts.normalizeSlashes(fileToOpen.fileName); this.activeFile = fileToOpen; - let fileName = fileToOpen.fileName.replace(Harness.IO.directoryName(fileToOpen.fileName), "").substr(1); + const fileName = fileToOpen.fileName.replace(Harness.IO.directoryName(fileToOpen.fileName), "").substr(1); this.scenarioActions.push(``); // Let the host know that this file is now open @@ -387,13 +387,13 @@ namespace FourSlash { } public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, negative: boolean) { - let startMarker = this.getMarkerByName(startMarkerName); - let endMarker = this.getMarkerByName(endMarkerName); - let predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) { + const startMarker = this.getMarkerByName(startMarkerName); + const endMarker = this.getMarkerByName(endMarkerName); + const predicate = function (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) { return ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false; }; - let exists = this.anyErrorInRange(predicate, startMarker, endMarker); + const exists = this.anyErrorInRange(predicate, startMarker, endMarker); this.taoInvalidReason = "verifyErrorExistsBetweenMarkers NYI"; @@ -413,10 +413,10 @@ namespace FourSlash { } private getDiagnostics(fileName: string): ts.Diagnostic[] { - let syntacticErrors = this.languageService.getSyntacticDiagnostics(fileName); - let semanticErrors = this.languageService.getSemanticDiagnostics(fileName); + const syntacticErrors = this.languageService.getSyntacticDiagnostics(fileName); + const semanticErrors = this.languageService.getSemanticDiagnostics(fileName); - let diagnostics: ts.Diagnostic[] = []; + const diagnostics: ts.Diagnostic[] = []; diagnostics.push.apply(diagnostics, syntacticErrors); diagnostics.push.apply(diagnostics, semanticErrors); @@ -424,9 +424,9 @@ namespace FourSlash { } private getAllDiagnostics(): ts.Diagnostic[] { - let diagnostics: ts.Diagnostic[] = []; + const diagnostics: ts.Diagnostic[] = []; - let fileNames = this.languageServiceAdapterHost.getFilenames(); + const fileNames = this.languageServiceAdapterHost.getFilenames(); for (let i = 0, n = fileNames.length; i < n; i++) { diagnostics.push.apply(this.getDiagnostics(fileNames[i])); } @@ -435,7 +435,7 @@ namespace FourSlash { } public verifyErrorExistsAfterMarker(markerName: string, negative: boolean, after: boolean) { - let marker: Marker = this.getMarkerByName(markerName); + const marker: Marker = this.getMarkerByName(markerName); let predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean; if (after) { @@ -451,8 +451,8 @@ namespace FourSlash { this.taoInvalidReason = "verifyErrorExistsAfterMarker NYI"; - let exists = this.anyErrorInRange(predicate, marker); - let diagnostics = this.getAllDiagnostics(); + const exists = this.anyErrorInRange(predicate, marker); + const diagnostics = this.getAllDiagnostics(); if (exists !== negative) { this.printErrorLog(negative, diagnostics); @@ -462,10 +462,10 @@ namespace FourSlash { private anyErrorInRange(predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean, startMarker: Marker, endMarker?: Marker) { - let errors = this.getDiagnostics(startMarker.fileName); + const errors = this.getDiagnostics(startMarker.fileName); let exists = false; - let startPos = startMarker.position; + const startPos = startMarker.position; let endPos: number = undefined; if (endMarker !== undefined) { endPos = endMarker.position; @@ -496,47 +496,47 @@ namespace FourSlash { } public verifyNumberOfErrorsInCurrentFile(expected: number) { - let errors = this.getDiagnostics(this.activeFile.fileName); - let actual = errors.length; + const errors = this.getDiagnostics(this.activeFile.fileName); + const actual = errors.length; this.scenarioActions.push(``); if (actual !== expected) { this.printErrorLog(false, errors); - let errorMsg = "Actual number of errors (" + actual + ") does not match expected number (" + expected + ")"; + const errorMsg = "Actual number of errors (" + actual + ") does not match expected number (" + expected + ")"; Harness.IO.log(errorMsg); this.raiseError(errorMsg); } } public verifyEval(expr: string, value: any) { - let emit = this.languageService.getEmitOutput(this.activeFile.fileName); + const emit = this.languageService.getEmitOutput(this.activeFile.fileName); if (emit.outputFiles.length !== 1) { throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName); } this.taoInvalidReason = "verifyEval impossible"; - let evaluation = new Function(`${emit.outputFiles[0].text};\r\nreturn (${expr});`)(); + const evaluation = new Function(`${emit.outputFiles[0].text};\r\nreturn (${expr});`)(); if (evaluation !== value) { this.raiseError(`Expected evaluation of expression "${expr}" to equal "${value}", but got "${evaluation}"`); } } public verifyGetEmitOutputForCurrentFile(expected: string): void { - let emit = this.languageService.getEmitOutput(this.activeFile.fileName); + const emit = this.languageService.getEmitOutput(this.activeFile.fileName); if (emit.outputFiles.length !== 1) { throw new Error("Expected exactly one output from emit of " + this.activeFile.fileName); } this.taoInvalidReason = "verifyGetEmitOutputForCurrentFile impossible"; - let actual = emit.outputFiles[0].text; + const actual = emit.outputFiles[0].text; if (actual !== expected) { this.raiseError(`Expected emit output to be "${expected}", but got "${actual}"`); } } public verifyGetEmitOutputContentsForCurrentFile(expected: { fileName: string; content: string; }[]): void { - let emit = this.languageService.getEmitOutput(this.activeFile.fileName); + const emit = this.languageService.getEmitOutput(this.activeFile.fileName); this.taoInvalidReason = "verifyGetEmitOutputContentsForCurrentFile impossible"; assert.equal(emit.outputFiles.length, expected.length, "Number of emit output files"); for (let i = 0; i < emit.outputFiles.length; i++) { @@ -553,7 +553,7 @@ namespace FourSlash { this.taoInvalidReason = "verifyMemberListContains only supports the \"symbol\" parameter"; } - let members = this.getMemberListAtCaret(); + const members = this.getMemberListAtCaret(); if (members) { this.assertItemInCompletionList(members.entries, symbol, text, documentation, kind); } @@ -577,10 +577,10 @@ namespace FourSlash { this.scenarioActions.push(``); } - let members = this.getMemberListAtCaret(); + const members = this.getMemberListAtCaret(); if (members) { - let match = members.entries.length === expectedCount; + const match = members.entries.length === expectedCount; if ((!match && !negative) || (match && negative)) { this.raiseError("Member list count was " + members.entries.length + ". Expected " + expectedCount); @@ -595,7 +595,7 @@ namespace FourSlash { this.scenarioActions.push(""); this.scenarioActions.push(``); - let members = this.getMemberListAtCaret(); + const members = this.getMemberListAtCaret(); if (members && members.entries.filter(e => e.name === symbol).length !== 0) { this.raiseError(`Member list did contain ${symbol}`); } @@ -604,8 +604,8 @@ namespace FourSlash { public verifyCompletionListItemsCountIsGreaterThan(count: number, negative: boolean) { this.taoInvalidReason = "verifyCompletionListItemsCountIsGreaterThan NYI"; - let completions = this.getCompletionListAtCaret(); - let itemsCount = completions.entries.length; + const completions = this.getCompletionListAtCaret(); + const itemsCount = completions.entries.length; if (negative) { if (itemsCount > count) { @@ -627,7 +627,7 @@ namespace FourSlash { this.scenarioActions.push(""); } - let members = this.getMemberListAtCaret(); + const members = this.getMemberListAtCaret(); if ((!members || members.entries.length === 0) && negative) { this.raiseError("Member list is empty at Caret"); } @@ -647,7 +647,7 @@ namespace FourSlash { public verifyCompletionListIsEmpty(negative: boolean) { this.scenarioActions.push(""); - let completions = this.getCompletionListAtCaret(); + const completions = this.getCompletionListAtCaret(); if ((!completions || completions.entries.length === 0) && negative) { this.raiseError("Completion list is empty at caret at position " + this.activeFile.fileName + " " + this.currentCaretPosition); } @@ -664,7 +664,7 @@ namespace FourSlash { public verifyCompletionListAllowsNewIdentifier(negative: boolean) { - let completions = this.getCompletionListAtCaret(); + const completions = this.getCompletionListAtCaret(); if ((completions && !completions.isNewIdentifierLocation) && !negative) { this.raiseError("Expected builder completion entry"); @@ -675,7 +675,7 @@ namespace FourSlash { } public verifyCompletionListContains(symbol: string, text?: string, documentation?: string, kind?: string) { - let completions = this.getCompletionListAtCaret(); + const completions = this.getCompletionListAtCaret(); if (completions) { this.assertItemInCompletionList(completions.entries, symbol, text, documentation, kind); } @@ -695,11 +695,11 @@ namespace FourSlash { * @param expectedKind the kind of symbol (see ScriptElementKind) */ public verifyCompletionListDoesNotContain(symbol: string, expectedText?: string, expectedDocumentation?: string, expectedKind?: string) { - let that = this; + const that = this; function filterByTextOrDocumentation(entry: ts.CompletionEntry) { - let details = that.getCompletionEntryDetails(entry.name); - let documentation = ts.displayPartsToString(details.documentation); - let text = ts.displayPartsToString(details.displayParts); + const details = that.getCompletionEntryDetails(entry.name); + const documentation = ts.displayPartsToString(details.documentation); + const text = ts.displayPartsToString(details.displayParts); if (expectedText && expectedDocumentation) { return (documentation === expectedDocumentation && text === expectedText) ? true : false; } @@ -717,7 +717,7 @@ namespace FourSlash { this.scenarioActions.push(""); this.scenarioActions.push(``); - let completions = this.getCompletionListAtCaret(); + const completions = this.getCompletionListAtCaret(); if (completions) { let filterCompletions = completions.entries.filter(e => e.name === symbol); filterCompletions = expectedKind ? filterCompletions.filter(e => e.kind === expectedKind) : filterCompletions; @@ -727,7 +727,7 @@ namespace FourSlash { // then these symbols must meet the criterion for Not supposed to be in the list. So we // raise an error let error = "Completion list did contain \'" + symbol + "\'."; - let details = this.getCompletionEntryDetails(filterCompletions[0].name); + const details = this.getCompletionEntryDetails(filterCompletions[0].name); if (expectedText) { error += "Expected text: " + expectedText + " to equal: " + ts.displayPartsToString(details.displayParts) + "."; } @@ -745,7 +745,7 @@ namespace FourSlash { public verifyCompletionEntryDetails(entryName: string, expectedText: string, expectedDocumentation?: string, kind?: string) { this.taoInvalidReason = "verifyCompletionEntryDetails NYI"; - let details = this.getCompletionEntryDetails(entryName); + const details = this.getCompletionEntryDetails(entryName); assert.equal(ts.displayPartsToString(details.displayParts), expectedText, assertionMessage("completion entry details text")); @@ -761,14 +761,14 @@ namespace FourSlash { public verifyReferencesAtPositionListContains(fileName: string, start: number, end: number, isWriteAccess?: boolean) { this.taoInvalidReason = "verifyReferencesAtPositionListContains NYI"; - let references = this.getReferencesAtCaret(); + const references = this.getReferencesAtCaret(); if (!references || references.length === 0) { this.raiseError("verifyReferencesAtPositionListContains failed - found 0 references, expected at least one."); } for (let i = 0; i < references.length; i++) { - let reference = references[i]; + const reference = references[i]; if (reference && reference.fileName === fileName && reference.textSpan.start === start && ts.textSpanEnd(reference.textSpan) === end) { if (typeof isWriteAccess !== "undefined" && reference.isWriteAccess !== isWriteAccess) { this.raiseError(`verifyReferencesAtPositionListContains failed - item isWriteAccess value does not match, actual: ${reference.isWriteAccess}, expected: ${isWriteAccess}.`); @@ -777,18 +777,18 @@ namespace FourSlash { } } - let missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess }; + const missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess }; this.raiseError(`verifyReferencesAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(references)})`); } public verifyReferencesCountIs(count: number, localFilesOnly = true) { this.taoInvalidReason = "verifyReferences NYI"; - let references = this.getReferencesAtCaret(); + const references = this.getReferencesAtCaret(); let referencesCount = 0; if (localFilesOnly) { - let localFiles = this.testData.files.map(file => file.fileName); + const localFiles = this.testData.files.map(file => file.fileName); // Count only the references in local files. Filter the ones in lib and other files. ts.forEach(references, entry => { if (localFiles.some((fileName) => fileName === entry.fileName)) { @@ -801,7 +801,7 @@ namespace FourSlash { } if (referencesCount !== count) { - let condition = localFilesOnly ? "excluding libs" : "including libs"; + const condition = localFilesOnly ? "excluding libs" : "including libs"; this.raiseError("Expected references count (" + condition + ") to be " + count + ", but is actually " + referencesCount); } } @@ -827,18 +827,18 @@ namespace FourSlash { } public getSyntacticDiagnostics(expected: string) { - let diagnostics = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); + const diagnostics = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); this.testDiagnostics(expected, diagnostics); } public getSemanticDiagnostics(expected: string) { - let diagnostics = this.languageService.getSemanticDiagnostics(this.activeFile.fileName); + const diagnostics = this.languageService.getSemanticDiagnostics(this.activeFile.fileName); this.testDiagnostics(expected, diagnostics); } private testDiagnostics(expected: string, diagnostics: ts.Diagnostic[]) { - let realized = ts.realizeDiagnostics(diagnostics, "\r\n"); - let actual = JSON.stringify(realized, null, " "); + const realized = ts.realizeDiagnostics(diagnostics, "\r\n"); + const actual = JSON.stringify(realized, null, " "); assert.equal(actual, expected); } @@ -850,9 +850,9 @@ namespace FourSlash { } }); - let actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); - let actualQuickInfoText = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.displayParts) : ""; - let actualQuickInfoDocumentation = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.documentation) : ""; + const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actualQuickInfoText = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.displayParts) : ""; + const actualQuickInfoDocumentation = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.documentation) : ""; if (negative) { if (expectedText !== undefined) { @@ -898,7 +898,7 @@ namespace FourSlash { return result; } - let actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); assert.equal(actualQuickInfo.kind, kind, this.messageAtLastKnownMarker("QuickInfo kind")); assert.equal(actualQuickInfo.kindModifiers, kindModifiers, this.messageAtLastKnownMarker("QuickInfo kindModifiers")); assert.equal(JSON.stringify(actualQuickInfo.textSpan), JSON.stringify(textSpan), this.messageAtLastKnownMarker("QuickInfo textSpan")); @@ -907,7 +907,7 @@ namespace FourSlash { } public verifyRenameLocations(findInStrings: boolean, findInComments: boolean) { - let renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); + const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (renameInfo.canRename) { let references = this.languageService.findRenameLocations( this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments); @@ -929,8 +929,8 @@ namespace FourSlash { references = references.sort((r1, r2) => r1.textSpan.start - r2.textSpan.start); for (let i = 0, n = ranges.length; i < n; i++) { - let reference = references[i]; - let range = ranges[i]; + const reference = references[i]; + const range = ranges[i]; if (reference.textSpan.start !== range.start || ts.textSpanEnd(reference.textSpan) !== range.end) { @@ -947,7 +947,7 @@ namespace FourSlash { public verifyQuickInfoExists(negative: boolean) { this.taoInvalidReason = "verifyQuickInfoExists NYI"; - let actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); if (negative) { if (actualQuickInfo) { this.raiseError("verifyQuickInfoExists failed. Expected quick info NOT to exist"); @@ -963,7 +963,7 @@ namespace FourSlash { public verifyCurrentSignatureHelpIs(expected: string) { this.taoInvalidReason = "verifyCurrentSignatureHelpIs NYI"; - let help = this.getActiveSignatureHelpItem(); + const help = this.getActiveSignatureHelpItem(); assert.equal( ts.displayPartsToString(help.prefixDisplayParts) + help.parameters.map(p => ts.displayPartsToString(p.displayParts)).join(ts.displayPartsToString(help.separatorDisplayParts)) + @@ -973,7 +973,7 @@ namespace FourSlash { public verifyCurrentParameterIsletiable(isVariable: boolean) { this.taoInvalidReason = "verifyCurrentParameterIsletiable NYI"; - let signature = this.getActiveSignatureHelpItem(); + const signature = this.getActiveSignatureHelpItem(); assert.isNotNull(signature); assert.equal(isVariable, signature.isVariadic); } @@ -981,24 +981,24 @@ namespace FourSlash { public verifyCurrentParameterHelpName(name: string) { this.taoInvalidReason = "verifyCurrentParameterHelpName NYI"; - let activeParameter = this.getActiveParameter(); - let activeParameterName = activeParameter.name; + const activeParameter = this.getActiveParameter(); + const activeParameterName = activeParameter.name; assert.equal(activeParameterName, name); } public verifyCurrentParameterSpanIs(parameter: string) { this.taoInvalidReason = "verifyCurrentParameterSpanIs NYI"; - let activeSignature = this.getActiveSignatureHelpItem(); - let activeParameter = this.getActiveParameter(); + const activeSignature = this.getActiveSignatureHelpItem(); + const activeParameter = this.getActiveParameter(); assert.equal(ts.displayPartsToString(activeParameter.displayParts), parameter); } public verifyCurrentParameterHelpDocComment(docComment: string) { this.taoInvalidReason = "verifyCurrentParameterHelpDocComment NYI"; - let activeParameter = this.getActiveParameter(); - let activeParameterDocComment = activeParameter.documentation; + const activeParameter = this.getActiveParameter(); + const activeParameterDocComment = activeParameter.documentation; assert.equal(ts.displayPartsToString(activeParameterDocComment), docComment, assertionMessage("current parameter Help DocComment")); } @@ -1017,7 +1017,7 @@ namespace FourSlash { public verifyCurrentSignatureHelpDocComment(docComment: string) { this.taoInvalidReason = "verifyCurrentSignatureHelpDocComment NYI"; - let actualDocComment = this.getActiveSignatureHelpItem().documentation; + const actualDocComment = this.getActiveSignatureHelpItem().documentation; assert.equal(ts.displayPartsToString(actualDocComment), docComment, assertionMessage("current signature help doc comment")); } @@ -1025,22 +1025,22 @@ namespace FourSlash { this.scenarioActions.push(""); this.scenarioActions.push(``); - let help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); - let actual = help && help.items ? help.items.length : 0; + const help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + const actual = help && help.items ? help.items.length : 0; assert.equal(actual, expected); } public verifySignatureHelpArgumentCount(expected: number) { this.taoInvalidReason = "verifySignatureHelpArgumentCount NYI"; - let signatureHelpItems = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); - let actual = signatureHelpItems.argumentCount; + const signatureHelpItems = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + const actual = signatureHelpItems.argumentCount; assert.equal(actual, expected); } public verifySignatureHelpPresent(shouldBePresent = true) { this.taoInvalidReason = "verifySignatureHelpPresent NYI"; - let actual = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + const actual = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); if (shouldBePresent) { if (!actual) { this.raiseError("Expected signature help to be present, but it wasn't"); @@ -1060,7 +1060,7 @@ namespace FourSlash { } public verifyRenameInfoSucceeded(displayName?: string, fullDisplayName?: string, kind?: string, kindModifiers?: string) { - let renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); + const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (!renameInfo.canRename) { this.raiseError("Rename did not succeed"); } @@ -1074,7 +1074,7 @@ namespace FourSlash { this.raiseError("Expected a single range to be selected in the test file."); } - let expectedRange = this.getRanges()[0]; + const expectedRange = this.getRanges()[0]; if (renameInfo.triggerSpan.start !== expectedRange.start || ts.textSpanEnd(renameInfo.triggerSpan) !== expectedRange.end) { this.raiseError("Expected triggerSpan [" + expectedRange.start + "," + expectedRange.end + "). Got [" + @@ -1083,7 +1083,7 @@ namespace FourSlash { } public verifyRenameInfoFailed(message?: string) { - let renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); + const renameInfo = this.languageService.getRenameInfo(this.activeFile.fileName, this.currentCaretPosition); if (renameInfo.canRename) { this.raiseError("Rename was expected to fail"); } @@ -1092,15 +1092,15 @@ namespace FourSlash { } private getActiveSignatureHelpItem() { - let help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); - let index = help.selectedItemIndex; + const help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + const index = help.selectedItemIndex; return help.items[index]; } private getActiveParameter(): ts.SignatureHelpParameter { - let help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); - let item = help.items[help.selectedItemIndex]; - let currentParam = help.argumentIndex; + const help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + const item = help.items[help.selectedItemIndex]; + const currentParam = help.argumentIndex; return item.parameters[currentParam]; } @@ -1109,8 +1109,8 @@ namespace FourSlash { private spanInfoToString(pos: number, spanInfo: ts.TextSpan, prefixString: string) { let resultString = "SpanInfo: " + JSON.stringify(spanInfo); if (spanInfo) { - let spanString = this.activeFile.content.substr(spanInfo.start, spanInfo.length); - let spanLineMap = ts.computeLineStarts(spanString); + const spanString = this.activeFile.content.substr(spanInfo.start, spanInfo.length); + const spanLineMap = ts.computeLineStarts(spanString); for (let i = 0; i < spanLineMap.length; i++) { if (!i) { resultString += "\n"; @@ -1124,17 +1124,17 @@ namespace FourSlash { } private baselineCurrentFileLocations(getSpanAtPos: (pos: number) => ts.TextSpan): string { - let fileLineMap = ts.computeLineStarts(this.activeFile.content); + const fileLineMap = ts.computeLineStarts(this.activeFile.content); let nextLine = 0; let resultString = ""; let currentLine: string; let previousSpanInfo: string; let startColumn: number; let length: number; - let prefixString = " >"; + const prefixString = " >"; let pos = 0; - let addSpanInfoString = () => { + const addSpanInfoString = () => { if (previousSpanInfo) { resultString += currentLine; let thisLineMarker = repeatString(startColumn, " ") + repeatString(length, "~"); @@ -1157,7 +1157,7 @@ namespace FourSlash { startColumn = 0; length = 0; } - let spanInfo = this.spanInfoToString(pos, getSpanAtPos(pos), prefixString); + const spanInfo = this.spanInfoToString(pos, getSpanAtPos(pos), prefixString); if (previousSpanInfo && previousSpanInfo !== spanInfo) { addSpanInfoString(); previousSpanInfo = spanInfo; @@ -1201,11 +1201,11 @@ namespace FourSlash { public baselineGetEmitOutput() { this.taoInvalidReason = "baselineGetEmitOutput impossible"; // Find file to be emitted - let emitFiles: FourSlashFile[] = []; // List of FourSlashFile that has emitThisFile flag on + const emitFiles: FourSlashFile[] = []; // List of FourSlashFile that has emitThisFile flag on - let allFourSlashFiles = this.testData.files; + const allFourSlashFiles = this.testData.files; for (let idx = 0; idx < allFourSlashFiles.length; ++idx) { - let file = allFourSlashFiles[idx]; + const file = allFourSlashFiles[idx]; if (file.fileOptions[metadataOptionNames.emitThisFile] === "true") { // Find a file with the flag emitThisFile turned on emitFiles.push(file); @@ -1224,20 +1224,20 @@ namespace FourSlash { let resultString = ""; // Loop through all the emittedFiles and emit them one by one emitFiles.forEach(emitFile => { - let emitOutput = this.languageService.getEmitOutput(emitFile.fileName); + const emitOutput = this.languageService.getEmitOutput(emitFile.fileName); // Print emitOutputStatus in readable format resultString += "EmitSkipped: " + emitOutput.emitSkipped + Harness.IO.newLine(); if (emitOutput.emitSkipped) { resultString += "Diagnostics:" + Harness.IO.newLine(); - let diagnostics = ts.getPreEmitDiagnostics(this.languageService.getProgram()); + const diagnostics = ts.getPreEmitDiagnostics(this.languageService.getProgram()); for (let i = 0, n = diagnostics.length; i < n; i++) { resultString += " " + diagnostics[0].messageText + Harness.IO.newLine(); } } emitOutput.outputFiles.forEach((outputFile, idx, array) => { - let fileName = "FileName : " + outputFile.name + Harness.IO.newLine(); + const fileName = "FileName : " + outputFile.name + Harness.IO.newLine(); resultString = resultString + fileName + outputFile.text; }); resultString += Harness.IO.newLine(); @@ -1257,19 +1257,19 @@ namespace FourSlash { } public printCurrentParameterHelp() { - let help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); + const help = this.languageService.getSignatureHelpItems(this.activeFile.fileName, this.currentCaretPosition); Harness.IO.log(JSON.stringify(help)); } public printCurrentQuickInfo() { - let quickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const quickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition); Harness.IO.log(JSON.stringify(quickInfo)); } public printErrorList() { - let syntacticErrors = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); - let semanticErrors = this.languageService.getSemanticDiagnostics(this.activeFile.fileName); - let errorList = syntacticErrors.concat(semanticErrors); + const syntacticErrors = this.languageService.getSyntacticDiagnostics(this.activeFile.fileName); + const semanticErrors = this.languageService.getSemanticDiagnostics(this.activeFile.fileName); + const errorList = syntacticErrors.concat(semanticErrors); Harness.IO.log(`Error list (${errorList.length} errors)`); if (errorList.length) { @@ -1284,8 +1284,8 @@ namespace FourSlash { public printCurrentFileState(makeWhitespaceVisible = false, makeCaretVisible = true) { for (let i = 0; i < this.testData.files.length; i++) { - let file = this.testData.files[i]; - let active = (this.activeFile === file); + const file = this.testData.files[i]; + const active = (this.activeFile === file); Harness.IO.log(`=== Script (${file.fileName}) ${(active ? "(active, cursor at |)" : "")} ===`); let content = this.getFileContent(file.fileName); if (active) { @@ -1299,22 +1299,22 @@ namespace FourSlash { } public printCurrentSignatureHelp() { - let sigHelp = this.getActiveSignatureHelpItem(); + const sigHelp = this.getActiveSignatureHelpItem(); Harness.IO.log(JSON.stringify(sigHelp)); } public printMemberListMembers() { - let members = this.getMemberListAtCaret(); + const members = this.getMemberListAtCaret(); Harness.IO.log(JSON.stringify(members)); } public printCompletionListMembers() { - let completions = this.getCompletionListAtCaret(); + const completions = this.getCompletionListAtCaret(); Harness.IO.log(JSON.stringify(completions)); } public printReferences() { - let references = this.getReferencesAtCaret(); + const references = this.getReferencesAtCaret(); ts.forEach(references, entry => { Harness.IO.log(JSON.stringify(entry)); }); @@ -1328,9 +1328,9 @@ namespace FourSlash { this.scenarioActions.push(``); let offset = this.currentCaretPosition; - let ch = ""; + const ch = ""; - let checkCadence = (count >> 2) + 1; + const checkCadence = (count >> 2) + 1; for (let i = 0; i < count; i++) { // Make the edit @@ -1343,7 +1343,7 @@ namespace FourSlash { // Handle post-keystroke formatting if (this.enableFormatting) { - let edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); + const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); if (edits.length) { offset += this.applyEdits(this.activeFile.fileName, edits, true); // this.checkPostEditInletiants(); @@ -1370,8 +1370,8 @@ namespace FourSlash { this.scenarioActions.push(``); let offset = this.currentCaretPosition; - let ch = ""; - let checkCadence = (count >> 2) + 1; + const ch = ""; + const checkCadence = (count >> 2) + 1; for (let i = 0; i < count; i++) { offset--; @@ -1385,7 +1385,7 @@ namespace FourSlash { // Handle post-keystroke formatting if (this.enableFormatting) { - let edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); + const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); if (edits.length) { offset += this.applyEdits(this.activeFile.fileName, edits, true); } @@ -1416,12 +1416,12 @@ namespace FourSlash { // as much as possible private typeHighFidelity(text: string) { let offset = this.currentCaretPosition; - let prevChar = " "; - let checkCadence = (text.length >> 2) + 1; + const prevChar = " "; + const checkCadence = (text.length >> 2) + 1; for (let i = 0; i < text.length; i++) { // Make the edit - let ch = text.charAt(i); + const ch = text.charAt(i); this.languageServiceAdapterHost.editScript(this.activeFile.fileName, offset, offset, ch); this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, offset); @@ -1445,7 +1445,7 @@ namespace FourSlash { // Handle post-keystroke formatting if (this.enableFormatting) { - let edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); + const edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions); if (edits.length) { offset += this.applyEdits(this.activeFile.fileName, edits, true); // this.checkPostEditInletiants(); @@ -1464,7 +1464,7 @@ namespace FourSlash { public paste(text: string) { this.scenarioActions.push(``); - let start = this.currentCaretPosition; + const start = this.currentCaretPosition; let offset = this.currentCaretPosition; this.languageServiceAdapterHost.editScript(this.activeFile.fileName, offset, offset, text); this.updateMarkersForEdit(this.activeFile.fileName, offset, offset, text); @@ -1473,7 +1473,7 @@ namespace FourSlash { // Handle formatting if (this.enableFormatting) { - let edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, offset, this.formatCodeOptions); + const edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, offset, this.formatCodeOptions); if (edits.length) { offset += this.applyEdits(this.activeFile.fileName, edits, true); this.checkPostEditInletiants(); @@ -1494,17 +1494,17 @@ namespace FourSlash { return; } - let incrementalSourceFile = this.languageService.getSourceFile(this.activeFile.fileName); + const incrementalSourceFile = this.languageService.getSourceFile(this.activeFile.fileName); Utils.assertInvariants(incrementalSourceFile, /*parent:*/ undefined); - let incrementalSyntaxDiagnostics = incrementalSourceFile.parseDiagnostics; + const incrementalSyntaxDiagnostics = incrementalSourceFile.parseDiagnostics; // Check syntactic structure - let content = this.getFileContent(this.activeFile.fileName); + const content = this.getFileContent(this.activeFile.fileName); - let referenceSourceFile = ts.createLanguageServiceSourceFile( + const referenceSourceFile = ts.createLanguageServiceSourceFile( this.activeFile.fileName, createScriptSnapShot(content), ts.ScriptTarget.Latest, /*version:*/ "0", /*setNodeParents:*/ false); - let referenceSyntaxDiagnostics = referenceSourceFile.parseDiagnostics; + const referenceSyntaxDiagnostics = referenceSourceFile.parseDiagnostics; Utils.assertDiagnosticsEquals(incrementalSyntaxDiagnostics, referenceSyntaxDiagnostics); Utils.assertStructuralEquals(incrementalSourceFile, referenceSourceFile); @@ -1514,7 +1514,7 @@ namespace FourSlash { // The caret can potentially end up between the \r and \n, which is confusing. If // that happens, move it back one character if (this.currentCaretPosition > 0) { - let ch = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition - 1, this.currentCaretPosition); + const ch = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition - 1, this.currentCaretPosition); if (ch === "\r") { this.currentCaretPosition--; } @@ -1527,18 +1527,18 @@ namespace FourSlash { let runningOffset = 0; edits = edits.sort((a, b) => a.span.start - b.span.start); // Get a snapshot of the content of the file so we can make sure any formatting edits didn't destroy non-whitespace characters - let oldContent = this.getFileContent(this.activeFile.fileName); + const oldContent = this.getFileContent(this.activeFile.fileName); for (let j = 0; j < edits.length; j++) { this.languageServiceAdapterHost.editScript(fileName, edits[j].span.start + runningOffset, ts.textSpanEnd(edits[j].span) + runningOffset, edits[j].newText); this.updateMarkersForEdit(fileName, edits[j].span.start + runningOffset, ts.textSpanEnd(edits[j].span) + runningOffset, edits[j].newText); - let change = (edits[j].span.start - ts.textSpanEnd(edits[j].span)) + edits[j].newText.length; + const change = (edits[j].span.start - ts.textSpanEnd(edits[j].span)) + edits[j].newText.length; runningOffset += change; // TODO: Consider doing this at least some of the time for higher fidelity. Currently causes a failure (bug 707150) // this.languageService.getScriptLexicalStructure(fileName); } if (isFormattingEdit) { - let newContent = this.getFileContent(fileName); + const newContent = this.getFileContent(fileName); if (newContent.replace(/\s/g, "") !== oldContent.replace(/\s/g, "")) { this.raiseError("Formatting operation destroyed non-whitespace content"); @@ -1552,7 +1552,7 @@ namespace FourSlash { } public setFormatOptions(formatCodeOptions: ts.FormatCodeOptions): ts.FormatCodeOptions { - let oldFormatCodeOptions = this.formatCodeOptions; + const oldFormatCodeOptions = this.formatCodeOptions; this.formatCodeOptions = formatCodeOptions; return oldFormatCodeOptions; } @@ -1560,7 +1560,7 @@ namespace FourSlash { public formatDocument() { this.scenarioActions.push(""); - let edits = this.languageService.getFormattingEditsForDocument(this.activeFile.fileName, this.formatCodeOptions); + const edits = this.languageService.getFormattingEditsForDocument(this.activeFile.fileName, this.formatCodeOptions); this.currentCaretPosition += this.applyEdits(this.activeFile.fileName, edits, true); this.fixCaretPosition(); } @@ -1568,14 +1568,14 @@ namespace FourSlash { public formatSelection(start: number, end: number) { this.taoInvalidReason = "formatSelection NYI"; - let edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, end, this.formatCodeOptions); + const edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, end, this.formatCodeOptions); this.currentCaretPosition += this.applyEdits(this.activeFile.fileName, edits, true); this.fixCaretPosition(); } private updateMarkersForEdit(fileName: string, minChar: number, limChar: number, text: string) { for (let i = 0; i < this.testData.markers.length; i++) { - let marker = this.testData.markers[i]; + const marker = this.testData.markers[i]; if (marker.fileName === fileName) { if (marker.position > minChar) { if (marker.position < limChar) { @@ -1596,7 +1596,7 @@ namespace FourSlash { } public goToEOF() { - let len = this.getFileContent(this.activeFile.fileName).length; + const len = this.getFileContent(this.activeFile.fileName).length; this.goToPosition(len); } @@ -1608,7 +1608,7 @@ namespace FourSlash { this.taoInvalidReason = "GoToDefinition not supported for non-zero definition indices"; } - let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); if (!definitions || !definitions.length) { this.raiseError("goToDefinition failed - expected to at least one definition location but got 0"); } @@ -1617,7 +1617,7 @@ namespace FourSlash { this.raiseError(`goToDefinition failed - definitionIndex value (${definitionIndex}) exceeds definition list size (${definitions.length})`); } - let definition = definitions[definitionIndex]; + const definition = definitions[definitionIndex]; this.openFile(definition.fileName); this.currentCaretPosition = definition.textSpan.start; } @@ -1630,7 +1630,7 @@ namespace FourSlash { this.taoInvalidReason = "GoToTypeDefinition not supported for non-zero definition indices"; } - let definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); if (!definitions || !definitions.length) { this.raiseError("goToTypeDefinition failed - expected to at least one definition location but got 0"); } @@ -1639,7 +1639,7 @@ namespace FourSlash { this.raiseError(`goToTypeDefinition failed - definitionIndex value (${definitionIndex}) exceeds definition list size (${definitions.length})`); } - let definition = definitions[definitionIndex]; + const definition = definitions[definitionIndex]; this.openFile(definition.fileName); this.currentCaretPosition = definition.textSpan.start; } @@ -1647,9 +1647,9 @@ namespace FourSlash { public verifyDefinitionLocationExists(negative: boolean) { this.taoInvalidReason = "verifyDefinitionLocationExists NYI"; - let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); - let foundDefinitions = definitions && definitions.length; + const foundDefinitions = definitions && definitions.length; if (foundDefinitions && negative) { this.raiseError(`goToDefinition - expected to 0 definition locations but got ${definitions.length}`); @@ -1660,19 +1660,19 @@ namespace FourSlash { } public verifyDefinitionsCount(negative: boolean, expectedCount: number) { - let assertFn = negative ? assert.notEqual : assert.equal; + const assertFn = negative ? assert.notEqual : assert.equal; - let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); - let actualCount = definitions && definitions.length || 0; + const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actualCount = definitions && definitions.length || 0; assertFn(actualCount, expectedCount, this.messageAtLastKnownMarker("Definitions Count")); } public verifyTypeDefinitionsCount(negative: boolean, expectedCount: number) { - let assertFn = negative ? assert.notEqual : assert.equal; + const assertFn = negative ? assert.notEqual : assert.equal; - let definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); - let actualCount = definitions && definitions.length || 0; + const definitions = this.languageService.getTypeDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actualCount = definitions && definitions.length || 0; assertFn(actualCount, expectedCount, this.messageAtLastKnownMarker("Type definitions Count")); } @@ -1680,9 +1680,9 @@ namespace FourSlash { public verifyDefinitionsName(negative: boolean, expectedName: string, expectedContainerName: string) { this.taoInvalidReason = "verifyDefinititionsInfo NYI"; - let definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); - let actualDefinitionName = definitions && definitions.length ? definitions[0].name : ""; - let actualDefinitionContainerName = definitions && definitions.length ? definitions[0].containerName : ""; + const definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actualDefinitionName = definitions && definitions.length ? definitions[0].name : ""; + const actualDefinitionContainerName = definitions && definitions.length ? definitions[0].containerName : ""; if (negative) { assert.notEqual(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name")); assert.notEqual(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name")); @@ -1706,7 +1706,7 @@ namespace FourSlash { public verifyCaretAtMarker(markerName = "") { this.taoInvalidReason = "verifyCaretAtMarker NYI"; - let pos = this.getMarkerByName(markerName); + const pos = this.getMarkerByName(markerName); if (pos.fileName !== this.activeFile.fileName) { throw new Error(`verifyCaretAtMarker failed - expected to be in file "${pos.fileName}", but was in file "${this.activeFile.fileName}"`); } @@ -1717,7 +1717,7 @@ namespace FourSlash { private getIndentation(fileName: string, position: number, indentStyle: ts.IndentStyle): number { - let formatOptions = ts.clone(this.formatCodeOptions); + const formatOptions = ts.clone(this.formatCodeOptions); formatOptions.IndentStyle = indentStyle; return this.languageService.getIndentationAtPosition(fileName, position, formatOptions); @@ -1726,8 +1726,8 @@ namespace FourSlash { public verifyIndentationAtCurrentPosition(numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart) { this.taoInvalidReason = "verifyIndentationAtCurrentPosition NYI"; - let actual = this.getIndentation(this.activeFile.fileName, this.currentCaretPosition, indentStyle); - let lineCol = this.getLineColStringAtPosition(this.currentCaretPosition); + const actual = this.getIndentation(this.activeFile.fileName, this.currentCaretPosition, indentStyle); + const lineCol = this.getLineColStringAtPosition(this.currentCaretPosition); if (actual !== numberOfSpaces) { this.raiseError(`verifyIndentationAtCurrentPosition failed at ${lineCol} - expected: ${numberOfSpaces}, actual: ${actual}`); } @@ -1736,8 +1736,8 @@ namespace FourSlash { public verifyIndentationAtPosition(fileName: string, position: number, numberOfSpaces: number, indentStyle: ts.IndentStyle = ts.IndentStyle.Smart) { this.taoInvalidReason = "verifyIndentationAtPosition NYI"; - let actual = this.getIndentation(fileName, position, indentStyle); - let lineCol = this.getLineColStringAtPosition(position); + const actual = this.getIndentation(fileName, position, indentStyle); + const lineCol = this.getLineColStringAtPosition(position); if (actual !== numberOfSpaces) { this.raiseError(`verifyIndentationAtPosition failed at ${lineCol} - expected: ${numberOfSpaces}, actual: ${actual}`); } @@ -1746,7 +1746,7 @@ namespace FourSlash { public verifyCurrentLineContent(text: string) { this.taoInvalidReason = "verifyCurrentLineContent NYI"; - let actual = this.getCurrentLineContent(); + const actual = this.getCurrentLineContent(); if (actual !== text) { throw new Error("verifyCurrentLineContent\n" + "\tExpected: \"" + text + "\"\n" + @@ -1757,8 +1757,8 @@ namespace FourSlash { public verifyCurrentFileContent(text: string) { this.taoInvalidReason = "verifyCurrentFileContent NYI"; - let actual = this.getFileContent(this.activeFile.fileName); - let replaceNewlines = (str: string) => str.replace(/\r\n/g, "\n"); + const actual = this.getFileContent(this.activeFile.fileName); + const replaceNewlines = (str: string) => str.replace(/\r\n/g, "\n"); if (replaceNewlines(actual) !== replaceNewlines(text)) { throw new Error("verifyCurrentFileContent\n" + "\tExpected: \"" + text + "\"\n" + @@ -1769,7 +1769,7 @@ namespace FourSlash { public verifyTextAtCaretIs(text: string) { this.taoInvalidReason = "verifyCurrentFileContent NYI"; - let actual = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition, this.currentCaretPosition + text.length); + const actual = this.getFileContent(this.activeFile.fileName).substring(this.currentCaretPosition, this.currentCaretPosition + text.length); if (actual !== text) { throw new Error("verifyTextAtCaretIs\n" + "\tExpected: \"" + text + "\"\n" + @@ -1780,14 +1780,14 @@ namespace FourSlash { public verifyCurrentNameOrDottedNameSpanText(text: string) { this.taoInvalidReason = "verifyCurrentNameOrDottedNameSpanText NYI"; - let span = this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, this.currentCaretPosition, this.currentCaretPosition); + const span = this.languageService.getNameOrDottedNameSpan(this.activeFile.fileName, this.currentCaretPosition, this.currentCaretPosition); if (!span) { this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" + "\tExpected: \"" + text + "\"\n" + "\t Actual: undefined"); } - let actual = this.getFileContent(this.activeFile.fileName).substring(span.start, ts.textSpanEnd(span)); + const actual = this.getFileContent(this.activeFile.fileName).substring(span.start, ts.textSpanEnd(span)); if (actual !== text) { this.raiseError("verifyCurrentNameOrDottedNameSpanText\n" + "\tExpected: \"" + text + "\"\n" + @@ -1825,10 +1825,10 @@ namespace FourSlash { } for (let i = 0; i < expected.length; i++) { - let expectedClassification = expected[i]; - let actualClassification = actual[i]; + const expectedClassification = expected[i]; + const actualClassification = actual[i]; - let expectedType: string = (ts.ClassificationTypeNames)[expectedClassification.classificationType]; + const expectedType: string = (ts.ClassificationTypeNames)[expectedClassification.classificationType]; if (expectedType !== actualClassification.classificationType) { this.raiseError("verifyClassifications failed - expected classifications type to be " + expectedType + ", but was " + @@ -1836,11 +1836,11 @@ namespace FourSlash { jsonMismatchString()); } - let expectedSpan = expectedClassification.textSpan; - let actualSpan = actualClassification.textSpan; + const expectedSpan = expectedClassification.textSpan; + const actualSpan = actualClassification.textSpan; if (expectedSpan) { - let expectedLength = expectedSpan.end - expectedSpan.start; + const expectedLength = expectedSpan.end - expectedSpan.start; if (expectedSpan.start !== actualSpan.start || expectedLength !== actualSpan.length) { this.raiseError("verifyClassifications failed - expected span of text to be " + @@ -1850,7 +1850,7 @@ namespace FourSlash { } } - let actualText = this.activeFile.content.substr(actualSpan.start, actualSpan.length); + const actualText = this.activeFile.content.substr(actualSpan.start, actualSpan.length); if (expectedClassification.text !== actualText) { this.raiseError("verifyClassifications failed - expected classified text to be " + expectedClassification.text + ", but was " + @@ -1868,7 +1868,7 @@ namespace FourSlash { public verifyProjectInfo(expected: string[]) { if (this.testType === FourSlashTestType.Server) { - let actual = (this.languageService).getProjectInfo( + const actual = (this.languageService).getProjectInfo( this.activeFile.fileName, /* needFileNameList */ true ); @@ -1882,14 +1882,14 @@ namespace FourSlash { } public verifySemanticClassifications(expected: { classificationType: string; text: string }[]) { - let actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, + const actual = this.languageService.getSemanticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length)); this.verifyClassifications(expected, actual); } public verifySyntacticClassifications(expected: { classificationType: string; text: string }[]) { - let actual = this.languageService.getSyntacticClassifications(this.activeFile.fileName, + const actual = this.languageService.getSyntacticClassifications(this.activeFile.fileName, ts.createTextSpan(0, this.activeFile.content.length)); this.verifyClassifications(expected, actual); @@ -1898,15 +1898,15 @@ namespace FourSlash { public verifyOutliningSpans(spans: TextSpan[]) { this.taoInvalidReason = "verifyOutliningSpans NYI"; - let actual = this.languageService.getOutliningSpans(this.activeFile.fileName); + const actual = this.languageService.getOutliningSpans(this.activeFile.fileName); if (actual.length !== spans.length) { this.raiseError(`verifyOutliningSpans failed - expected total spans to be ${spans.length}, but was ${actual.length}`); } for (let i = 0; i < spans.length; i++) { - let expectedSpan = spans[i]; - let actualSpan = actual[i]; + const expectedSpan = spans[i]; + const actualSpan = actual[i]; if (expectedSpan.start !== actualSpan.textSpan.start || expectedSpan.end !== ts.textSpanEnd(actualSpan.textSpan)) { this.raiseError(`verifyOutliningSpans failed - span ${(i + 1)} expected: (${expectedSpan.start},${expectedSpan.end}), actual: (${actualSpan.textSpan.start},${ts.textSpanEnd(actualSpan.textSpan)})`); } @@ -1914,7 +1914,7 @@ namespace FourSlash { } public verifyTodoComments(descriptors: string[], spans: TextSpan[]) { - let actual = this.languageService.getTodoComments(this.activeFile.fileName, + const actual = this.languageService.getTodoComments(this.activeFile.fileName, descriptors.map(d => { return { text: d, priority: 0 }; })); if (actual.length !== spans.length) { @@ -1922,9 +1922,9 @@ namespace FourSlash { } for (let i = 0; i < spans.length; i++) { - let expectedSpan = spans[i]; - let actualComment = actual[i]; - let actualCommentSpan = ts.createTextSpan(actualComment.position, actualComment.message.length); + const expectedSpan = spans[i]; + const actualComment = actual[i]; + const actualCommentSpan = ts.createTextSpan(actualComment.position, actualComment.message.length); if (expectedSpan.start !== actualCommentSpan.start || expectedSpan.end !== ts.textSpanEnd(actualCommentSpan)) { this.raiseError(`verifyOutliningSpans failed - span ${(i + 1)} expected: (${expectedSpan.start},${expectedSpan.end}), actual: (${actualCommentSpan.start},${ts.textSpanEnd(actualCommentSpan)})`); @@ -1934,7 +1934,7 @@ namespace FourSlash { public verifyDocCommentTemplate(expected?: ts.TextInsertion) { const name = "verifyDocCommentTemplate"; - let actual = this.languageService.getDocCommentTemplateAtPosition(this.activeFile.fileName, this.currentCaretPosition); + const actual = this.languageService.getDocCommentTemplateAtPosition(this.activeFile.fileName, this.currentCaretPosition); if (expected === undefined) { if (actual) { @@ -1968,7 +1968,7 @@ namespace FourSlash { public verifyMatchingBracePosition(bracePosition: number, expectedMatchPosition: number) { this.taoInvalidReason = "verifyMatchingBracePosition NYI"; - let actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition); + const actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition); if (actual.length !== 2) { this.raiseError(`verifyMatchingBracePosition failed - expected result to contain 2 spans, but it had ${actual.length}`); @@ -1993,7 +1993,7 @@ namespace FourSlash { public verifyNoMatchingBracePosition(bracePosition: number) { this.taoInvalidReason = "verifyNoMatchingBracePosition NYI"; - let actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition); + const actual = this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, bracePosition); if (actual.length !== 0) { this.raiseError("verifyNoMatchingBracePosition failed - expected: 0 spans, actual: " + actual.length); @@ -2007,7 +2007,7 @@ namespace FourSlash { public verifyNavigationItemsCount(expected: number, searchValue: string, matchKind?: string) { this.taoInvalidReason = "verifyNavigationItemsCount NYI"; - let items = this.languageService.getNavigateToItems(searchValue); + const items = this.languageService.getNavigateToItems(searchValue); let actual = 0; let item: ts.NavigateToItem = null; @@ -2037,14 +2037,14 @@ namespace FourSlash { parentName?: string) { this.taoInvalidReason = "verifyNavigationItemsListContains NYI"; - let items = this.languageService.getNavigateToItems(searchValue); + const items = this.languageService.getNavigateToItems(searchValue); if (!items || items.length === 0) { this.raiseError("verifyNavigationItemsListContains failed - found 0 navigation items, expected at least one."); } for (let i = 0; i < items.length; i++) { - let item = items[i]; + const item = items[i]; if (item && item.name === name && item.kind === kind && (matchKind === undefined || item.matchKind === matchKind) && (fileName === undefined || item.fileName === fileName) && @@ -2055,7 +2055,7 @@ namespace FourSlash { // if there was an explicit match kind specified, then it should be validated. if (matchKind !== undefined) { - let missingItem = { name: name, kind: kind, searchValue: searchValue, matchKind: matchKind, fileName: fileName, parentName: parentName }; + const missingItem = { name: name, kind: kind, searchValue: searchValue, matchKind: matchKind, fileName: fileName, parentName: parentName }; this.raiseError(`verifyNavigationItemsListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(items)})`); } } @@ -2063,8 +2063,8 @@ namespace FourSlash { public verifyGetScriptLexicalStructureListCount(expected: number) { this.taoInvalidReason = "verifyNavigationItemsListContains impossible"; - let items = this.languageService.getNavigationBarItems(this.activeFile.fileName); - let actual = this.getNavigationBarItemsCount(items); + const items = this.languageService.getNavigationBarItems(this.activeFile.fileName); + const actual = this.getNavigationBarItemsCount(items); if (expected !== actual) { this.raiseError(`verifyGetScriptLexicalStructureListCount failed - found: ${actual} navigation items, expected: ${expected}.`); @@ -2086,7 +2086,7 @@ namespace FourSlash { public verifyGetScriptLexicalStructureListContains(name: string, kind: string) { this.taoInvalidReason = "verifyGetScriptLexicalStructureListContains impossible"; - let items = this.languageService.getNavigationBarItems(this.activeFile.fileName); + const items = this.languageService.getNavigationBarItems(this.activeFile.fileName); if (!items || items.length === 0) { this.raiseError("verifyGetScriptLexicalStructureListContains failed - found 0 navigation items, expected at least one."); @@ -2096,14 +2096,14 @@ namespace FourSlash { return; } - let missingItem = { name: name, kind: kind }; + const missingItem = { name: name, kind: kind }; this.raiseError(`verifyGetScriptLexicalStructureListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(items, null, " ")})`); } private navigationBarItemsContains(items: ts.NavigationBarItem[], name: string, kind: string) { if (items) { for (let i = 0; i < items.length; i++) { - let item = items[i]; + const item = items[i]; if (item && item.text === name && item.kind === kind) { return true; } @@ -2118,25 +2118,25 @@ namespace FourSlash { } public printNavigationItems(searchValue: string) { - let items = this.languageService.getNavigateToItems(searchValue); - let length = items && items.length; + const items = this.languageService.getNavigateToItems(searchValue); + const length = items && items.length; Harness.IO.log(`NavigationItems list (${length} items)`); for (let i = 0; i < length; i++) { - let item = items[i]; + const item = items[i]; Harness.IO.log(`name: ${item.name}, kind: ${item.kind}, parentName: ${item.containerName}, fileName: ${item.fileName}`); } } public printScriptLexicalStructureItems() { - let items = this.languageService.getNavigationBarItems(this.activeFile.fileName); - let length = items && items.length; + const items = this.languageService.getNavigationBarItems(this.activeFile.fileName); + const length = items && items.length; Harness.IO.log(`NavigationItems list (${length} items)`); for (let i = 0; i < length; i++) { - let item = items[i]; + const item = items[i]; Harness.IO.log(`name: ${item.text}, kind: ${item.kind}`); } } @@ -2148,13 +2148,13 @@ namespace FourSlash { public verifyOccurrencesAtPositionListContains(fileName: string, start: number, end: number, isWriteAccess?: boolean) { this.taoInvalidReason = "verifyOccurrencesAtPositionListContains NYI"; - let occurrences = this.getOccurrencesAtCurrentPosition(); + const occurrences = this.getOccurrencesAtCurrentPosition(); if (!occurrences || occurrences.length === 0) { this.raiseError("verifyOccurrencesAtPositionListContains failed - found 0 references, expected at least one."); } - for (let occurrence of occurrences) { + for (const occurrence of occurrences) { if (occurrence && occurrence.fileName === fileName && occurrence.textSpan.start === start && ts.textSpanEnd(occurrence.textSpan) === end) { if (typeof isWriteAccess !== "undefined" && occurrence.isWriteAccess !== isWriteAccess) { this.raiseError(`verifyOccurrencesAtPositionListContains failed - item isWriteAccess value does not match, actual: ${occurrence.isWriteAccess}, expected: ${isWriteAccess}.`); @@ -2163,39 +2163,39 @@ namespace FourSlash { } } - let missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess }; + const missingItem = { fileName: fileName, start: start, end: end, isWriteAccess: isWriteAccess }; this.raiseError(`verifyOccurrencesAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(occurrences)})`); } public verifyOccurrencesAtPositionListCount(expectedCount: number) { this.taoInvalidReason = "verifyOccurrencesAtPositionListCount NYI"; - let occurrences = this.getOccurrencesAtCurrentPosition(); - let actualCount = occurrences ? occurrences.length : 0; + const occurrences = this.getOccurrencesAtCurrentPosition(); + const actualCount = occurrences ? occurrences.length : 0; if (expectedCount !== actualCount) { this.raiseError(`verifyOccurrencesAtPositionListCount failed - actual: ${actualCount}, expected:${expectedCount}`); } } private getDocumentHighlightsAtCurrentPosition(fileNamesToSearch: string[]) { - let filesToSearch = fileNamesToSearch.map(name => ts.combinePaths(this.basePath, name)); + const filesToSearch = fileNamesToSearch.map(name => ts.combinePaths(this.basePath, name)); return this.languageService.getDocumentHighlights(this.activeFile.fileName, this.currentCaretPosition, filesToSearch); } public verifyDocumentHighlightsAtPositionListContains(fileName: string, start: number, end: number, fileNamesToSearch: string[], kind?: string) { this.taoInvalidReason = "verifyDocumentHighlightsAtPositionListContains NYI"; - let documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch); + const documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch); if (!documentHighlights || documentHighlights.length === 0) { this.raiseError("verifyDocumentHighlightsAtPositionListContains failed - found 0 highlights, expected at least one."); } - for (let documentHighlight of documentHighlights) { + for (const documentHighlight of documentHighlights) { if (documentHighlight.fileName === fileName) { - let { highlightSpans } = documentHighlight; + const { highlightSpans } = documentHighlight; - for (let highlight of highlightSpans) { + for (const highlight of highlightSpans) { if (highlight && highlight.textSpan.start === start && ts.textSpanEnd(highlight.textSpan) === end) { if (typeof kind !== "undefined" && highlight.kind !== kind) { this.raiseError(`verifyDocumentHighlightsAtPositionListContains failed - item "kind" value does not match, actual: ${highlight.kind}, expected: ${kind}.`); @@ -2206,15 +2206,15 @@ namespace FourSlash { } } - let missingItem = { fileName: fileName, start: start, end: end, kind: kind }; + const missingItem = { fileName: fileName, start: start, end: end, kind: kind }; this.raiseError(`verifyDocumentHighlightsAtPositionListContains failed - could not find the item: ${JSON.stringify(missingItem)} in the returned list: (${JSON.stringify(documentHighlights)})`); } public verifyDocumentHighlightsAtPositionListCount(expectedCount: number, fileNamesToSearch: string[]) { this.taoInvalidReason = "verifyDocumentHighlightsAtPositionListCount NYI"; - let documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch); - let actualCount = documentHighlights + const documentHighlights = this.getDocumentHighlightsAtCurrentPosition(fileNamesToSearch); + const actualCount = documentHighlights ? documentHighlights.reduce((currentCount, { highlightSpans }) => currentCount + highlightSpans.length, 0) : 0; @@ -2225,13 +2225,13 @@ namespace FourSlash { // Get the text of the entire line the caret is currently at private getCurrentLineContent() { - let text = this.getFileContent(this.activeFile.fileName); + const text = this.getFileContent(this.activeFile.fileName); - let pos = this.currentCaretPosition; + const pos = this.currentCaretPosition; let startPos = pos, endPos = pos; while (startPos > 0) { - let ch = text.charCodeAt(startPos - 1); + const ch = text.charCodeAt(startPos - 1); if (ch === ts.CharacterCodes.carriageReturn || ch === ts.CharacterCodes.lineFeed) { break; } @@ -2240,7 +2240,7 @@ namespace FourSlash { } while (endPos < text.length) { - let ch = text.charCodeAt(endPos); + const ch = text.charCodeAt(endPos); if (ch === ts.CharacterCodes.carriageReturn || ch === ts.CharacterCodes.lineFeed) { break; @@ -2261,10 +2261,10 @@ namespace FourSlash { } for (let i = 0; i < items.length; i++) { - let item = items[i]; + const item = items[i]; if (item.name === name) { if (documentation != undefined || text !== undefined) { - let details = this.getCompletionEntryDetails(item.name); + const details = this.getCompletionEntryDetails(item.name); if (documentation !== undefined) { assert.equal(ts.displayPartsToString(details.documentation), documentation, assertionMessage("completion item documentation")); @@ -2282,7 +2282,7 @@ namespace FourSlash { } } - let itemsString = items.map((item) => JSON.stringify({ name: item.name, kind: item.kind })).join(",\n"); + const itemsString = items.map((item) => JSON.stringify({ name: item.name, kind: item.kind })).join(",\n"); this.raiseError(`Expected "${JSON.stringify({ name, text, documentation, kind })}" to be in list [${itemsString}]`); } @@ -2290,7 +2290,7 @@ namespace FourSlash { private findFile(indexOrName: any) { let result: FourSlashFile = null; if (typeof indexOrName === "number") { - let index = indexOrName; + const index = indexOrName; if (index >= this.testData.files.length) { throw new Error(`File index (${index}) in openFile was out of range. There are only ${this.testData.files.length} files in this test.`); } @@ -2304,10 +2304,10 @@ namespace FourSlash { // names are stored in the compiler with this relative path, this allows people to use goTo.file on just the fileName name = name.indexOf("/") === -1 ? (this.basePath + "/" + name) : name; - let availableNames: string[] = []; + const availableNames: string[] = []; let foundIt = false; for (let i = 0; i < this.testData.files.length; i++) { - let fn = this.testData.files[i].fileName; + const fn = this.testData.files[i].fileName; if (fn) { if (fn === name) { result = this.testData.files[i]; @@ -2330,15 +2330,15 @@ namespace FourSlash { } private getLineColStringAtPosition(position: number) { - let pos = this.languageServiceAdapterHost.positionToLineAndCharacter(this.activeFile.fileName, position); + const pos = this.languageServiceAdapterHost.positionToLineAndCharacter(this.activeFile.fileName, position); return `line ${(pos.line + 1)}, col ${pos.character}`; } public getMarkerByName(markerName: string) { - let markerPos = this.testData.markerPositions[markerName]; + const markerPos = this.testData.markerPositions[markerName]; if (markerPos === undefined) { - let markerNames: string[] = []; - for (let m in this.testData.markerPositions) markerNames.push(m); + const markerNames: string[] = []; + for (const m in this.testData.markerPositions) markerNames.push(m); throw new Error(`Unknown marker "${markerName}" Available markers: ${markerNames.map(m => "\"" + m + "\"").join(", ")}`); } else { @@ -2368,12 +2368,12 @@ namespace FourSlash { } // TOOD: should these just use the Harness's stdout/stderr? - let fsOutput = new Harness.Compiler.WriterAggregator(); - let fsErrors = new Harness.Compiler.WriterAggregator(); + const fsOutput = new Harness.Compiler.WriterAggregator(); + const fsErrors = new Harness.Compiler.WriterAggregator(); export let xmlData: TestXmlData[] = []; export function runFourSlashTest(basePath: string, testType: FourSlashTestType, fileName: string) { - let content = Harness.IO.readFile(fileName); - let xml = runFourSlashTestContent(basePath, testType, content, fileName); + const content = Harness.IO.readFile(fileName); + const xml = runFourSlashTestContent(basePath, testType, content, fileName); xmlData.push(xml); } @@ -2381,12 +2381,12 @@ namespace FourSlash { // here we cache the JS output and reuse it for every test. let fourslashJsOutput: string; { - let host = Harness.Compiler.createCompilerHost([{ unitName: Harness.Compiler.fourslashFileName, content: undefined }], + const host = Harness.Compiler.createCompilerHost([{ unitName: Harness.Compiler.fourslashFileName, content: undefined }], (fn, contents) => fourslashJsOutput = contents, ts.ScriptTarget.Latest, Harness.IO.useCaseSensitiveFileNames()); - let program = ts.createProgram([Harness.Compiler.fourslashFileName], { noResolve: true, target: ts.ScriptTarget.ES3 }, host); + const program = ts.createProgram([Harness.Compiler.fourslashFileName], { noResolve: true, target: ts.ScriptTarget.ES3 }, host); program.emit(host.getSourceFile(Harness.Compiler.fourslashFileName, ts.ScriptTarget.ES3)); } @@ -2394,12 +2394,12 @@ namespace FourSlash { export function runFourSlashTestContent(basePath: string, testType: FourSlashTestType, content: string, fileName: string): TestXmlData { // Parse out the files and their metadata - let testData = parseTestData(basePath, content, fileName); + const testData = parseTestData(basePath, content, fileName); currentTestState = new TestState(basePath, testType, testData); let result = ""; - let host = Harness.Compiler.createCompilerHost( + const host = Harness.Compiler.createCompilerHost( [ { unitName: Harness.Compiler.fourslashFileName, content: undefined }, { unitName: fileName, content: content } @@ -2408,11 +2408,11 @@ namespace FourSlash { ts.ScriptTarget.Latest, Harness.IO.useCaseSensitiveFileNames()); - let program = ts.createProgram([Harness.Compiler.fourslashFileName, fileName], { outFile: "fourslashTestOutput.js", noResolve: true, target: ts.ScriptTarget.ES3 }, host); + const program = ts.createProgram([Harness.Compiler.fourslashFileName, fileName], { outFile: "fourslashTestOutput.js", noResolve: true, target: ts.ScriptTarget.ES3 }, host); - let sourceFile = host.getSourceFile(fileName, ts.ScriptTarget.ES3); + const sourceFile = host.getSourceFile(fileName, ts.ScriptTarget.ES3); - let diagnostics = ts.getPreEmitDiagnostics(program, sourceFile); + const diagnostics = ts.getPreEmitDiagnostics(program, sourceFile); if (diagnostics.length > 0) { throw new Error(`Error compiling ${fileName}: ` + diagnostics.map(e => ts.flattenDiagnosticMessageText(e.messageText, Harness.IO.newLine())).join("\r\n")); @@ -2432,13 +2432,13 @@ namespace FourSlash { throw err; } - let xmlData = currentTestState.getTestXmlData(); + const xmlData = currentTestState.getTestXmlData(); xmlData.originalName = fileName; return xmlData; } function chompLeadingSpace(content: string) { - let lines = content.split("\n"); + const lines = content.split("\n"); for (let i = 0; i < lines.length; i++) { if ((lines[i].length !== 0) && (lines[i].charAt(0) !== " ")) { return content; @@ -2450,22 +2450,22 @@ namespace FourSlash { function parseTestData(basePath: string, contents: string, fileName: string): FourSlashData { // Regex for parsing options in the format "@Alpha: Value of any sort" - let optionRegex = /^\s*@(\w+): (.*)\s*/; + const optionRegex = /^\s*@(\w+): (.*)\s*/; // List of all the subfiles we've parsed out - let files: FourSlashFile[] = []; + const files: FourSlashFile[] = []; // Global options - let globalOptions: { [s: string]: string; } = {}; + const globalOptions: { [s: string]: string; } = {}; // Marker positions // Split up the input file by line // Note: IE JS engine incorrectly handles consecutive delimiters here when using RegExp split, so // we have to string-based splitting instead and try to figure out the delimiting chars - let lines = contents.split("\n"); + const lines = contents.split("\n"); - let markerPositions: MarkerMap = {}; - let markers: Marker[] = []; - let ranges: Range[] = []; + const markerPositions: MarkerMap = {}; + const markers: Marker[] = []; + const ranges: Range[] = []; // Stuff related to the subfile we're parsing let currentFileContent: string = null; @@ -2474,7 +2474,7 @@ namespace FourSlash { for (let i = 0; i < lines.length; i++) { let line = lines[i]; - let lineLength = line.length; + const lineLength = line.length; if (lineLength > 0 && line.charAt(lineLength - 1) === "\r") { line = line.substr(0, lineLength - 1); @@ -2496,9 +2496,9 @@ namespace FourSlash { } else if (line.substr(0, 2) === "//") { // Comment line, check for global/file @options and record them - let match = optionRegex.exec(line.substr(2)); + const match = optionRegex.exec(line.substr(2)); if (match) { - let fileMetadataNamesIndex = fileMetadataNames.indexOf(match[1]); + const fileMetadataNamesIndex = fileMetadataNames.indexOf(match[1]); if (fileMetadataNamesIndex === -1) { // Check if the match is already existed in the global options if (globalOptions[match[1]] !== undefined) { @@ -2510,7 +2510,7 @@ namespace FourSlash { if (fileMetadataNamesIndex === fileMetadataNames.indexOf(metadataOptionNames.fileName)) { // Found an @FileName directive, if this is not the first then create a new subfile if (currentFileContent) { - let file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); + const file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); file.fileOptions = currentFileOptions; // Store result file @@ -2540,7 +2540,7 @@ namespace FourSlash { else { // Empty line or code line, terminate current subfile if there is one if (currentFileContent) { - let file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); + const file = parseFileContent(currentFileContent, currentFileName, markerPositions, markers, ranges); file.fileOptions = currentFileOptions; // Store result file @@ -2583,7 +2583,7 @@ namespace FourSlash { } function getNonFileNameOptionInObject(optionObject: { [s: string]: string }): string { - for (let option in optionObject) { + for (const option in optionObject) { if (option !== metadataOptionNames.fileName) { return option; } @@ -2598,7 +2598,7 @@ namespace FourSlash { } function reportError(fileName: string, line: number, col: number, message: string) { - let errorMessage = fileName + "(" + line + "," + col + "): " + message; + const errorMessage = fileName + "(" + line + "," + col + "): " + message; throw new Error(errorMessage); } @@ -2617,7 +2617,7 @@ namespace FourSlash { return null; } - let marker: Marker = { + const marker: Marker = { fileName: fileName, position: location.position, data: markerValue @@ -2634,14 +2634,14 @@ namespace FourSlash { } function recordMarker(fileName: string, location: ILocationInformation, name: string, markerMap: MarkerMap, markers: Marker[]): Marker { - let marker: Marker = { + const marker: Marker = { fileName: fileName, position: location.position }; // Verify markers for uniqueness if (markerMap[name] !== undefined) { - let message = "Marker '" + name + "' is duplicated in the source file contents."; + const message = "Marker '" + name + "' is duplicated in the source file contents."; reportError(marker.fileName, location.sourceLine, location.sourceColumn, message); return null; } @@ -2656,7 +2656,7 @@ namespace FourSlash { content = chompLeadingSpace(content); // Any slash-star comment with a character not in this string is not a marker. - let validMarkerChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$1234567890_"; + const validMarkerChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz$1234567890_"; /// The file content (minus metacharacters) so far let output = ""; @@ -2665,7 +2665,7 @@ namespace FourSlash { let openMarker: ILocationInformation = null; /// A stack of the open range markers that are still unclosed - let openRanges: IRangeLocationInformation[] = []; + const openRanges: IRangeLocationInformation[] = []; /// A list of ranges we've collected so far */ let localRanges: Range[] = []; @@ -2683,7 +2683,7 @@ namespace FourSlash { let line = 1; let column = 1; - let flush = (lastSafeCharIndex: number) => { + const flush = (lastSafeCharIndex: number) => { if (lastSafeCharIndex === undefined) { output = output + content.substr(lastNormalCharPosition); } @@ -2695,7 +2695,7 @@ namespace FourSlash { if (content.length > 0) { let previousChar = content.charAt(0); for (let i = 1; i < content.length; i++) { - let currentChar = content.charAt(i); + const currentChar = content.charAt(i); switch (state) { case State.none: if (previousChar === "[" && currentChar === "|") { @@ -2713,12 +2713,12 @@ namespace FourSlash { } else if (previousChar === "|" && currentChar === "]") { // found a range end - let rangeStart = openRanges.pop(); + const rangeStart = openRanges.pop(); if (!rangeStart) { reportError(fileName, line, column, "Found range end with no matching start."); } - let range: Range = { + const range: Range = { fileName: fileName, start: rangeStart.position, end: (i - 1) - difference, @@ -2758,8 +2758,8 @@ namespace FourSlash { // Object markers are only ever terminated by |} and have no content restrictions if (previousChar === "|" && currentChar === "}") { // Record the marker - let objectMarkerNameText = content.substring(openMarker.sourcePosition + 2, i - 1).trim(); - let marker = recordObjectMarker(fileName, openMarker, objectMarkerNameText, markerMap, markers); + const objectMarkerNameText = content.substring(openMarker.sourcePosition + 2, i - 1).trim(); + const marker = recordObjectMarker(fileName, openMarker, objectMarkerNameText, markerMap, markers); if (openRanges.length > 0) { openRanges[openRanges.length - 1].marker = marker; @@ -2779,8 +2779,8 @@ namespace FourSlash { if (previousChar === "*" && currentChar === "/") { // Record the marker // start + 2 to ignore the */, -1 on the end to ignore the * (/ is next) - let markerNameText = content.substring(openMarker.sourcePosition + 2, i - 1).trim(); - let marker = recordMarker(fileName, openMarker, markerNameText, markerMap, markers); + const markerNameText = content.substring(openMarker.sourcePosition + 2, i - 1).trim(); + const marker = recordMarker(fileName, openMarker, markerNameText, markerMap, markers); if (openRanges.length > 0) { openRanges[openRanges.length - 1].marker = marker; @@ -2831,7 +2831,7 @@ namespace FourSlash { flush(undefined); if (openRanges.length > 0) { - let openRange = openRanges[0]; + const openRange = openRanges[0]; reportError(fileName, openRange.sourceLine, openRange.sourceColumn, "Unterminated range."); } diff --git a/src/harness/fourslashRunner.ts b/src/harness/fourslashRunner.ts index 867c0d5a4d6..7228f06c20f 100644 --- a/src/harness/fourslashRunner.ts +++ b/src/harness/fourslashRunner.ts @@ -45,10 +45,10 @@ class FourSlashRunner extends RunnerBase { this.tests.forEach((fn: string) => { describe(fn, () => { fn = ts.normalizeSlashes(fn); - let justName = fn.replace(/^.*[\\\/]/, ""); + const justName = fn.replace(/^.*[\\\/]/, ""); // Convert to relative path - let testIndex = fn.indexOf("tests/"); + const testIndex = fn.indexOf("tests/"); if (testIndex >= 0) fn = fn.substr(testIndex); if (justName && !justName.match(/fourslash\.ts$/i) && !justName.match(/\.d\.ts$/i)) { @@ -60,21 +60,21 @@ class FourSlashRunner extends RunnerBase { }); describe("Generate Tao XML", () => { - let invalidReasons: any = {}; + const invalidReasons: any = {}; FourSlash.xmlData.forEach(xml => { if (xml.invalidReason !== null) { invalidReasons[xml.invalidReason] = (invalidReasons[xml.invalidReason] || 0) + 1; } }); - let invalidReport: { reason: string; count: number }[] = []; - for (let reason in invalidReasons) { + const invalidReport: { reason: string; count: number }[] = []; + for (const reason in invalidReasons) { if (invalidReasons.hasOwnProperty(reason)) { invalidReport.push({ reason: reason, count: invalidReasons[reason] }); } } invalidReport.sort((lhs, rhs) => lhs.count > rhs.count ? -1 : lhs.count === rhs.count ? 0 : 1); - let lines: string[] = []; + const lines: string[] = []; lines.push("