From fc606eb4283aa0398fbb56df111427882921503d Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Mon, 13 Feb 2017 17:15:43 -0800 Subject: [PATCH] Update LKG --- lib/protocol.d.ts | 7 +- lib/tsc.js | 668 +++++++++++++++++++----------- lib/tsserver.js | 674 +++++++++++++++++++----------- lib/tsserverlibrary.d.ts | 33 +- lib/tsserverlibrary.js | 674 +++++++++++++++++++----------- lib/typescript.d.ts | 29 +- lib/typescript.js | 792 ++++++++++++++++++++++++------------ lib/typescriptServices.d.ts | 29 +- lib/typescriptServices.js | 792 ++++++++++++++++++++++++------------ lib/typingsInstaller.js | 150 ++++--- 10 files changed, 2463 insertions(+), 1385 deletions(-) diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index f6a2150bec3..b33005cf2f8 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -734,9 +734,9 @@ declare namespace ts.server.protocol { */ formatOptions?: FormatCodeSettings; /** - * The host's additional supported file extensions + * The host's additional supported .js file extensions */ - extraFileExtensions?: FileExtensionInfo[]; + extraFileExtensions?: JsFileExtensionInfo[]; } /** * Configure request; value of command field is "configure". Specifies @@ -1861,9 +1861,8 @@ declare namespace ts.server.protocol { [option: string]: string[] | boolean | undefined; } - interface FileExtensionInfo { + interface JsFileExtensionInfo { extension: string; - scriptKind: ScriptKind; isMixedContent: boolean; } diff --git a/lib/tsc.js b/lib/tsc.js index 8efa3998dfe..60288a15ae0 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -1753,13 +1753,13 @@ var ts; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0) { + if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + var extensions = allSupportedExtensions.slice(0); for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { var extInfo = extraFileExtensions_1[_i]; - if (needAllExtensions || extInfo.scriptKind === 3) { + if (extensions.indexOf(extInfo.extension) === -1) { extensions.push(extInfo.extension); } } @@ -1790,30 +1790,30 @@ var ts; function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { - return adjustExtensionPriority(i); + return adjustExtensionPriority(i, supportedExtensions); } } return 0; } ts.getExtensionPriority = getExtensionPriority; - function adjustExtensionPriority(extensionPriority) { + function adjustExtensionPriority(extensionPriority, supportedExtensions) { if (extensionPriority < 2) { return 0; } - else if (extensionPriority < 5) { + else if (extensionPriority < supportedExtensions.length) { return 2; } else { - return 5; + return supportedExtensions.length; } } ts.adjustExtensionPriority = adjustExtensionPriority; - function getNextLowestExtensionPriority(extensionPriority) { + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { if (extensionPriority < 2) { return 2; } else { - return 5; + return supportedExtensions.length; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; @@ -2679,6 +2679,7 @@ var ts; Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", message: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", message: "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", message: "Generators are only available when targeting ECMAScript 2015 or higher." }, @@ -2958,6 +2959,7 @@ var ts; Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: { code: 2543, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", message: "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference." }, Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: { code: 2544, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", message: "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference." }, A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: { code: 2545, category: ts.DiagnosticCategory.Error, key: "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", message: "A mixin class must have a constructor with a single rest parameter of type 'any[]'." }, + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: { code: 2546, category: ts.DiagnosticCategory.Error, key: "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", message: "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3211,7 +3213,7 @@ var ts; File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, Loading_module_0_from_node_modules_folder_target_file_type_1: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", message: "Loading module '{0}' from 'node_modules' folder, target file type '{1}'." }, Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_a_types_or_main_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_types_or_main_field_6100", message: "'package.json' does not have a 'types' or 'main' field." }, + package_json_does_not_have_a_0_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_0_field_6100", message: "'package.json' does not have a '{0}' field." }, package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, @@ -3248,7 +3250,6 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, - No_types_specified_in_package_json_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json', so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -6180,6 +6181,11 @@ var ts; return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); } ts.getCommentsFromJSDoc = getCommentsFromJSDoc; + function hasJSDocParameterTags(node) { + var parameterTags = getJSDocTags(node, 284); + return parameterTags && parameterTags.length > 0; + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; function getJSDocTags(node, kind) { var docs = getJSDocs(node); if (docs) { @@ -17571,7 +17577,8 @@ var ts; flowAfterCatch = currentFlow; } if (node.finallyBlock) { - addAntecedent(preFinallyLabel, preTryFlow); + var preFinallyFlow = { flags: 2048, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); if (!(currentFlow.flags & 1)) { @@ -17581,6 +17588,11 @@ var ts; : unreachableFlow; } } + if (!(currentFlow.flags & 1)) { + var afterFinallyFlow = { flags: 4096, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } } else { currentFlow = finishFlowLabel(preFinallyLabel); @@ -18280,7 +18292,7 @@ var ts; case 148: case 147: case 274: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 0); + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 67108864 : 0), 0); case 289: return bindJSDocProperty(node); case 259: @@ -18309,7 +18321,7 @@ var ts; return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 150: case 149: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 67108864 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); case 227: return bindFunctionDeclaration(node); case 151: @@ -18432,10 +18444,10 @@ var ts; } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { - bindAnonymousDeclaration(node, 1073741824, getDeclarationName(node)); + bindAnonymousDeclaration(node, 33554432, getDeclarationName(node)); } else if (!node.exportClause) { - declareSymbol(container.symbol.exports, container.symbol, node, 1073741824, 0); + declareSymbol(container.symbol.exports, container.symbol, node, 33554432, 0); } } function bindImportClause(node) { @@ -18508,7 +18520,7 @@ var ts; } } var symbol = node.symbol; - var prototypeSymbol = createSymbol(4 | 134217728, "prototype"); + var prototypeSymbol = createSymbol(4 | 16777216, "prototype"); var symbolExport = symbol.exports.get(prototypeSymbol.name); if (symbolExport) { if (node.name) { @@ -18552,7 +18564,7 @@ var ts; } if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 536870912 : 0), 0); + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 67108864 : 0), 0); } } function bindFunctionDeclaration(node) { @@ -19306,37 +19318,28 @@ var ts; return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); } ts.moduleHasNonRelativeName = moduleHasNonRelativeName; - function tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, baseDirectory, state) { + function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { var jsonContent = readJson(packageJsonPath, state.host); - switch (extensions) { - case Extensions.DtsOnly: - case Extensions.TypeScript: - return tryReadFromField("typings") || tryReadFromField("types"); - case Extensions.JavaScript: - if (typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main); - } - return ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - } - return undefined; - } + return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); - } - return typesFilePath; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } + return; } + var fileName = jsonContent[fieldName]; + if (typeof fileName !== "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + } + return; + } + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; } } function readJson(path, host) { @@ -19737,7 +19740,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state); + var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); } @@ -19750,7 +19754,7 @@ var ts; } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); } } @@ -19766,7 +19770,7 @@ var ts; } return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } @@ -19794,7 +19798,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } function directoryProbablyExists(directoryName, host) { return !host.directoryExists || host.directoryExists(directoryName); @@ -19851,45 +19855,48 @@ var ts; failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var mainOrTypesFile = tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, candidate, state); - if (mainOrTypesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(mainOrTypesFile), state.host); - var fromExactFile = tryFile(mainOrTypesFile, failedLookupLocations, onlyRecordFailures_1, state); - if (fromExactFile) { - var resolved_3 = fromExactFile && resolvedIfExtensionMatches(extensions, fromExactFile); - if (resolved_3) { - return resolved_3; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromExactFile); - } - } - var resolved = tryAddingExtensions(mainOrTypesFile, Extensions.TypeScript, failedLookupLocations, onlyRecordFailures_1, state); - if (resolved) { - return resolved; + if (considerPackageJson) { + var packageJsonPath = pathToPackageJson(candidate); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; } } else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_types_or_main_field); + if (directoryExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + failedLookupLocations.push(packageJsonPath); } } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocations.push(packageJsonPath); - } return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); } + function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + if (!file) { + return undefined; + } + var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); + var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); + if (fromFile) { + var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return resolved; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + } function resolvedIfExtensionMatches(extensions, path) { var extension = ts.tryGetExtensionFromPath(path); return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; @@ -19976,7 +19983,7 @@ var ts; } var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (moduleHasNonRelativeName(moduleName)) { - var resolved_4 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { return resolutionFromCache; @@ -19984,8 +19991,8 @@ var ts; var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state)); }); - if (resolved_4) { - return resolved_4; + if (resolved_3) { + return resolved_3; } if (extensions === Extensions.TypeScript) { return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); @@ -20067,9 +20074,9 @@ var ts; var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; var strictNullChecks = compilerOptions.strictNullChecks; var emitResolver = createResolver(); - var undefinedSymbol = createSymbol(4 | 67108864, "undefined"); + var undefinedSymbol = createSymbol(4, "undefined"); undefinedSymbol.declarations = []; - var argumentsSymbol = createSymbol(4 | 67108864, "arguments"); + var argumentsSymbol = createSymbol(4, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, @@ -20133,8 +20140,8 @@ var ts; var numericLiteralTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; - var unknownSymbol = createSymbol(4 | 67108864, "unknown"); - var resolvingSymbol = createSymbol(67108864, "__resolving__"); + var unknownSymbol = createSymbol(4, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__"); var anyType = createIntrinsicType(1, "any"); var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); @@ -20153,7 +20160,7 @@ var ts; var silentNeverType = createIntrinsicType(8192, "never"); var nonPrimitiveType = createIntrinsicType(16777216, "object"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyTypeLiteralSymbol = createSymbol(2048 | 67108864, "__type"); + var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); emptyTypeLiteralSymbol.members = ts.createMap(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -20299,7 +20306,9 @@ var ts; } function createSymbol(flags, name) { symbolCount++; - return new Symbol(flags, name); + var symbol = (new Symbol(flags | 134217728, name)); + symbol.checkFlags = 0; + return symbol; } function getExcludedSymbolFlags(flags) { var result = 0; @@ -20345,7 +20354,7 @@ var ts; mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { - var result = createSymbol(symbol.flags | 33554432, symbol.name); + var result = createSymbol(symbol.flags, symbol.name); result.declarations = symbol.declarations.slice(0); result.parent = symbol.parent; if (symbol.valueDeclaration) @@ -20404,7 +20413,7 @@ var ts; target.set(id, sourceSymbol); } else { - if (!(targetSymbol.flags & 33554432)) { + if (!(targetSymbol.flags & 134217728)) { targetSymbol = cloneSymbol(targetSymbol); target.set(id, targetSymbol); } @@ -20431,7 +20440,7 @@ var ts; } mainModule = resolveExternalModuleSymbol(mainModule); if (mainModule.flags & 1920) { - mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); + mainModule = mainModule.flags & 134217728 ? mainModule : cloneSymbol(mainModule); mergeSymbol(mainModule, moduleAugmentation.symbol); } else { @@ -20454,7 +20463,7 @@ var ts; } } function getSymbolLinks(symbol) { - if (symbol.flags & 67108864) + if (symbol.flags & 134217728) return symbol; var id = getSymbolId(symbol); return symbolLinks[id] || (symbolLinks[id] = {}); @@ -20466,6 +20475,9 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 ? type.objectFlags : 0; } + function getCheckFlags(symbol) { + return symbol.flags & 134217728 ? symbol.checkFlags : 0; + } function isGlobalSourceFile(node) { return node.kind === 263 && !ts.isExternalOrCommonJsModule(node); } @@ -20473,7 +20485,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -21083,7 +21095,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -21266,16 +21278,7 @@ var ts; : symbol; } function symbolIsValue(symbol) { - if (symbol.flags & 16777216) { - return symbolIsValue(getSymbolLinks(symbol).target); - } - if (symbol.flags & 107455) { - return true; - } - if (symbol.flags & 8388608) { - return (resolveAlias(symbol).flags & 107455) !== 0; - } - return false; + return !!(symbol.flags & 107455 || symbol.flags & 8388608 && resolveAlias(symbol).flags & 107455); } function findConstructorDeclaration(node) { var members = node.members; @@ -21698,7 +21701,7 @@ var ts; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { if (flags & 1) { - if (symbol.flags & 16777216) { + if (getCheckFlags(symbol) & 1) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -21936,7 +21939,7 @@ var ts; writeSpace(writer); } buildSymbolDisplay(prop, writer); - if (prop.flags & 536870912) { + if (prop.flags & 67108864) { writePunctuation(writer, 54); } } @@ -22096,7 +22099,11 @@ var ts; } writePunctuation(writer, 55); writeSpace(writer); - buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); + var type = getTypeOfSymbol(p); + if (isRequiredInitializedParameter(parameterNode)) { + type = includeFalsyTypes(type, 2048); + } + buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { if (bindingPattern.kind === 173) { @@ -22554,7 +22561,7 @@ var ts; getUnionType([type, checkExpressionCached(declaration.initializer)], true) : type; } - function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + function getTypeForDeclarationFromJSDocComment(declaration) { var jsdocType = ts.getJSDocType(declaration); if (jsdocType) { return getTypeFromTypeNode(jsdocType); @@ -22572,9 +22579,17 @@ var ts; function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } + function removeOptionalityFromAnnotation(annotatedType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 145 && + declaration.initializer && + getFalsyFlags(annotatedType) & 2048 && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); + return annotationIncludesUndefined ? getNonNullableType(annotatedType) : annotatedType; + } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536) { - var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); + var type = getTypeForDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { return type; } @@ -22590,7 +22605,8 @@ var ts; return getTypeForBindingElement(declaration); } if (declaration.type) { - return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); + var declaredType = removeOptionalityFromAnnotation(getTypeFromTypeNode(declaration.type), declaration); + return addOptionality(declaredType, declaration.questionToken && includeOptionality); } if ((compilerOptions.noImplicitAny || declaration.flags & 65536) && declaration.kind === 225 && !ts.isBindingPattern(declaration.name) && @@ -22639,6 +22655,21 @@ var ts; } return undefined; } + function getTypeForJSSpecialPropertyDeclaration(declaration) { + var expression = declaration.kind === 193 ? declaration : + declaration.kind === 178 ? ts.getAncestor(declaration, 193) : + undefined; + if (!expression) { + return unknownType; + } + if (expression.flags & 65536) { + var type = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type && type !== unknownType) { + return getWidenedType(type); + } + } + return getWidenedLiteralType(checkExpressionCached(expression.right)); + } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { return checkDeclarationInitializer(element); @@ -22666,7 +22697,7 @@ var ts; return; } var text = ts.getTextOfPropertyName(name); - var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); + var flags = 4 | (e.initializer ? 67108864 : 0); var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; @@ -22727,7 +22758,7 @@ var ts; function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.flags & 134217728) { + if (symbol.flags & 16777216) { return links.type = getTypeOfPrototypeProperty(symbol); } var declaration = symbol.valueDeclaration; @@ -22746,16 +22777,7 @@ var ts; var type = void 0; if (declaration.kind === 193 || declaration.kind === 178 && declaration.parent.kind === 193) { - if (declaration.flags & 65536) { - var jsdocType = ts.getJSDocType(declaration.parent); - if (jsdocType) { - return links.type = getTypeFromTypeNode(jsdocType); - } - } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 193 ? - checkExpressionCached(decl.right) : - checkExpressionCached(decl.parent.right); }); - type = getUnionType(declaredTypes, true); + type = getWidenedType(getUnionType(ts.map(symbol.declarations, getTypeForJSSpecialPropertyDeclaration), true)); } else { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); @@ -22792,7 +22814,7 @@ var ts; var getter = ts.getDeclarationOfKind(symbol, 152); var setter = ts.getDeclarationOfKind(symbol, 153); if (getter && getter.flags & 65536) { - var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; } @@ -22856,7 +22878,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 536870912 ? includeFalsyTypes(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 67108864 ? includeFalsyTypes(type, 2048) : type; } } } @@ -22904,7 +22926,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (symbol.flags & 16777216) { + if (getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -23596,7 +23618,7 @@ var ts; s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); - s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); + s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); } s.resolvedReturnType = undefined; s.unionSignatures = unionSignatures; @@ -23754,10 +23776,10 @@ var ts; if (t.flags & 32) { var propName = t.text; var modifiersProp = getPropertyOfType(modifiersType, propName); - var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912); - var prop = createSymbol(4 | 67108864 | (isOptional ? 536870912 : 0), propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); + var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); + prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 4 : 0; prop.type = propType; - prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); if (propertySymbol) { prop.mappedTypeOrigin = propertySymbol; } @@ -23950,18 +23972,19 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var types = containingType.types; - var excludeModifiers = containingType.flags & 65536 ? 8 | 16 : 0; var props; - var commonFlags = (containingType.flags & 131072) ? 536870912 : 0; - var isReadonly = false; - var isPartial = false; + var types = containingType.types; + var isUnion = containingType.flags & 65536; + var excludeModifiers = isUnion ? 24 : 0; + var commonFlags = isUnion ? 0 : 67108864; + var checkFlags = 2; for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & excludeModifiers)) { + var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { props = [prop]; @@ -23969,25 +23992,26 @@ var ts; else if (!ts.contains(props, prop)) { props.push(prop); } - if (isReadonlySymbol(prop)) { - isReadonly = true; - } + checkFlags |= (isReadonlySymbol(prop) ? 4 : 0) | + (!(modifiers & 24) ? 32 : 0) | + (modifiers & 16 ? 64 : 0) | + (modifiers & 8 ? 128 : 0) | + (modifiers & 32 ? 256 : 0); } - else if (containingType.flags & 65536) { - isPartial = true; + else if (isUnion) { + checkFlags |= 8; } } } if (!props) { return undefined; } - if (props.length === 1 && !isPartial) { + if (props.length === 1 && !(checkFlags & 8)) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -23998,17 +24022,15 @@ var ts; commonType = type; } else if (type !== commonType) { - hasNonUniformType = true; + checkFlags |= 16; } propTypes.push(type); } - var result = createSymbol(4 | 67108864 | 268435456 | commonFlags, name); + var result = createSymbol(4 | commonFlags, name); + result.checkFlags = checkFlags; result.containingType = containingType; - result.hasNonUniformType = hasNonUniformType; - result.isPartial = isPartial; result.declarations = declarations; - result.isReadonly = isReadonly; - result.type = containingType.flags & 65536 ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } function getUnionOrIntersectionProperty(type, name) { @@ -24024,7 +24046,7 @@ var ts; } function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); - return property && !(property.flags & 268435456 && property.isPartial) ? property : undefined; + return property && !(getCheckFlags(property) & 8) ? property : undefined; } function getPropertyOfType(type, name) { type = getApparentType(type); @@ -24153,6 +24175,12 @@ var ts; ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + } return false; } function createTypePredicateFromTypePredicateNode(node) { @@ -24182,6 +24210,7 @@ var ts; var hasThisParameter = void 0; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { var param = declaration.parameters[i]; var paramSymbol = param.symbol; @@ -24201,7 +24230,8 @@ var ts; } var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param); + isJSDocOptionalParameter(param) || + isUntypedSignatureInJSFile; if (!isOptionalParameter_1) { minArgumentCount = parameters.length; } @@ -24673,7 +24703,7 @@ var ts; for (var i = 0; i < arity; i++) { var typeParameter = createType(16384); typeParameters.push(typeParameter); - var property = createSymbol(4 | 67108864, "" + i); + var property = createSymbol(4, "" + i); property.type = typeParameter; properties.push(property); } @@ -24888,7 +24918,10 @@ var ts; if (type.flags & 65536 && typeSet.unionIndex === undefined) { typeSet.unionIndex = typeSet.length; } - typeSet.push(type); + if (!(type.flags & 32768 && type.objectFlags & 16 && + type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + typeSet.push(type); + } } } function addTypesToIntersection(typeSet, types) { @@ -25170,15 +25203,15 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 536870912) { + if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 67108864) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); - var flags = 4 | 67108864 | (leftProp.flags & 536870912); + var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); + result.checkFlags = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp) ? 4 : 0; result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; - result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp); members.set(leftProp.name, result); } } @@ -25469,12 +25502,13 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (symbol.flags & 16777216) { + if (getCheckFlags(symbol) & 1) { var links = getSymbolLinks(symbol); symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); } - var result = createSymbol(16777216 | 67108864 | symbol.flags, symbol.name); + var result = createSymbol(symbol.flags, symbol.name); + result.checkFlags = 1; result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -26255,20 +26289,42 @@ var ts; if (target.flags & 65536 && containsType(targetTypes, source)) { return -1; } - var len = targetTypes.length; - for (var i = 0; i < len; i++) { - var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, false); if (related) { return related; } } + if (reportErrors) { + var discriminantType = findMatchingDiscriminantType(source, target); + isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], true); + } return 0; } + function findMatchingDiscriminantType(source, target) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProperty = sourceProperties_1[_i]; + if (isDiscriminantProperty(target, sourceProperty.name)) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _a = 0, _b = target.types; _a < _b.length; _a++) { + var type = _b[_a]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.name); + if (targetType && isRelatedTo(sourceType, targetType)) { + return type; + } + } + } + } + } + } function typeRelatedToEachType(source, target, reportErrors) { var result = -1; var targetTypes = target.types; - for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { - var targetType = targetTypes_1[_i]; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; var related = isRelatedTo(source, targetType, reportErrors); if (!related) { return 0; @@ -26438,17 +26494,23 @@ var ts; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { - if (!(targetProp.flags & 536870912) || requireOptionalProperties) { + if (!(targetProp.flags & 67108864) || requireOptionalProperties) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); } return 0; } } - else if (!(targetProp.flags & 134217728)) { + else if (!(targetProp.flags & 16777216)) { var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { + if (getCheckFlags(sourceProp) & 128) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); + } + return 0; + } if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { if (sourcePropFlags & 8 && targetPropFlags & 8) { @@ -26462,12 +26524,9 @@ var ts; } } else if (targetPropFlags & 16) { - var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32; - var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined; - var targetClass = getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp)); - if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { + if (!isValidOverrideOf(sourceProp, targetProp)) { if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass)); + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); } return 0; } @@ -26486,7 +26545,7 @@ var ts; return 0; } result &= related; - if (relation !== comparableRelation && sourceProp.flags & 536870912 && !(targetProp.flags & 536870912)) { + if (relation !== comparableRelation && sourceProp.flags & 67108864 && !(targetProp.flags & 67108864)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -26507,8 +26566,8 @@ var ts; return 0; } var result = -1; - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProp = sourceProperties_1[_i]; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProp = sourceProperties_2[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return 0; @@ -26669,6 +26728,37 @@ var ts; return false; } } + function forEachProperty(prop, callback) { + if (getCheckFlags(prop) & 2) { + for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var p = getPropertyOfType(t, prop.name); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + function isValidOverrideOf(sourceProp, targetProp) { + return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); + } + function isClassDerivedFromDeclaringClasses(checkClass, prop) { + return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } function isAbstractConstructorType(type) { if (getObjectFlags(type) & 16) { var symbol = type.symbol; @@ -26714,7 +26804,7 @@ var ts; } } else { - if ((sourceProp.flags & 536870912) !== (targetProp.flags & 536870912)) { + if ((sourceProp.flags & 67108864) !== (targetProp.flags & 67108864)) { return 0; } } @@ -26913,7 +27003,7 @@ var ts; types.push(undefinedType); if (flags & 4096) types.push(nullType); - return getUnionType(types, true); + return getUnionType(types); } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 ? @@ -26928,8 +27018,8 @@ var ts; getSignaturesOfType(type, 0).length === 0 && getSignaturesOfType(type, 1).length === 0; } - function createTransientSymbol(source, type) { - var symbol = createSymbol(source.flags | 67108864, source.name); + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.name); symbol.declarations = source.declarations; symbol.parent = source.parent; symbol.type = type; @@ -26945,7 +27035,7 @@ var ts; var property = _a[_i]; var original = getTypeOfSymbol(property); var updated = f(original); - members.set(property.name, updated === original ? property : createTransientSymbol(property, updated)); + members.set(property.name, updated === original ? property : createSymbolWithType(property, updated)); } ; return members; @@ -27134,7 +27224,7 @@ var ts; var typeInferencesArray = [typeInferences]; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 536870912; + var optionalMask = target.declaration.questionToken ? 0 : 67108864; var members = createSymbolTable(properties); for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; @@ -27142,10 +27232,10 @@ var ts; if (!inferredPropType) { return undefined; } - var inferredProp = createSymbol(4 | 67108864 | prop.flags & optionalMask, prop.name); + var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.name); + inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 4 : 0; inferredProp.declarations = prop.declarations; inferredProp.type = inferredPropType; - inferredProp.isReadonly = readonlyMask && isReadonlySymbol(prop); members.set(prop.name, inferredProp); } if (indexInfo) { @@ -27256,8 +27346,8 @@ var ts; var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; - for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { - var t = targetTypes_2[_d]; + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; if (t.flags & 540672 && ts.contains(typeVariables, t)) { typeVariable = t; typeVariableCount++; @@ -27539,9 +27629,9 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && prop.flags & 268435456) { + if (prop && getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.checkFlags & 16 && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -27689,10 +27779,16 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, undefined, false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - return node.parent.kind === 176 || node.parent.kind === 259 ? + var isDestructuringDefaultAssignment = node.parent.kind === 176 && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 259 && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 193 && parent.parent.left === parent || + parent.parent.kind === 215 && parent.parent.initializer === parent; + } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); } @@ -27969,7 +28065,16 @@ var ts; } } var type = void 0; - if (flow.flags & 16) { + if (flow.flags & 4096) { + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flow.flags & 2048) { + flow = flow.antecedent; + continue; + } + else if (flow.flags & 16) { type = getTypeAtFlowAssignment(flow); if (!type) { flow = flow.antecedent; @@ -28103,6 +28208,9 @@ var ts; var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; + if (antecedent.flags & 2048 && antecedent.lock.locked) { + continue; + } var flowType = getTypeAtFlowNode(antecedent); var type = getTypeFromFlowType(flowType); if (type === declaredType && declaredType === initialType) { @@ -29403,12 +29511,12 @@ var ts; type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; - var prop = createSymbol(4 | 67108864 | member.flags, member.name); + var prop = createSymbol(4 | member.flags, member.name); if (inDestructuringPattern) { var isOptional = (memberDecl.kind === 259 && hasDefaultValue(memberDecl.initializer)) || (memberDecl.kind === 260 && memberDecl.objectAssignmentInitializer); if (isOptional) { - prop.flags |= 536870912; + prop.flags |= 67108864; } if (ts.hasDynamicName(memberDecl)) { patternWithComputedProperties = true; @@ -29417,7 +29525,7 @@ var ts; else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { - prop.flags |= impliedProp.flags & 536870912; + prop.flags |= impliedProp.flags & 67108864; } else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); @@ -29474,7 +29582,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { var prop = _a[_i]; if (!propertiesTable.get(prop.name)) { - if (!(prop.flags & 536870912)) { + if (!(prop.flags & 67108864)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } propertiesTable.set(prop.name, prop); @@ -29849,7 +29957,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var _i = 0, targetProperties_1 = targetProperties; _i < targetProperties_1.length; _i++) { var targetProperty = targetProperties_1[_i]; - if (!(targetProperty.flags & 536870912) && !nameTable.get(targetProperty.name)) { + if (!(targetProperty.flags & 67108864) && !nameTable.get(targetProperty.name)) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperty.name, typeToString(targetAttributesType)); } } @@ -29871,17 +29979,35 @@ var ts; return s.valueDeclaration ? s.valueDeclaration.kind : 148; } function getDeclarationModifierFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + } + if (getCheckFlags(s) & 2) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 128 ? 8 : + checkFlags & 32 ? 4 : + 16; + var staticModifier = checkFlags & 256 ? 32 : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216) { + return 4 | 32; + } + return 0; } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } - function checkClassPropertyAccess(node, left, type, prop) { + function checkPropertyAccessibility(node, left, type, prop) { var flags = getDeclarationModifierFlagsFromSymbol(prop); - var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); var errorNode = node.kind === 178 || node.kind === 225 ? node.name : node.right; + if (getCheckFlags(prop) & 128) { + error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); + return false; + } if (left.kind === 96) { if (languageVersion < 2) { var propKind = getDeclarationKindFromSymbol(prop); @@ -29891,7 +30017,7 @@ var ts; } } if (flags & 128) { - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } } @@ -29901,7 +30027,7 @@ var ts; if (flags & 8) { var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } return true; @@ -29911,10 +30037,10 @@ var ts; } var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return hasBaseType(enclosingClass, declaringClass) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; }); if (!enclosingClass) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); return false; } if (flags & 32) { @@ -29969,7 +30095,7 @@ var ts; noUnusedIdentifiers && (prop.flags & 106500) && prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (prop.flags & 16777216) { + if (getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } else { @@ -30013,9 +30139,7 @@ var ts; } markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; - if (prop.parent && prop.parent.flags & 32) { - checkClassPropertyAccess(node, left, apparentType, prop); - } + checkPropertyAccessibility(node, left, apparentType, prop); var propType = getTypeOfSymbol(prop); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -30039,8 +30163,8 @@ var ts; var type = checkExpression(left); if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(getWidenedType(type), propertyName); - if (prop && prop.parent && prop.parent.flags & 32) { - return checkClassPropertyAccess(node, left, type, prop); + if (prop) { + return checkPropertyAccessibility(node, left, type, prop); } } return true; @@ -31021,7 +31145,7 @@ var ts; var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { if (!parameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + signature.thisParameter = createSymbolWithType(context.thisParameter, undefined); } assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } @@ -31331,11 +31455,11 @@ var ts; return true; } function isReadonlySymbol(symbol) { - return symbol.isReadonly || - symbol.flags & 4 && (getDeclarationModifierFlagsFromSymbol(symbol) & 64) !== 0 || - symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 || + return !!(getCheckFlags(symbol) & 4 || + symbol.flags & 4 && getDeclarationModifierFlagsFromSymbol(symbol) & 64 || + symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || symbol.flags & 98304 && !(symbol.flags & 65536) || - (symbol.flags & 8) !== 0; + symbol.flags & 8); } function isReferenceToReadonlyEntity(expr, symbol) { if (isReadonlySymbol(symbol)) { @@ -33598,8 +33722,8 @@ var ts; var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); markPropertyAsReferenced(property); - if (parent.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent, parent.initializer, parentType, property); + if (parent.initializer && property) { + checkPropertyAccessibility(parent, parent.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { @@ -34331,7 +34455,7 @@ var ts; } } function getTargetSymbol(s) { - return s.flags & 16777216 ? getSymbolLinks(s).target : s; + return getCheckFlags(s) & 1 ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -34341,7 +34465,7 @@ var ts; 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) { + if (base.flags & 16777216) { continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); @@ -34779,7 +34903,7 @@ var ts; } if (isAmbientExternalModule) { if (ts.isExternalModuleAugmentation(node)) { - var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 134217728); if (checkBody && node.body) { for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; @@ -34849,7 +34973,7 @@ var ts; } var symbol = getSymbolOfNode(node); if (symbol) { - var reportError = !(symbol.flags & 33554432); + var reportError = !(symbol.flags & 134217728); if (!reportError) { reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } @@ -35706,7 +35830,7 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (symbol.flags & 268435456) { + if (getCheckFlags(symbol) & 2) { var symbols_3 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { @@ -35717,7 +35841,7 @@ var ts; }); return symbols_3; } - else if (symbol.flags & 67108864) { + else if (symbol.flags & 134217728) { if (symbol.leftSpread) { var links = symbol; return [links.leftSpread, links.rightSpread]; @@ -35922,6 +36046,12 @@ var ts; } return false; } + function isRequiredInitializedParameter(parameter) { + return strictNullChecks && + !isOptionalParameter(parameter) && + parameter.initializer && + !(ts.getModifierFlags(parameter) & 92); + } function getNodeCheckFlags(node) { node = ts.getParseTreeNode(node); return node ? getNodeLinks(node).flags : undefined; @@ -36001,6 +36131,9 @@ var ts; var type = symbol && !(symbol.flags & (2048 | 131072)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; + if (flags & 4096) { + type = includeFalsyTypes(type, 2048); + } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { @@ -36082,6 +36215,7 @@ var ts; isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, @@ -36297,7 +36431,7 @@ var ts; return emptyObjectType; } function createThenableType() { - var thenPropertySymbol = createSymbol(67108864 | 4, "then"); + var thenPropertySymbol = createSymbol(4, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; var thenableType = createObjectType(16); thenableType.properties = [thenPropertySymbol]; @@ -37099,9 +37233,29 @@ var ts; } } } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { + checkESModuleMarker(node.name); + } var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } + function checkESModuleMarker(name) { + if (name.kind === 70) { + if (ts.unescapeIdentifier(name.text) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 70) { if (name.originalKeywordKind === 109) { @@ -37110,8 +37264,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -40053,8 +40207,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 261) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -44473,6 +44627,9 @@ var ts; startLexicalEnvironment(); var statements = []; var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (!currentModuleInfo.exportEquals) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); ts.addRange(statements, endLexicalEnvironment()); @@ -44563,6 +44720,9 @@ var ts; startLexicalEnvironment(); var statements = []; var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (!currentModuleInfo.exportEquals) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); ts.addRange(statements, endLexicalEnvironment()); @@ -44908,26 +45068,26 @@ var ts; return statements; } function appendExportStatement(statements, exportName, expression, location, allowComments) { - if (exportName.text === "default") { - var sourceFile = ts.getOriginalNode(currentSourceFile, ts.isSourceFile); - if (sourceFile && !sourceFile.symbol.exports.get("___esModule")) { - if (languageVersion === 0) { - statements = ts.append(statements, ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createTrue()))); - } - else { - statements = ts.append(statements, ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ - ts.createIdentifier("exports"), - ts.createLiteral("__esModule"), - ts.createObjectLiteral([ - ts.createPropertyAssignment("value", ts.createTrue()) - ]) - ]))); - } - } - } statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); return statements; } + function createUnderscoreUnderscoreESModule() { + var statement; + if (languageVersion === 0) { + statement = ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(true))); + } + else { + statement = ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ])); + } + ts.setEmitFlags(statement, 524288); + return statement; + } function createExportStatement(name, value, location, allowComments) { var statement = ts.setTextRange(ts.createStatement(createExportExpression(name, value)), location); ts.startOnNewLine(statement); @@ -46467,6 +46627,7 @@ var ts; emitNodeWithComments: emitNodeWithComments, emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, + emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition, }; function emitNodeWithComments(hint, node, emitCallback) { if (disabled) { @@ -46600,6 +46761,12 @@ var ts; writer.write(" "); } } + function emitLeadingCommentsOfPosition(pos) { + if (disabled || pos === -1) { + return; + } + emitLeadingComments(pos, true); + } function emitTrailingComments(pos) { forEachTrailingCommentToEmit(pos, emitTrailingComment); } @@ -46947,12 +47114,16 @@ var ts; function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); - if (type) { + var shouldUseResolverType = declaration.kind === 145 && + resolver.isRequiredInitializedParameter(declaration); + if (type && !shouldUseResolverType) { emitType(type); } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); + var format = 2 | 1024 | + (shouldUseResolverType ? 4096 : 0); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } } @@ -48384,7 +48555,7 @@ var ts; var newLine = ts.getNewLineCharacter(printerOptions); var languageVersion = ts.getEmitScriptTarget(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); - var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; + var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; var currentSourceFile; var nodeIdToGeneratedName; var autoGeneratedIdToGeneratedName; @@ -49294,6 +49465,9 @@ var ts; else { writeToken(16, node.pos, node); emitBlockStatements(node); + increaseIndent(); + emitLeadingCommentsOfPosition(node.statements.end); + decreaseIndent(); writeToken(17, node.statements.end, node); } } @@ -49996,6 +50170,9 @@ var ts; for (var i = 0; i < count; i++) { var child = children[start + i]; if (previousSibling) { + if (delimiter && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } write(delimiter); if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { if ((format & (3 | 64)) === 0) { @@ -50029,6 +50206,9 @@ var ts; if (format & 16 && hasTrailingComma) { write(","); } + if (previousSibling && delimiter && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } if (format & 64) { decreaseIndent(); } @@ -52862,7 +53042,7 @@ var ts; } function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); - var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); for (var i = 0; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); @@ -52874,7 +53054,7 @@ var ts; } function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); - var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); for (var i = nextExtensionPriority; i < extensions.length; i++) { var lowerPriorityExtension = extensions[i]; var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); diff --git a/lib/tsserver.js b/lib/tsserver.js index 61e6fea4a30..f987c7edea6 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -1763,13 +1763,13 @@ var ts; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0) { + if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + var extensions = allSupportedExtensions.slice(0); for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { var extInfo = extraFileExtensions_1[_i]; - if (needAllExtensions || extInfo.scriptKind === 3) { + if (extensions.indexOf(extInfo.extension) === -1) { extensions.push(extInfo.extension); } } @@ -1800,30 +1800,30 @@ var ts; function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { - return adjustExtensionPriority(i); + return adjustExtensionPriority(i, supportedExtensions); } } return 0; } ts.getExtensionPriority = getExtensionPriority; - function adjustExtensionPriority(extensionPriority) { + function adjustExtensionPriority(extensionPriority, supportedExtensions) { if (extensionPriority < 2) { return 0; } - else if (extensionPriority < 5) { + else if (extensionPriority < supportedExtensions.length) { return 2; } else { - return 5; + return supportedExtensions.length; } } ts.adjustExtensionPriority = adjustExtensionPriority; - function getNextLowestExtensionPriority(extensionPriority) { + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { if (extensionPriority < 2) { return 2; } else { - return 5; + return supportedExtensions.length; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; @@ -2689,6 +2689,7 @@ var ts; Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", message: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", message: "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", message: "Generators are only available when targeting ECMAScript 2015 or higher." }, @@ -2968,6 +2969,7 @@ var ts; Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: { code: 2543, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", message: "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference." }, Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: { code: 2544, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", message: "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference." }, A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: { code: 2545, category: ts.DiagnosticCategory.Error, key: "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", message: "A mixin class must have a constructor with a single rest parameter of type 'any[]'." }, + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: { code: 2546, category: ts.DiagnosticCategory.Error, key: "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", message: "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3221,7 +3223,7 @@ var ts; File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, Loading_module_0_from_node_modules_folder_target_file_type_1: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", message: "Loading module '{0}' from 'node_modules' folder, target file type '{1}'." }, Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_a_types_or_main_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_types_or_main_field_6100", message: "'package.json' does not have a 'types' or 'main' field." }, + package_json_does_not_have_a_0_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_0_field_6100", message: "'package.json' does not have a '{0}' field." }, package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, @@ -3258,7 +3260,6 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, - No_types_specified_in_package_json_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json', so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -3382,37 +3383,28 @@ var ts; return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); } ts.moduleHasNonRelativeName = moduleHasNonRelativeName; - function tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, baseDirectory, state) { + function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { var jsonContent = readJson(packageJsonPath, state.host); - switch (extensions) { - case Extensions.DtsOnly: - case Extensions.TypeScript: - return tryReadFromField("typings") || tryReadFromField("types"); - case Extensions.JavaScript: - if (typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main); - } - return ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - } - return undefined; - } + return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); - } - return typesFilePath; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } + return; } + var fileName = jsonContent[fieldName]; + if (typeof fileName !== "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + } + return; + } + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; } } function readJson(path, host) { @@ -3813,7 +3805,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state); + var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); } @@ -3826,7 +3819,7 @@ var ts; } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); } } @@ -3842,7 +3835,7 @@ var ts; } return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } @@ -3870,7 +3863,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } function directoryProbablyExists(directoryName, host) { return !host.directoryExists || host.directoryExists(directoryName); @@ -3927,45 +3920,48 @@ var ts; failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var mainOrTypesFile = tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, candidate, state); - if (mainOrTypesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(mainOrTypesFile), state.host); - var fromExactFile = tryFile(mainOrTypesFile, failedLookupLocations, onlyRecordFailures_1, state); - if (fromExactFile) { - var resolved_3 = fromExactFile && resolvedIfExtensionMatches(extensions, fromExactFile); - if (resolved_3) { - return resolved_3; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromExactFile); - } - } - var resolved = tryAddingExtensions(mainOrTypesFile, Extensions.TypeScript, failedLookupLocations, onlyRecordFailures_1, state); - if (resolved) { - return resolved; + if (considerPackageJson) { + var packageJsonPath = pathToPackageJson(candidate); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; } } else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_types_or_main_field); + if (directoryExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + failedLookupLocations.push(packageJsonPath); } } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocations.push(packageJsonPath); - } return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); } + function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + if (!file) { + return undefined; + } + var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); + var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); + if (fromFile) { + var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return resolved; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + } function resolvedIfExtensionMatches(extensions, path) { var extension = ts.tryGetExtensionFromPath(path); return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; @@ -4052,7 +4048,7 @@ var ts; } var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (moduleHasNonRelativeName(moduleName)) { - var resolved_4 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { return resolutionFromCache; @@ -4060,8 +4056,8 @@ var ts; var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state)); }); - if (resolved_4) { - return resolved_4; + if (resolved_3) { + return resolved_3; } if (extensions === Extensions.TypeScript) { return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); @@ -5389,6 +5385,11 @@ var ts; return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); } ts.getCommentsFromJSDoc = getCommentsFromJSDoc; + function hasJSDocParameterTags(node) { + var parameterTags = getJSDocTags(node, 284); + return parameterTags && parameterTags.length > 0; + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; function getJSDocTags(node, kind) { var docs = getJSDocs(node); if (docs) { @@ -18335,7 +18336,8 @@ var ts; flowAfterCatch = currentFlow; } if (node.finallyBlock) { - addAntecedent(preFinallyLabel, preTryFlow); + var preFinallyFlow = { flags: 2048, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); if (!(currentFlow.flags & 1)) { @@ -18345,6 +18347,11 @@ var ts; : unreachableFlow; } } + if (!(currentFlow.flags & 1)) { + var afterFinallyFlow = { flags: 4096, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } } else { currentFlow = finishFlowLabel(preFinallyLabel); @@ -19044,7 +19051,7 @@ var ts; case 148: case 147: case 274: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 0); + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 67108864 : 0), 0); case 289: return bindJSDocProperty(node); case 259: @@ -19073,7 +19080,7 @@ var ts; return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 150: case 149: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 67108864 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); case 227: return bindFunctionDeclaration(node); case 151: @@ -19196,10 +19203,10 @@ var ts; } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { - bindAnonymousDeclaration(node, 1073741824, getDeclarationName(node)); + bindAnonymousDeclaration(node, 33554432, getDeclarationName(node)); } else if (!node.exportClause) { - declareSymbol(container.symbol.exports, container.symbol, node, 1073741824, 0); + declareSymbol(container.symbol.exports, container.symbol, node, 33554432, 0); } } function bindImportClause(node) { @@ -19272,7 +19279,7 @@ var ts; } } var symbol = node.symbol; - var prototypeSymbol = createSymbol(4 | 134217728, "prototype"); + var prototypeSymbol = createSymbol(4 | 16777216, "prototype"); var symbolExport = symbol.exports.get(prototypeSymbol.name); if (symbolExport) { if (node.name) { @@ -19316,7 +19323,7 @@ var ts; } if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 536870912 : 0), 0); + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 67108864 : 0), 0); } } function bindFunctionDeclaration(node) { @@ -20077,9 +20084,9 @@ var ts; var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; var strictNullChecks = compilerOptions.strictNullChecks; var emitResolver = createResolver(); - var undefinedSymbol = createSymbol(4 | 67108864, "undefined"); + var undefinedSymbol = createSymbol(4, "undefined"); undefinedSymbol.declarations = []; - var argumentsSymbol = createSymbol(4 | 67108864, "arguments"); + var argumentsSymbol = createSymbol(4, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, @@ -20143,8 +20150,8 @@ var ts; var numericLiteralTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; - var unknownSymbol = createSymbol(4 | 67108864, "unknown"); - var resolvingSymbol = createSymbol(67108864, "__resolving__"); + var unknownSymbol = createSymbol(4, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__"); var anyType = createIntrinsicType(1, "any"); var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); @@ -20163,7 +20170,7 @@ var ts; var silentNeverType = createIntrinsicType(8192, "never"); var nonPrimitiveType = createIntrinsicType(16777216, "object"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyTypeLiteralSymbol = createSymbol(2048 | 67108864, "__type"); + var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); emptyTypeLiteralSymbol.members = ts.createMap(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -20309,7 +20316,9 @@ var ts; } function createSymbol(flags, name) { symbolCount++; - return new Symbol(flags, name); + var symbol = (new Symbol(flags | 134217728, name)); + symbol.checkFlags = 0; + return symbol; } function getExcludedSymbolFlags(flags) { var result = 0; @@ -20355,7 +20364,7 @@ var ts; mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { - var result = createSymbol(symbol.flags | 33554432, symbol.name); + var result = createSymbol(symbol.flags, symbol.name); result.declarations = symbol.declarations.slice(0); result.parent = symbol.parent; if (symbol.valueDeclaration) @@ -20414,7 +20423,7 @@ var ts; target.set(id, sourceSymbol); } else { - if (!(targetSymbol.flags & 33554432)) { + if (!(targetSymbol.flags & 134217728)) { targetSymbol = cloneSymbol(targetSymbol); target.set(id, targetSymbol); } @@ -20441,7 +20450,7 @@ var ts; } mainModule = resolveExternalModuleSymbol(mainModule); if (mainModule.flags & 1920) { - mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); + mainModule = mainModule.flags & 134217728 ? mainModule : cloneSymbol(mainModule); mergeSymbol(mainModule, moduleAugmentation.symbol); } else { @@ -20464,7 +20473,7 @@ var ts; } } function getSymbolLinks(symbol) { - if (symbol.flags & 67108864) + if (symbol.flags & 134217728) return symbol; var id = getSymbolId(symbol); return symbolLinks[id] || (symbolLinks[id] = {}); @@ -20476,6 +20485,9 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 ? type.objectFlags : 0; } + function getCheckFlags(symbol) { + return symbol.flags & 134217728 ? symbol.checkFlags : 0; + } function isGlobalSourceFile(node) { return node.kind === 263 && !ts.isExternalOrCommonJsModule(node); } @@ -20483,7 +20495,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -21093,7 +21105,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -21276,16 +21288,7 @@ var ts; : symbol; } function symbolIsValue(symbol) { - if (symbol.flags & 16777216) { - return symbolIsValue(getSymbolLinks(symbol).target); - } - if (symbol.flags & 107455) { - return true; - } - if (symbol.flags & 8388608) { - return (resolveAlias(symbol).flags & 107455) !== 0; - } - return false; + return !!(symbol.flags & 107455 || symbol.flags & 8388608 && resolveAlias(symbol).flags & 107455); } function findConstructorDeclaration(node) { var members = node.members; @@ -21708,7 +21711,7 @@ var ts; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { if (flags & 1) { - if (symbol.flags & 16777216) { + if (getCheckFlags(symbol) & 1) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -21946,7 +21949,7 @@ var ts; writeSpace(writer); } buildSymbolDisplay(prop, writer); - if (prop.flags & 536870912) { + if (prop.flags & 67108864) { writePunctuation(writer, 54); } } @@ -22106,7 +22109,11 @@ var ts; } writePunctuation(writer, 55); writeSpace(writer); - buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); + var type = getTypeOfSymbol(p); + if (isRequiredInitializedParameter(parameterNode)) { + type = includeFalsyTypes(type, 2048); + } + buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { if (bindingPattern.kind === 173) { @@ -22564,7 +22571,7 @@ var ts; getUnionType([type, checkExpressionCached(declaration.initializer)], true) : type; } - function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + function getTypeForDeclarationFromJSDocComment(declaration) { var jsdocType = ts.getJSDocType(declaration); if (jsdocType) { return getTypeFromTypeNode(jsdocType); @@ -22582,9 +22589,17 @@ var ts; function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } + function removeOptionalityFromAnnotation(annotatedType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 145 && + declaration.initializer && + getFalsyFlags(annotatedType) & 2048 && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); + return annotationIncludesUndefined ? getNonNullableType(annotatedType) : annotatedType; + } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536) { - var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); + var type = getTypeForDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { return type; } @@ -22600,7 +22615,8 @@ var ts; return getTypeForBindingElement(declaration); } if (declaration.type) { - return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); + var declaredType = removeOptionalityFromAnnotation(getTypeFromTypeNode(declaration.type), declaration); + return addOptionality(declaredType, declaration.questionToken && includeOptionality); } if ((compilerOptions.noImplicitAny || declaration.flags & 65536) && declaration.kind === 225 && !ts.isBindingPattern(declaration.name) && @@ -22649,6 +22665,21 @@ var ts; } return undefined; } + function getTypeForJSSpecialPropertyDeclaration(declaration) { + var expression = declaration.kind === 193 ? declaration : + declaration.kind === 178 ? ts.getAncestor(declaration, 193) : + undefined; + if (!expression) { + return unknownType; + } + if (expression.flags & 65536) { + var type = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type && type !== unknownType) { + return getWidenedType(type); + } + } + return getWidenedLiteralType(checkExpressionCached(expression.right)); + } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { return checkDeclarationInitializer(element); @@ -22676,7 +22707,7 @@ var ts; return; } var text = ts.getTextOfPropertyName(name); - var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); + var flags = 4 | (e.initializer ? 67108864 : 0); var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; @@ -22737,7 +22768,7 @@ var ts; function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.flags & 134217728) { + if (symbol.flags & 16777216) { return links.type = getTypeOfPrototypeProperty(symbol); } var declaration = symbol.valueDeclaration; @@ -22756,16 +22787,7 @@ var ts; var type = void 0; if (declaration.kind === 193 || declaration.kind === 178 && declaration.parent.kind === 193) { - if (declaration.flags & 65536) { - var jsdocType = ts.getJSDocType(declaration.parent); - if (jsdocType) { - return links.type = getTypeFromTypeNode(jsdocType); - } - } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 193 ? - checkExpressionCached(decl.right) : - checkExpressionCached(decl.parent.right); }); - type = getUnionType(declaredTypes, true); + type = getWidenedType(getUnionType(ts.map(symbol.declarations, getTypeForJSSpecialPropertyDeclaration), true)); } else { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); @@ -22802,7 +22824,7 @@ var ts; var getter = ts.getDeclarationOfKind(symbol, 152); var setter = ts.getDeclarationOfKind(symbol, 153); if (getter && getter.flags & 65536) { - var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; } @@ -22866,7 +22888,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 536870912 ? includeFalsyTypes(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 67108864 ? includeFalsyTypes(type, 2048) : type; } } } @@ -22914,7 +22936,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (symbol.flags & 16777216) { + if (getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -23606,7 +23628,7 @@ var ts; s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); - s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); + s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); } s.resolvedReturnType = undefined; s.unionSignatures = unionSignatures; @@ -23764,10 +23786,10 @@ var ts; if (t.flags & 32) { var propName = t.text; var modifiersProp = getPropertyOfType(modifiersType, propName); - var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912); - var prop = createSymbol(4 | 67108864 | (isOptional ? 536870912 : 0), propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); + var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); + prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 4 : 0; prop.type = propType; - prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); if (propertySymbol) { prop.mappedTypeOrigin = propertySymbol; } @@ -23960,18 +23982,19 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var types = containingType.types; - var excludeModifiers = containingType.flags & 65536 ? 8 | 16 : 0; var props; - var commonFlags = (containingType.flags & 131072) ? 536870912 : 0; - var isReadonly = false; - var isPartial = false; + var types = containingType.types; + var isUnion = containingType.flags & 65536; + var excludeModifiers = isUnion ? 24 : 0; + var commonFlags = isUnion ? 0 : 67108864; + var checkFlags = 2; for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & excludeModifiers)) { + var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { props = [prop]; @@ -23979,25 +24002,26 @@ var ts; else if (!ts.contains(props, prop)) { props.push(prop); } - if (isReadonlySymbol(prop)) { - isReadonly = true; - } + checkFlags |= (isReadonlySymbol(prop) ? 4 : 0) | + (!(modifiers & 24) ? 32 : 0) | + (modifiers & 16 ? 64 : 0) | + (modifiers & 8 ? 128 : 0) | + (modifiers & 32 ? 256 : 0); } - else if (containingType.flags & 65536) { - isPartial = true; + else if (isUnion) { + checkFlags |= 8; } } } if (!props) { return undefined; } - if (props.length === 1 && !isPartial) { + if (props.length === 1 && !(checkFlags & 8)) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -24008,17 +24032,15 @@ var ts; commonType = type; } else if (type !== commonType) { - hasNonUniformType = true; + checkFlags |= 16; } propTypes.push(type); } - var result = createSymbol(4 | 67108864 | 268435456 | commonFlags, name); + var result = createSymbol(4 | commonFlags, name); + result.checkFlags = checkFlags; result.containingType = containingType; - result.hasNonUniformType = hasNonUniformType; - result.isPartial = isPartial; result.declarations = declarations; - result.isReadonly = isReadonly; - result.type = containingType.flags & 65536 ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } function getUnionOrIntersectionProperty(type, name) { @@ -24034,7 +24056,7 @@ var ts; } function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); - return property && !(property.flags & 268435456 && property.isPartial) ? property : undefined; + return property && !(getCheckFlags(property) & 8) ? property : undefined; } function getPropertyOfType(type, name) { type = getApparentType(type); @@ -24163,6 +24185,12 @@ var ts; ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + } return false; } function createTypePredicateFromTypePredicateNode(node) { @@ -24192,6 +24220,7 @@ var ts; var hasThisParameter = void 0; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { var param = declaration.parameters[i]; var paramSymbol = param.symbol; @@ -24211,7 +24240,8 @@ var ts; } var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param); + isJSDocOptionalParameter(param) || + isUntypedSignatureInJSFile; if (!isOptionalParameter_1) { minArgumentCount = parameters.length; } @@ -24683,7 +24713,7 @@ var ts; for (var i = 0; i < arity; i++) { var typeParameter = createType(16384); typeParameters.push(typeParameter); - var property = createSymbol(4 | 67108864, "" + i); + var property = createSymbol(4, "" + i); property.type = typeParameter; properties.push(property); } @@ -24898,7 +24928,10 @@ var ts; if (type.flags & 65536 && typeSet.unionIndex === undefined) { typeSet.unionIndex = typeSet.length; } - typeSet.push(type); + if (!(type.flags & 32768 && type.objectFlags & 16 && + type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + typeSet.push(type); + } } } function addTypesToIntersection(typeSet, types) { @@ -25180,15 +25213,15 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 536870912) { + if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 67108864) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); - var flags = 4 | 67108864 | (leftProp.flags & 536870912); + var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); + result.checkFlags = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp) ? 4 : 0; result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; - result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp); members.set(leftProp.name, result); } } @@ -25479,12 +25512,13 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (symbol.flags & 16777216) { + if (getCheckFlags(symbol) & 1) { var links = getSymbolLinks(symbol); symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); } - var result = createSymbol(16777216 | 67108864 | symbol.flags, symbol.name); + var result = createSymbol(symbol.flags, symbol.name); + result.checkFlags = 1; result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -26265,20 +26299,42 @@ var ts; if (target.flags & 65536 && containsType(targetTypes, source)) { return -1; } - var len = targetTypes.length; - for (var i = 0; i < len; i++) { - var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, false); if (related) { return related; } } + if (reportErrors) { + var discriminantType = findMatchingDiscriminantType(source, target); + isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], true); + } return 0; } + function findMatchingDiscriminantType(source, target) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProperty = sourceProperties_1[_i]; + if (isDiscriminantProperty(target, sourceProperty.name)) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _a = 0, _b = target.types; _a < _b.length; _a++) { + var type = _b[_a]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.name); + if (targetType && isRelatedTo(sourceType, targetType)) { + return type; + } + } + } + } + } + } function typeRelatedToEachType(source, target, reportErrors) { var result = -1; var targetTypes = target.types; - for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { - var targetType = targetTypes_1[_i]; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; var related = isRelatedTo(source, targetType, reportErrors); if (!related) { return 0; @@ -26448,17 +26504,23 @@ var ts; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { - if (!(targetProp.flags & 536870912) || requireOptionalProperties) { + if (!(targetProp.flags & 67108864) || requireOptionalProperties) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); } return 0; } } - else if (!(targetProp.flags & 134217728)) { + else if (!(targetProp.flags & 16777216)) { var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { + if (getCheckFlags(sourceProp) & 128) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); + } + return 0; + } if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { if (sourcePropFlags & 8 && targetPropFlags & 8) { @@ -26472,12 +26534,9 @@ var ts; } } else if (targetPropFlags & 16) { - var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32; - var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined; - var targetClass = getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp)); - if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { + if (!isValidOverrideOf(sourceProp, targetProp)) { if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass)); + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); } return 0; } @@ -26496,7 +26555,7 @@ var ts; return 0; } result &= related; - if (relation !== comparableRelation && sourceProp.flags & 536870912 && !(targetProp.flags & 536870912)) { + if (relation !== comparableRelation && sourceProp.flags & 67108864 && !(targetProp.flags & 67108864)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -26517,8 +26576,8 @@ var ts; return 0; } var result = -1; - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProp = sourceProperties_1[_i]; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProp = sourceProperties_2[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return 0; @@ -26679,6 +26738,37 @@ var ts; return false; } } + function forEachProperty(prop, callback) { + if (getCheckFlags(prop) & 2) { + for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var p = getPropertyOfType(t, prop.name); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + function isValidOverrideOf(sourceProp, targetProp) { + return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); + } + function isClassDerivedFromDeclaringClasses(checkClass, prop) { + return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } function isAbstractConstructorType(type) { if (getObjectFlags(type) & 16) { var symbol = type.symbol; @@ -26724,7 +26814,7 @@ var ts; } } else { - if ((sourceProp.flags & 536870912) !== (targetProp.flags & 536870912)) { + if ((sourceProp.flags & 67108864) !== (targetProp.flags & 67108864)) { return 0; } } @@ -26923,7 +27013,7 @@ var ts; types.push(undefinedType); if (flags & 4096) types.push(nullType); - return getUnionType(types, true); + return getUnionType(types); } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 ? @@ -26938,8 +27028,8 @@ var ts; getSignaturesOfType(type, 0).length === 0 && getSignaturesOfType(type, 1).length === 0; } - function createTransientSymbol(source, type) { - var symbol = createSymbol(source.flags | 67108864, source.name); + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.name); symbol.declarations = source.declarations; symbol.parent = source.parent; symbol.type = type; @@ -26955,7 +27045,7 @@ var ts; var property = _a[_i]; var original = getTypeOfSymbol(property); var updated = f(original); - members.set(property.name, updated === original ? property : createTransientSymbol(property, updated)); + members.set(property.name, updated === original ? property : createSymbolWithType(property, updated)); } ; return members; @@ -27144,7 +27234,7 @@ var ts; var typeInferencesArray = [typeInferences]; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 536870912; + var optionalMask = target.declaration.questionToken ? 0 : 67108864; var members = createSymbolTable(properties); for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; @@ -27152,10 +27242,10 @@ var ts; if (!inferredPropType) { return undefined; } - var inferredProp = createSymbol(4 | 67108864 | prop.flags & optionalMask, prop.name); + var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.name); + inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 4 : 0; inferredProp.declarations = prop.declarations; inferredProp.type = inferredPropType; - inferredProp.isReadonly = readonlyMask && isReadonlySymbol(prop); members.set(prop.name, inferredProp); } if (indexInfo) { @@ -27266,8 +27356,8 @@ var ts; var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; - for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { - var t = targetTypes_2[_d]; + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; if (t.flags & 540672 && ts.contains(typeVariables, t)) { typeVariable = t; typeVariableCount++; @@ -27549,9 +27639,9 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && prop.flags & 268435456) { + if (prop && getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.checkFlags & 16 && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -27699,10 +27789,16 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, undefined, false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - return node.parent.kind === 176 || node.parent.kind === 259 ? + var isDestructuringDefaultAssignment = node.parent.kind === 176 && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 259 && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 193 && parent.parent.left === parent || + parent.parent.kind === 215 && parent.parent.initializer === parent; + } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); } @@ -27979,7 +28075,16 @@ var ts; } } var type = void 0; - if (flow.flags & 16) { + if (flow.flags & 4096) { + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flow.flags & 2048) { + flow = flow.antecedent; + continue; + } + else if (flow.flags & 16) { type = getTypeAtFlowAssignment(flow); if (!type) { flow = flow.antecedent; @@ -28113,6 +28218,9 @@ var ts; var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; + if (antecedent.flags & 2048 && antecedent.lock.locked) { + continue; + } var flowType = getTypeAtFlowNode(antecedent); var type = getTypeFromFlowType(flowType); if (type === declaredType && declaredType === initialType) { @@ -29413,12 +29521,12 @@ var ts; type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; - var prop = createSymbol(4 | 67108864 | member.flags, member.name); + var prop = createSymbol(4 | member.flags, member.name); if (inDestructuringPattern) { var isOptional = (memberDecl.kind === 259 && hasDefaultValue(memberDecl.initializer)) || (memberDecl.kind === 260 && memberDecl.objectAssignmentInitializer); if (isOptional) { - prop.flags |= 536870912; + prop.flags |= 67108864; } if (ts.hasDynamicName(memberDecl)) { patternWithComputedProperties = true; @@ -29427,7 +29535,7 @@ var ts; else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { - prop.flags |= impliedProp.flags & 536870912; + prop.flags |= impliedProp.flags & 67108864; } else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); @@ -29484,7 +29592,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { var prop = _a[_i]; if (!propertiesTable.get(prop.name)) { - if (!(prop.flags & 536870912)) { + if (!(prop.flags & 67108864)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } propertiesTable.set(prop.name, prop); @@ -29859,7 +29967,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var _i = 0, targetProperties_1 = targetProperties; _i < targetProperties_1.length; _i++) { var targetProperty = targetProperties_1[_i]; - if (!(targetProperty.flags & 536870912) && !nameTable.get(targetProperty.name)) { + if (!(targetProperty.flags & 67108864) && !nameTable.get(targetProperty.name)) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperty.name, typeToString(targetAttributesType)); } } @@ -29881,17 +29989,35 @@ var ts; return s.valueDeclaration ? s.valueDeclaration.kind : 148; } function getDeclarationModifierFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + } + if (getCheckFlags(s) & 2) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 128 ? 8 : + checkFlags & 32 ? 4 : + 16; + var staticModifier = checkFlags & 256 ? 32 : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216) { + return 4 | 32; + } + return 0; } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } - function checkClassPropertyAccess(node, left, type, prop) { + function checkPropertyAccessibility(node, left, type, prop) { var flags = getDeclarationModifierFlagsFromSymbol(prop); - var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); var errorNode = node.kind === 178 || node.kind === 225 ? node.name : node.right; + if (getCheckFlags(prop) & 128) { + error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); + return false; + } if (left.kind === 96) { if (languageVersion < 2) { var propKind = getDeclarationKindFromSymbol(prop); @@ -29901,7 +30027,7 @@ var ts; } } if (flags & 128) { - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } } @@ -29911,7 +30037,7 @@ var ts; if (flags & 8) { var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } return true; @@ -29921,10 +30047,10 @@ var ts; } var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return hasBaseType(enclosingClass, declaringClass) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; }); if (!enclosingClass) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); return false; } if (flags & 32) { @@ -29979,7 +30105,7 @@ var ts; noUnusedIdentifiers && (prop.flags & 106500) && prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (prop.flags & 16777216) { + if (getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } else { @@ -30023,9 +30149,7 @@ var ts; } markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; - if (prop.parent && prop.parent.flags & 32) { - checkClassPropertyAccess(node, left, apparentType, prop); - } + checkPropertyAccessibility(node, left, apparentType, prop); var propType = getTypeOfSymbol(prop); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -30049,8 +30173,8 @@ var ts; var type = checkExpression(left); if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(getWidenedType(type), propertyName); - if (prop && prop.parent && prop.parent.flags & 32) { - return checkClassPropertyAccess(node, left, type, prop); + if (prop) { + return checkPropertyAccessibility(node, left, type, prop); } } return true; @@ -31031,7 +31155,7 @@ var ts; var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { if (!parameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + signature.thisParameter = createSymbolWithType(context.thisParameter, undefined); } assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } @@ -31341,11 +31465,11 @@ var ts; return true; } function isReadonlySymbol(symbol) { - return symbol.isReadonly || - symbol.flags & 4 && (getDeclarationModifierFlagsFromSymbol(symbol) & 64) !== 0 || - symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 || + return !!(getCheckFlags(symbol) & 4 || + symbol.flags & 4 && getDeclarationModifierFlagsFromSymbol(symbol) & 64 || + symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || symbol.flags & 98304 && !(symbol.flags & 65536) || - (symbol.flags & 8) !== 0; + symbol.flags & 8); } function isReferenceToReadonlyEntity(expr, symbol) { if (isReadonlySymbol(symbol)) { @@ -33608,8 +33732,8 @@ var ts; var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); markPropertyAsReferenced(property); - if (parent.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent, parent.initializer, parentType, property); + if (parent.initializer && property) { + checkPropertyAccessibility(parent, parent.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { @@ -34341,7 +34465,7 @@ var ts; } } function getTargetSymbol(s) { - return s.flags & 16777216 ? getSymbolLinks(s).target : s; + return getCheckFlags(s) & 1 ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -34351,7 +34475,7 @@ var ts; 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) { + if (base.flags & 16777216) { continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); @@ -34789,7 +34913,7 @@ var ts; } if (isAmbientExternalModule) { if (ts.isExternalModuleAugmentation(node)) { - var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 134217728); if (checkBody && node.body) { for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; @@ -34859,7 +34983,7 @@ var ts; } var symbol = getSymbolOfNode(node); if (symbol) { - var reportError = !(symbol.flags & 33554432); + var reportError = !(symbol.flags & 134217728); if (!reportError) { reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } @@ -35716,7 +35840,7 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (symbol.flags & 268435456) { + if (getCheckFlags(symbol) & 2) { var symbols_3 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { @@ -35727,7 +35851,7 @@ var ts; }); return symbols_3; } - else if (symbol.flags & 67108864) { + else if (symbol.flags & 134217728) { if (symbol.leftSpread) { var links = symbol; return [links.leftSpread, links.rightSpread]; @@ -35932,6 +36056,12 @@ var ts; } return false; } + function isRequiredInitializedParameter(parameter) { + return strictNullChecks && + !isOptionalParameter(parameter) && + parameter.initializer && + !(ts.getModifierFlags(parameter) & 92); + } function getNodeCheckFlags(node) { node = ts.getParseTreeNode(node); return node ? getNodeLinks(node).flags : undefined; @@ -36011,6 +36141,9 @@ var ts; var type = symbol && !(symbol.flags & (2048 | 131072)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; + if (flags & 4096) { + type = includeFalsyTypes(type, 2048); + } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { @@ -36092,6 +36225,7 @@ var ts; isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, @@ -36307,7 +36441,7 @@ var ts; return emptyObjectType; } function createThenableType() { - var thenPropertySymbol = createSymbol(67108864 | 4, "then"); + var thenPropertySymbol = createSymbol(4, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; var thenableType = createObjectType(16); thenableType.properties = [thenPropertySymbol]; @@ -37109,9 +37243,29 @@ var ts; } } } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { + checkESModuleMarker(node.name); + } var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } + function checkESModuleMarker(name) { + if (name.kind === 70) { + if (ts.unescapeIdentifier(name.text) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 70) { if (name.originalKeywordKind === 109) { @@ -37120,8 +37274,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -40063,8 +40217,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 261) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -44483,6 +44637,9 @@ var ts; startLexicalEnvironment(); var statements = []; var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (!currentModuleInfo.exportEquals) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); ts.addRange(statements, endLexicalEnvironment()); @@ -44573,6 +44730,9 @@ var ts; startLexicalEnvironment(); var statements = []; var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (!currentModuleInfo.exportEquals) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); ts.addRange(statements, endLexicalEnvironment()); @@ -44918,26 +45078,26 @@ var ts; return statements; } function appendExportStatement(statements, exportName, expression, location, allowComments) { - if (exportName.text === "default") { - var sourceFile = ts.getOriginalNode(currentSourceFile, ts.isSourceFile); - if (sourceFile && !sourceFile.symbol.exports.get("___esModule")) { - if (languageVersion === 0) { - statements = ts.append(statements, ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createTrue()))); - } - else { - statements = ts.append(statements, ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ - ts.createIdentifier("exports"), - ts.createLiteral("__esModule"), - ts.createObjectLiteral([ - ts.createPropertyAssignment("value", ts.createTrue()) - ]) - ]))); - } - } - } statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); return statements; } + function createUnderscoreUnderscoreESModule() { + var statement; + if (languageVersion === 0) { + statement = ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(true))); + } + else { + statement = ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ])); + } + ts.setEmitFlags(statement, 524288); + return statement; + } function createExportStatement(name, value, location, allowComments) { var statement = ts.setTextRange(ts.createStatement(createExportExpression(name, value)), location); ts.startOnNewLine(statement); @@ -46411,12 +46571,16 @@ var ts; function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); - if (type) { + var shouldUseResolverType = declaration.kind === 145 && + resolver.isRequiredInitializedParameter(declaration); + if (type && !shouldUseResolverType) { emitType(type); } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); + var format = 2 | 1024 | + (shouldUseResolverType ? 4096 : 0); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } } @@ -47996,6 +48160,7 @@ var ts; emitNodeWithComments: emitNodeWithComments, emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, + emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition, }; function emitNodeWithComments(hint, node, emitCallback) { if (disabled) { @@ -48129,6 +48294,12 @@ var ts; writer.write(" "); } } + function emitLeadingCommentsOfPosition(pos) { + if (disabled || pos === -1) { + return; + } + emitLeadingComments(pos, true); + } function emitTrailingComments(pos) { forEachTrailingCommentToEmit(pos, emitTrailingComment); } @@ -48394,7 +48565,7 @@ var ts; var newLine = ts.getNewLineCharacter(printerOptions); var languageVersion = ts.getEmitScriptTarget(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); - var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; + var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; var currentSourceFile; var nodeIdToGeneratedName; var autoGeneratedIdToGeneratedName; @@ -49304,6 +49475,9 @@ var ts; else { writeToken(16, node.pos, node); emitBlockStatements(node); + increaseIndent(); + emitLeadingCommentsOfPosition(node.statements.end); + decreaseIndent(); writeToken(17, node.statements.end, node); } } @@ -50006,6 +50180,9 @@ var ts; for (var i = 0; i < count; i++) { var child = children[start + i]; if (previousSibling) { + if (delimiter && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } write(delimiter); if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { if ((format & (3 | 64)) === 0) { @@ -50039,6 +50216,9 @@ var ts; if (format & 16 && hasTrailingComma) { write(","); } + if (previousSibling && delimiter && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } if (format & 64) { decreaseIndent(); } @@ -52872,7 +53052,7 @@ var ts; } function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); - var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); for (var i = 0; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); @@ -52884,7 +53064,7 @@ var ts; } function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); - var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); for (var i = nextExtensionPriority; i < extensions.length; i++) { var lowerPriorityExtension = extensions[i]; var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); @@ -57511,7 +57691,7 @@ var ts; if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { return undefined; } - if (symbol.parent || (symbol.flags & 268435456)) { + if (symbol.parent || (symbol.flags & 134217728 && symbol.checkFlags & 2)) { return undefined; } var scope; @@ -57666,7 +57846,7 @@ var ts; if (relatedSymbol) { addReferenceToRelatedSymbol(referenceLocation, relatedSymbol); } - else if (!(referenceSymbol.flags & 67108864) && ts.contains(searchSymbols, shorthandValueSymbol)) { + else if (!(referenceSymbol.flags & 134217728) && ts.contains(searchSymbols, shorthandValueSymbol)) { addReferenceToRelatedSymbol(referenceSymbolDeclaration.name, shorthandValueSymbol); } else if (searchLocation.kind === 122) { @@ -60919,7 +61099,7 @@ var ts; if (flags & 16384) return ts.ScriptElementKind.constructorImplementationElement; if (flags & 4) { - if (flags & 268435456) { + if (flags & 134217728 && symbol.checkFlags & 2) { var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { var rootSymbolFlags = rootSymbol.getFlags(); if (rootSymbolFlags & (98308 | 3)) { diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index e21d929629f..6462f7940a0 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -1421,9 +1421,21 @@ declare namespace ts { ArrayMutation = 256, Referenced = 512, Shared = 1024, + PreFinally = 2048, + AfterFinally = 4096, Label = 12, Condition = 96, } + interface FlowLock { + locked?: boolean; + } + interface AfterFinallyFlow extends FlowNode, FlowLock { + antecedent: FlowNode; + } + interface PreFinallyFlow extends FlowNode { + antecedent: FlowNode; + lock: FlowLock; + } interface FlowNode { flags: FlowFlags; id?: number; @@ -1630,6 +1642,7 @@ declare namespace ts { InTypeAlias = 512, UseTypeAliasValue = 1024, SuppressAnyReturnType = 2048, + AddUndefined = 4096, } const enum SymbolFormatFlags { None = 0, @@ -1679,13 +1692,10 @@ declare namespace ts { ExportType = 2097152, ExportNamespace = 4194304, Alias = 8388608, - Instantiated = 16777216, - Merged = 33554432, - Transient = 67108864, - Prototype = 134217728, - SyntheticProperty = 268435456, - Optional = 536870912, - ExportStar = 1073741824, + Prototype = 16777216, + ExportStar = 33554432, + Optional = 67108864, + Transient = 134217728, Enum = 384, Variable = 3, Value = 107455, @@ -1865,9 +1875,8 @@ declare namespace ts { isReadonly: boolean; declaration?: SignatureDeclaration; } - interface FileExtensionInfo { + interface JsFileExtensionInfo { extension: string; - scriptKind: ScriptKind; isMixedContent: boolean; } interface DiagnosticMessage { @@ -2267,7 +2276,7 @@ declare namespace ts { config?: any; error?: Diagnostic; }; - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: FileExtensionInfo[]): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine; function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; @@ -3648,7 +3657,7 @@ declare namespace ts.server.protocol { hostInfo?: string; file?: string; formatOptions?: FormatCodeSettings; - extraFileExtensions?: FileExtensionInfo[]; + extraFileExtensions?: JsFileExtensionInfo[]; } interface ConfigureRequest extends Request { command: CommandTypes.Configure; @@ -4730,7 +4739,7 @@ declare namespace ts.server { interface HostConfiguration { formatCodeOptions: FormatCodeSettings; hostInfo: string; - extraFileExtensions?: FileExtensionInfo[]; + extraFileExtensions?: JsFileExtensionInfo[]; } interface OpenConfiguredProjectResult { configFileName?: NormalizedPath; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index ed29a8d08e2..e297d40ea3a 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -1763,13 +1763,13 @@ var ts; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0) { + if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + var extensions = allSupportedExtensions.slice(0); for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { var extInfo = extraFileExtensions_1[_i]; - if (needAllExtensions || extInfo.scriptKind === 3) { + if (extensions.indexOf(extInfo.extension) === -1) { extensions.push(extInfo.extension); } } @@ -1800,30 +1800,30 @@ var ts; function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { - return adjustExtensionPriority(i); + return adjustExtensionPriority(i, supportedExtensions); } } return 0; } ts.getExtensionPriority = getExtensionPriority; - function adjustExtensionPriority(extensionPriority) { + function adjustExtensionPriority(extensionPriority, supportedExtensions) { if (extensionPriority < 2) { return 0; } - else if (extensionPriority < 5) { + else if (extensionPriority < supportedExtensions.length) { return 2; } else { - return 5; + return supportedExtensions.length; } } ts.adjustExtensionPriority = adjustExtensionPriority; - function getNextLowestExtensionPriority(extensionPriority) { + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { if (extensionPriority < 2) { return 2; } else { - return 5; + return supportedExtensions.length; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; @@ -2689,6 +2689,7 @@ var ts; Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", message: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", message: "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", message: "Generators are only available when targeting ECMAScript 2015 or higher." }, @@ -2968,6 +2969,7 @@ var ts; Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: { code: 2543, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", message: "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference." }, Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: { code: 2544, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", message: "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference." }, A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: { code: 2545, category: ts.DiagnosticCategory.Error, key: "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", message: "A mixin class must have a constructor with a single rest parameter of type 'any[]'." }, + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: { code: 2546, category: ts.DiagnosticCategory.Error, key: "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", message: "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3221,7 +3223,7 @@ var ts; File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, Loading_module_0_from_node_modules_folder_target_file_type_1: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", message: "Loading module '{0}' from 'node_modules' folder, target file type '{1}'." }, Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_a_types_or_main_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_types_or_main_field_6100", message: "'package.json' does not have a 'types' or 'main' field." }, + package_json_does_not_have_a_0_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_0_field_6100", message: "'package.json' does not have a '{0}' field." }, package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, @@ -3258,7 +3260,6 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, - No_types_specified_in_package_json_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json', so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -6001,7 +6002,7 @@ var ts; } function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); - var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); for (var i = 0; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); @@ -6013,7 +6014,7 @@ var ts; } function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); - var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); for (var i = nextExtensionPriority; i < extensions.length; i++) { var lowerPriorityExtension = extensions[i]; var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); @@ -6061,37 +6062,28 @@ var ts; return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); } ts.moduleHasNonRelativeName = moduleHasNonRelativeName; - function tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, baseDirectory, state) { + function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { var jsonContent = readJson(packageJsonPath, state.host); - switch (extensions) { - case Extensions.DtsOnly: - case Extensions.TypeScript: - return tryReadFromField("typings") || tryReadFromField("types"); - case Extensions.JavaScript: - if (typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main); - } - return ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - } - return undefined; - } + return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); - } - return typesFilePath; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } + return; } + var fileName = jsonContent[fieldName]; + if (typeof fileName !== "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + } + return; + } + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; } } function readJson(path, host) { @@ -6492,7 +6484,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state); + var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); } @@ -6505,7 +6498,7 @@ var ts; } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); } } @@ -6521,7 +6514,7 @@ var ts; } return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } @@ -6549,7 +6542,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } function directoryProbablyExists(directoryName, host) { return !host.directoryExists || host.directoryExists(directoryName); @@ -6606,45 +6599,48 @@ var ts; failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var mainOrTypesFile = tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, candidate, state); - if (mainOrTypesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(mainOrTypesFile), state.host); - var fromExactFile = tryFile(mainOrTypesFile, failedLookupLocations, onlyRecordFailures_1, state); - if (fromExactFile) { - var resolved_3 = fromExactFile && resolvedIfExtensionMatches(extensions, fromExactFile); - if (resolved_3) { - return resolved_3; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromExactFile); - } - } - var resolved = tryAddingExtensions(mainOrTypesFile, Extensions.TypeScript, failedLookupLocations, onlyRecordFailures_1, state); - if (resolved) { - return resolved; + if (considerPackageJson) { + var packageJsonPath = pathToPackageJson(candidate); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; } } else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_types_or_main_field); + if (directoryExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + failedLookupLocations.push(packageJsonPath); } } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocations.push(packageJsonPath); - } return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); } + function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + if (!file) { + return undefined; + } + var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); + var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); + if (fromFile) { + var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return resolved; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + } function resolvedIfExtensionMatches(extensions, path) { var extension = ts.tryGetExtensionFromPath(path); return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; @@ -6731,7 +6727,7 @@ var ts; } var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (moduleHasNonRelativeName(moduleName)) { - var resolved_4 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { return resolutionFromCache; @@ -6739,8 +6735,8 @@ var ts; var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state)); }); - if (resolved_4) { - return resolved_4; + if (resolved_3) { + return resolved_3; } if (extensions === Extensions.TypeScript) { return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); @@ -8068,6 +8064,11 @@ var ts; return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); } ts.getCommentsFromJSDoc = getCommentsFromJSDoc; + function hasJSDocParameterTags(node) { + var parameterTags = getJSDocTags(node, 284); + return parameterTags && parameterTags.length > 0; + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; function getJSDocTags(node, kind) { var docs = getJSDocs(node); if (docs) { @@ -19459,7 +19460,8 @@ var ts; flowAfterCatch = currentFlow; } if (node.finallyBlock) { - addAntecedent(preFinallyLabel, preTryFlow); + var preFinallyFlow = { flags: 2048, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); if (!(currentFlow.flags & 1)) { @@ -19469,6 +19471,11 @@ var ts; : unreachableFlow; } } + if (!(currentFlow.flags & 1)) { + var afterFinallyFlow = { flags: 4096, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } } else { currentFlow = finishFlowLabel(preFinallyLabel); @@ -20168,7 +20175,7 @@ var ts; case 148: case 147: case 274: - return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 536870912 : 0), 0); + return bindPropertyOrMethodOrAccessor(node, 4 | (node.questionToken ? 67108864 : 0), 0); case 289: return bindJSDocProperty(node); case 259: @@ -20197,7 +20204,7 @@ var ts; return declareSymbolAndAddToSymbolTable(node, 131072, 0); case 150: case 149: - return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 536870912 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); + return bindPropertyOrMethodOrAccessor(node, 8192 | (node.questionToken ? 67108864 : 0), ts.isObjectLiteralMethod(node) ? 0 : 99263); case 227: return bindFunctionDeclaration(node); case 151: @@ -20320,10 +20327,10 @@ var ts; } function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { - bindAnonymousDeclaration(node, 1073741824, getDeclarationName(node)); + bindAnonymousDeclaration(node, 33554432, getDeclarationName(node)); } else if (!node.exportClause) { - declareSymbol(container.symbol.exports, container.symbol, node, 1073741824, 0); + declareSymbol(container.symbol.exports, container.symbol, node, 33554432, 0); } } function bindImportClause(node) { @@ -20396,7 +20403,7 @@ var ts; } } var symbol = node.symbol; - var prototypeSymbol = createSymbol(4 | 134217728, "prototype"); + var prototypeSymbol = createSymbol(4 | 16777216, "prototype"); var symbolExport = symbol.exports.get(prototypeSymbol.name); if (symbolExport) { if (node.name) { @@ -20440,7 +20447,7 @@ var ts; } if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 536870912 : 0), 0); + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 | (node.questionToken ? 67108864 : 0), 0); } } function bindFunctionDeclaration(node) { @@ -21201,9 +21208,9 @@ var ts; var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; var strictNullChecks = compilerOptions.strictNullChecks; var emitResolver = createResolver(); - var undefinedSymbol = createSymbol(4 | 67108864, "undefined"); + var undefinedSymbol = createSymbol(4, "undefined"); undefinedSymbol.declarations = []; - var argumentsSymbol = createSymbol(4 | 67108864, "arguments"); + var argumentsSymbol = createSymbol(4, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, @@ -21267,8 +21274,8 @@ var ts; var numericLiteralTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; - var unknownSymbol = createSymbol(4 | 67108864, "unknown"); - var resolvingSymbol = createSymbol(67108864, "__resolving__"); + var unknownSymbol = createSymbol(4, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__"); var anyType = createIntrinsicType(1, "any"); var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); @@ -21287,7 +21294,7 @@ var ts; var silentNeverType = createIntrinsicType(8192, "never"); var nonPrimitiveType = createIntrinsicType(16777216, "object"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyTypeLiteralSymbol = createSymbol(2048 | 67108864, "__type"); + var emptyTypeLiteralSymbol = createSymbol(2048, "__type"); emptyTypeLiteralSymbol.members = ts.createMap(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -21433,7 +21440,9 @@ var ts; } function createSymbol(flags, name) { symbolCount++; - return new Symbol(flags, name); + var symbol = (new Symbol(flags | 134217728, name)); + symbol.checkFlags = 0; + return symbol; } function getExcludedSymbolFlags(flags) { var result = 0; @@ -21479,7 +21488,7 @@ var ts; mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { - var result = createSymbol(symbol.flags | 33554432, symbol.name); + var result = createSymbol(symbol.flags, symbol.name); result.declarations = symbol.declarations.slice(0); result.parent = symbol.parent; if (symbol.valueDeclaration) @@ -21538,7 +21547,7 @@ var ts; target.set(id, sourceSymbol); } else { - if (!(targetSymbol.flags & 33554432)) { + if (!(targetSymbol.flags & 134217728)) { targetSymbol = cloneSymbol(targetSymbol); target.set(id, targetSymbol); } @@ -21565,7 +21574,7 @@ var ts; } mainModule = resolveExternalModuleSymbol(mainModule); if (mainModule.flags & 1920) { - mainModule = mainModule.flags & 33554432 ? mainModule : cloneSymbol(mainModule); + mainModule = mainModule.flags & 134217728 ? mainModule : cloneSymbol(mainModule); mergeSymbol(mainModule, moduleAugmentation.symbol); } else { @@ -21588,7 +21597,7 @@ var ts; } } function getSymbolLinks(symbol) { - if (symbol.flags & 67108864) + if (symbol.flags & 134217728) return symbol; var id = getSymbolId(symbol); return symbolLinks[id] || (symbolLinks[id] = {}); @@ -21600,6 +21609,9 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 ? type.objectFlags : 0; } + function getCheckFlags(symbol) { + return symbol.flags & 134217728 ? symbol.checkFlags : 0; + } function isGlobalSourceFile(node) { return node.kind === 263 && !ts.isExternalOrCommonJsModule(node); } @@ -21607,7 +21619,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -22217,7 +22229,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((symbol.flags & 16777216) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((getCheckFlags(symbol) & 1) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -22400,16 +22412,7 @@ var ts; : symbol; } function symbolIsValue(symbol) { - if (symbol.flags & 16777216) { - return symbolIsValue(getSymbolLinks(symbol).target); - } - if (symbol.flags & 107455) { - return true; - } - if (symbol.flags & 8388608) { - return (resolveAlias(symbol).flags & 107455) !== 0; - } - return false; + return !!(symbol.flags & 107455 || symbol.flags & 8388608 && resolveAlias(symbol).flags & 107455); } function findConstructorDeclaration(node) { var members = node.members; @@ -22832,7 +22835,7 @@ var ts; function appendParentTypeArgumentsAndSymbolName(symbol) { if (parentSymbol) { if (flags & 1) { - if (symbol.flags & 16777216) { + if (getCheckFlags(symbol) & 1) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -23070,7 +23073,7 @@ var ts; writeSpace(writer); } buildSymbolDisplay(prop, writer); - if (prop.flags & 536870912) { + if (prop.flags & 67108864) { writePunctuation(writer, 54); } } @@ -23230,7 +23233,11 @@ var ts; } writePunctuation(writer, 55); writeSpace(writer); - buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); + var type = getTypeOfSymbol(p); + if (isRequiredInitializedParameter(parameterNode)) { + type = includeFalsyTypes(type, 2048); + } + buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { if (bindingPattern.kind === 173) { @@ -23688,7 +23695,7 @@ var ts; getUnionType([type, checkExpressionCached(declaration.initializer)], true) : type; } - function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + function getTypeForDeclarationFromJSDocComment(declaration) { var jsdocType = ts.getJSDocType(declaration); if (jsdocType) { return getTypeFromTypeNode(jsdocType); @@ -23706,9 +23713,17 @@ var ts; function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } + function removeOptionalityFromAnnotation(annotatedType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 145 && + declaration.initializer && + getFalsyFlags(annotatedType) & 2048 && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048); + return annotationIncludesUndefined ? getNonNullableType(annotatedType) : annotatedType; + } function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536) { - var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); + var type = getTypeForDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { return type; } @@ -23724,7 +23739,8 @@ var ts; return getTypeForBindingElement(declaration); } if (declaration.type) { - return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); + var declaredType = removeOptionalityFromAnnotation(getTypeFromTypeNode(declaration.type), declaration); + return addOptionality(declaredType, declaration.questionToken && includeOptionality); } if ((compilerOptions.noImplicitAny || declaration.flags & 65536) && declaration.kind === 225 && !ts.isBindingPattern(declaration.name) && @@ -23773,6 +23789,21 @@ var ts; } return undefined; } + function getTypeForJSSpecialPropertyDeclaration(declaration) { + var expression = declaration.kind === 193 ? declaration : + declaration.kind === 178 ? ts.getAncestor(declaration, 193) : + undefined; + if (!expression) { + return unknownType; + } + if (expression.flags & 65536) { + var type = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type && type !== unknownType) { + return getWidenedType(type); + } + } + return getWidenedLiteralType(checkExpressionCached(expression.right)); + } function getTypeFromBindingElement(element, includePatternInType, reportErrors) { if (element.initializer) { return checkDeclarationInitializer(element); @@ -23800,7 +23831,7 @@ var ts; return; } var text = ts.getTextOfPropertyName(name); - var flags = 4 | 67108864 | (e.initializer ? 536870912 : 0); + var flags = 4 | (e.initializer ? 67108864 : 0); var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; @@ -23861,7 +23892,7 @@ var ts; function getTypeOfVariableOrParameterOrProperty(symbol) { var links = getSymbolLinks(symbol); if (!links.type) { - if (symbol.flags & 134217728) { + if (symbol.flags & 16777216) { return links.type = getTypeOfPrototypeProperty(symbol); } var declaration = symbol.valueDeclaration; @@ -23880,16 +23911,7 @@ var ts; var type = void 0; if (declaration.kind === 193 || declaration.kind === 178 && declaration.parent.kind === 193) { - if (declaration.flags & 65536) { - var jsdocType = ts.getJSDocType(declaration.parent); - if (jsdocType) { - return links.type = getTypeFromTypeNode(jsdocType); - } - } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 193 ? - checkExpressionCached(decl.right) : - checkExpressionCached(decl.parent.right); }); - type = getUnionType(declaredTypes, true); + type = getWidenedType(getUnionType(ts.map(symbol.declarations, getTypeForJSSpecialPropertyDeclaration), true)); } else { type = getWidenedTypeForVariableLikeDeclaration(declaration, true); @@ -23926,7 +23948,7 @@ var ts; var getter = ts.getDeclarationOfKind(symbol, 152); var setter = ts.getDeclarationOfKind(symbol, 153); if (getter && getter.flags & 65536) { - var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; } @@ -23990,7 +24012,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 536870912 ? includeFalsyTypes(type, 2048) : type; + links.type = strictNullChecks && symbol.flags & 67108864 ? includeFalsyTypes(type, 2048) : type; } } } @@ -24038,7 +24060,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (symbol.flags & 16777216) { + if (getCheckFlags(symbol) & 1) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 | 4)) { @@ -24730,7 +24752,7 @@ var ts; s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), true); - s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); + s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); } s.resolvedReturnType = undefined; s.unionSignatures = unionSignatures; @@ -24888,10 +24910,10 @@ var ts; if (t.flags & 32) { var propName = t.text; var modifiersProp = getPropertyOfType(modifiersType, propName); - var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912); - var prop = createSymbol(4 | 67108864 | (isOptional ? 536870912 : 0), propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864); + var prop = createSymbol(4 | (isOptional ? 67108864 : 0), propName); + prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 4 : 0; prop.type = propType; - prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); if (propertySymbol) { prop.mappedTypeOrigin = propertySymbol; } @@ -25084,18 +25106,19 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var types = containingType.types; - var excludeModifiers = containingType.flags & 65536 ? 8 | 16 : 0; var props; - var commonFlags = (containingType.flags & 131072) ? 536870912 : 0; - var isReadonly = false; - var isPartial = false; + var types = containingType.types; + var isUnion = containingType.flags & 65536; + var excludeModifiers = isUnion ? 24 : 0; + var commonFlags = isUnion ? 0 : 67108864; + var checkFlags = 2; for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & excludeModifiers)) { + var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { props = [prop]; @@ -25103,25 +25126,26 @@ var ts; else if (!ts.contains(props, prop)) { props.push(prop); } - if (isReadonlySymbol(prop)) { - isReadonly = true; - } + checkFlags |= (isReadonlySymbol(prop) ? 4 : 0) | + (!(modifiers & 24) ? 32 : 0) | + (modifiers & 16 ? 64 : 0) | + (modifiers & 8 ? 128 : 0) | + (modifiers & 32 ? 256 : 0); } - else if (containingType.flags & 65536) { - isPartial = true; + else if (isUnion) { + checkFlags |= 8; } } } if (!props) { return undefined; } - if (props.length === 1 && !isPartial) { + if (props.length === 1 && !(checkFlags & 8)) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -25132,17 +25156,15 @@ var ts; commonType = type; } else if (type !== commonType) { - hasNonUniformType = true; + checkFlags |= 16; } propTypes.push(type); } - var result = createSymbol(4 | 67108864 | 268435456 | commonFlags, name); + var result = createSymbol(4 | commonFlags, name); + result.checkFlags = checkFlags; result.containingType = containingType; - result.hasNonUniformType = hasNonUniformType; - result.isPartial = isPartial; result.declarations = declarations; - result.isReadonly = isReadonly; - result.type = containingType.flags & 65536 ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } function getUnionOrIntersectionProperty(type, name) { @@ -25158,7 +25180,7 @@ var ts; } function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); - return property && !(property.flags & 268435456 && property.isPartial) ? property : undefined; + return property && !(getCheckFlags(property) & 8) ? property : undefined; } function getPropertyOfType(type, name) { type = getApparentType(type); @@ -25287,6 +25309,12 @@ var ts; ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + } return false; } function createTypePredicateFromTypePredicateNode(node) { @@ -25316,6 +25344,7 @@ var ts; var hasThisParameter = void 0; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) { var param = declaration.parameters[i]; var paramSymbol = param.symbol; @@ -25335,7 +25364,8 @@ var ts; } var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param); + isJSDocOptionalParameter(param) || + isUntypedSignatureInJSFile; if (!isOptionalParameter_1) { minArgumentCount = parameters.length; } @@ -25807,7 +25837,7 @@ var ts; for (var i = 0; i < arity; i++) { var typeParameter = createType(16384); typeParameters.push(typeParameter); - var property = createSymbol(4 | 67108864, "" + i); + var property = createSymbol(4, "" + i); property.type = typeParameter; properties.push(property); } @@ -26022,7 +26052,10 @@ var ts; if (type.flags & 65536 && typeSet.unionIndex === undefined) { typeSet.unionIndex = typeSet.length; } - typeSet.push(type); + if (!(type.flags & 32768 && type.objectFlags & 16 && + type.symbol && type.symbol.flags & (16 | 8192) && containsIdenticalType(typeSet, type))) { + typeSet.push(type); + } } } function addTypesToIntersection(typeSet, types) { @@ -26304,15 +26337,15 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 536870912) { + if (maybeTypeOfKind(rightType, 2048) || rightProp.flags & 67108864) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); - var flags = 4 | 67108864 | (leftProp.flags & 536870912); + var flags = 4 | (leftProp.flags & 67108864); var result = createSymbol(flags, leftProp.name); + result.checkFlags = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp) ? 4 : 0; result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; - result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp); members.set(leftProp.name, result); } } @@ -26603,12 +26636,13 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (symbol.flags & 16777216) { + if (getCheckFlags(symbol) & 1) { var links = getSymbolLinks(symbol); symbol = links.target; mapper = combineTypeMappers(links.mapper, mapper); } - var result = createSymbol(16777216 | 67108864 | symbol.flags, symbol.name); + var result = createSymbol(symbol.flags, symbol.name); + result.checkFlags = 1; result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -27389,20 +27423,42 @@ var ts; if (target.flags & 65536 && containsType(targetTypes, source)) { return -1; } - var len = targetTypes.length; - for (var i = 0; i < len; i++) { - var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, false); if (related) { return related; } } + if (reportErrors) { + var discriminantType = findMatchingDiscriminantType(source, target); + isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], true); + } return 0; } + function findMatchingDiscriminantType(source, target) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProperty = sourceProperties_1[_i]; + if (isDiscriminantProperty(target, sourceProperty.name)) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _a = 0, _b = target.types; _a < _b.length; _a++) { + var type = _b[_a]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.name); + if (targetType && isRelatedTo(sourceType, targetType)) { + return type; + } + } + } + } + } + } function typeRelatedToEachType(source, target, reportErrors) { var result = -1; var targetTypes = target.types; - for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { - var targetType = targetTypes_1[_i]; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; var related = isRelatedTo(source, targetType, reportErrors); if (!related) { return 0; @@ -27572,17 +27628,23 @@ var ts; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { - if (!(targetProp.flags & 536870912) || requireOptionalProperties) { + if (!(targetProp.flags & 67108864) || requireOptionalProperties) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); } return 0; } } - else if (!(targetProp.flags & 134217728)) { + else if (!(targetProp.flags & 16777216)) { var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 || targetPropFlags & 8) { + if (getCheckFlags(sourceProp) & 128) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); + } + return 0; + } if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { if (sourcePropFlags & 8 && targetPropFlags & 8) { @@ -27596,12 +27658,9 @@ var ts; } } else if (targetPropFlags & 16) { - var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32; - var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined; - var targetClass = getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp)); - if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { + if (!isValidOverrideOf(sourceProp, targetProp)) { if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass)); + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); } return 0; } @@ -27620,7 +27679,7 @@ var ts; return 0; } result &= related; - if (relation !== comparableRelation && sourceProp.flags & 536870912 && !(targetProp.flags & 536870912)) { + if (relation !== comparableRelation && sourceProp.flags & 67108864 && !(targetProp.flags & 67108864)) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target)); } @@ -27641,8 +27700,8 @@ var ts; return 0; } var result = -1; - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProp = sourceProperties_1[_i]; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProp = sourceProperties_2[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return 0; @@ -27803,6 +27862,37 @@ var ts; return false; } } + function forEachProperty(prop, callback) { + if (getCheckFlags(prop) & 2) { + for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var p = getPropertyOfType(t, prop.name); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + function isValidOverrideOf(sourceProp, targetProp) { + return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 ? + !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); + } + function isClassDerivedFromDeclaringClasses(checkClass, prop) { + return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } function isAbstractConstructorType(type) { if (getObjectFlags(type) & 16) { var symbol = type.symbol; @@ -27848,7 +27938,7 @@ var ts; } } else { - if ((sourceProp.flags & 536870912) !== (targetProp.flags & 536870912)) { + if ((sourceProp.flags & 67108864) !== (targetProp.flags & 67108864)) { return 0; } } @@ -28047,7 +28137,7 @@ var ts; types.push(undefinedType); if (flags & 4096) types.push(nullType); - return getUnionType(types, true); + return getUnionType(types); } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 ? @@ -28062,8 +28152,8 @@ var ts; getSignaturesOfType(type, 0).length === 0 && getSignaturesOfType(type, 1).length === 0; } - function createTransientSymbol(source, type) { - var symbol = createSymbol(source.flags | 67108864, source.name); + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.name); symbol.declarations = source.declarations; symbol.parent = source.parent; symbol.type = type; @@ -28079,7 +28169,7 @@ var ts; var property = _a[_i]; var original = getTypeOfSymbol(property); var updated = f(original); - members.set(property.name, updated === original ? property : createTransientSymbol(property, updated)); + members.set(property.name, updated === original ? property : createSymbolWithType(property, updated)); } ; return members; @@ -28268,7 +28358,7 @@ var ts; var typeInferencesArray = [typeInferences]; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 536870912; + var optionalMask = target.declaration.questionToken ? 0 : 67108864; var members = createSymbolTable(properties); for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; @@ -28276,10 +28366,10 @@ var ts; if (!inferredPropType) { return undefined; } - var inferredProp = createSymbol(4 | 67108864 | prop.flags & optionalMask, prop.name); + var inferredProp = createSymbol(4 | prop.flags & optionalMask, prop.name); + inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 4 : 0; inferredProp.declarations = prop.declarations; inferredProp.type = inferredPropType; - inferredProp.isReadonly = readonlyMask && isReadonlySymbol(prop); members.set(prop.name, inferredProp); } if (indexInfo) { @@ -28390,8 +28480,8 @@ var ts; var targetTypes = target.types; var typeVariableCount = 0; var typeVariable = void 0; - for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { - var t = targetTypes_2[_d]; + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; if (t.flags & 540672 && ts.contains(typeVariables, t)) { typeVariable = t; typeVariableCount++; @@ -28673,9 +28763,9 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && prop.flags & 268435456) { + if (prop && getCheckFlags(prop) & 2) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.checkFlags & 16 && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -28823,10 +28913,16 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, undefined, false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - return node.parent.kind === 176 || node.parent.kind === 259 ? + var isDestructuringDefaultAssignment = node.parent.kind === 176 && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 259 && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 193 && parent.parent.left === parent || + parent.parent.kind === 215 && parent.parent.initializer === parent; + } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); } @@ -29103,7 +29199,16 @@ var ts; } } var type = void 0; - if (flow.flags & 16) { + if (flow.flags & 4096) { + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flow.flags & 2048) { + flow = flow.antecedent; + continue; + } + else if (flow.flags & 16) { type = getTypeAtFlowAssignment(flow); if (!type) { flow = flow.antecedent; @@ -29237,6 +29342,9 @@ var ts; var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; + if (antecedent.flags & 2048 && antecedent.lock.locked) { + continue; + } var flowType = getTypeAtFlowNode(antecedent); var type = getTypeFromFlowType(flowType); if (type === declaredType && declaredType === initialType) { @@ -30537,12 +30645,12 @@ var ts; type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; - var prop = createSymbol(4 | 67108864 | member.flags, member.name); + var prop = createSymbol(4 | member.flags, member.name); if (inDestructuringPattern) { var isOptional = (memberDecl.kind === 259 && hasDefaultValue(memberDecl.initializer)) || (memberDecl.kind === 260 && memberDecl.objectAssignmentInitializer); if (isOptional) { - prop.flags |= 536870912; + prop.flags |= 67108864; } if (ts.hasDynamicName(memberDecl)) { patternWithComputedProperties = true; @@ -30551,7 +30659,7 @@ var ts; else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { - prop.flags |= impliedProp.flags & 536870912; + prop.flags |= impliedProp.flags & 67108864; } else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0)) { error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); @@ -30608,7 +30716,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { var prop = _a[_i]; if (!propertiesTable.get(prop.name)) { - if (!(prop.flags & 536870912)) { + if (!(prop.flags & 67108864)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } propertiesTable.set(prop.name, prop); @@ -30983,7 +31091,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var _i = 0, targetProperties_1 = targetProperties; _i < targetProperties_1.length; _i++) { var targetProperty = targetProperties_1[_i]; - if (!(targetProperty.flags & 536870912) && !nameTable.get(targetProperty.name)) { + if (!(targetProperty.flags & 67108864) && !nameTable.get(targetProperty.name)) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperty.name, typeToString(targetAttributesType)); } } @@ -31005,17 +31113,35 @@ var ts; return s.valueDeclaration ? s.valueDeclaration.kind : 148; } function getDeclarationModifierFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 ? 4 | 32 : 0; + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 ? flags : flags & ~28; + } + if (getCheckFlags(s) & 2) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 128 ? 8 : + checkFlags & 32 ? 4 : + 16; + var staticModifier = checkFlags & 256 ? 32 : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216) { + return 4 | 32; + } + return 0; } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; } - function checkClassPropertyAccess(node, left, type, prop) { + function checkPropertyAccessibility(node, left, type, prop) { var flags = getDeclarationModifierFlagsFromSymbol(prop); - var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); var errorNode = node.kind === 178 || node.kind === 225 ? node.name : node.right; + if (getCheckFlags(prop) & 128) { + error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); + return false; + } if (left.kind === 96) { if (languageVersion < 2) { var propKind = getDeclarationKindFromSymbol(prop); @@ -31025,7 +31151,7 @@ var ts; } } if (flags & 128) { - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } } @@ -31035,7 +31161,7 @@ var ts; if (flags & 8) { var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } return true; @@ -31045,10 +31171,10 @@ var ts; } var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return hasBaseType(enclosingClass, declaringClass) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; }); if (!enclosingClass) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); return false; } if (flags & 32) { @@ -31103,7 +31229,7 @@ var ts; noUnusedIdentifiers && (prop.flags & 106500) && prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8)) { - if (prop.flags & 16777216) { + if (getCheckFlags(prop) & 1) { getSymbolLinks(prop).target.isReferenced = true; } else { @@ -31147,9 +31273,7 @@ var ts; } markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; - if (prop.parent && prop.parent.flags & 32) { - checkClassPropertyAccess(node, left, apparentType, prop); - } + checkPropertyAccessibility(node, left, apparentType, prop); var propType = getTypeOfSymbol(prop); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -31173,8 +31297,8 @@ var ts; var type = checkExpression(left); if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(getWidenedType(type), propertyName); - if (prop && prop.parent && prop.parent.flags & 32) { - return checkClassPropertyAccess(node, left, type, prop); + if (prop) { + return checkPropertyAccessibility(node, left, type, prop); } } return true; @@ -32155,7 +32279,7 @@ var ts; var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { if (!parameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + signature.thisParameter = createSymbolWithType(context.thisParameter, undefined); } assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } @@ -32465,11 +32589,11 @@ var ts; return true; } function isReadonlySymbol(symbol) { - return symbol.isReadonly || - symbol.flags & 4 && (getDeclarationModifierFlagsFromSymbol(symbol) & 64) !== 0 || - symbol.flags & 3 && (getDeclarationNodeFlagsFromSymbol(symbol) & 2) !== 0 || + return !!(getCheckFlags(symbol) & 4 || + symbol.flags & 4 && getDeclarationModifierFlagsFromSymbol(symbol) & 64 || + symbol.flags & 3 && getDeclarationNodeFlagsFromSymbol(symbol) & 2 || symbol.flags & 98304 && !(symbol.flags & 65536) || - (symbol.flags & 8) !== 0; + symbol.flags & 8); } function isReferenceToReadonlyEntity(expr, symbol) { if (isReadonlySymbol(symbol)) { @@ -34732,8 +34856,8 @@ var ts; var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); markPropertyAsReferenced(property); - if (parent.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent, parent.initializer, parentType, property); + if (parent.initializer && property) { + checkPropertyAccessibility(parent, parent.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { @@ -35465,7 +35589,7 @@ var ts; } } function getTargetSymbol(s) { - return s.flags & 16777216 ? getSymbolLinks(s).target : s; + return getCheckFlags(s) & 1 ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -35475,7 +35599,7 @@ var ts; 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) { + if (base.flags & 16777216) { continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); @@ -35913,7 +36037,7 @@ var ts; } if (isAmbientExternalModule) { if (ts.isExternalModuleAugmentation(node)) { - var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432); + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 134217728); if (checkBody && node.body) { for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { var statement = _a[_i]; @@ -35983,7 +36107,7 @@ var ts; } var symbol = getSymbolOfNode(node); if (symbol) { - var reportError = !(symbol.flags & 33554432); + var reportError = !(symbol.flags & 134217728); if (!reportError) { reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); } @@ -36840,7 +36964,7 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (symbol.flags & 268435456) { + if (getCheckFlags(symbol) & 2) { var symbols_3 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { @@ -36851,7 +36975,7 @@ var ts; }); return symbols_3; } - else if (symbol.flags & 67108864) { + else if (symbol.flags & 134217728) { if (symbol.leftSpread) { var links = symbol; return [links.leftSpread, links.rightSpread]; @@ -37056,6 +37180,12 @@ var ts; } return false; } + function isRequiredInitializedParameter(parameter) { + return strictNullChecks && + !isOptionalParameter(parameter) && + parameter.initializer && + !(ts.getModifierFlags(parameter) & 92); + } function getNodeCheckFlags(node) { node = ts.getParseTreeNode(node); return node ? getNodeLinks(node).flags : undefined; @@ -37135,6 +37265,9 @@ var ts; var type = symbol && !(symbol.flags & (2048 | 131072)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; + if (flags & 4096) { + type = includeFalsyTypes(type, 2048); + } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { @@ -37216,6 +37349,7 @@ var ts; isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, @@ -37431,7 +37565,7 @@ var ts; return emptyObjectType; } function createThenableType() { - var thenPropertySymbol = createSymbol(67108864 | 4, "then"); + var thenPropertySymbol = createSymbol(4, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; var thenableType = createObjectType(16); thenableType.properties = [thenPropertySymbol]; @@ -38233,9 +38367,29 @@ var ts; } } } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1)) { + checkESModuleMarker(node.name); + } var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } + function checkESModuleMarker(name) { + if (name.kind === 70) { + if (ts.unescapeIdentifier(name.text) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 70) { if (name.originalKeywordKind === 109) { @@ -38244,8 +38398,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -41187,8 +41341,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 261) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -45607,6 +45761,9 @@ var ts; startLexicalEnvironment(); var statements = []; var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (!currentModuleInfo.exportEquals) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); ts.addRange(statements, endLexicalEnvironment()); @@ -45697,6 +45854,9 @@ var ts; startLexicalEnvironment(); var statements = []; var statementOffset = ts.addPrologueDirectives(statements, node.statements, !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (!currentModuleInfo.exportEquals) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, true)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); ts.addRange(statements, endLexicalEnvironment()); @@ -46042,26 +46202,26 @@ var ts; return statements; } function appendExportStatement(statements, exportName, expression, location, allowComments) { - if (exportName.text === "default") { - var sourceFile = ts.getOriginalNode(currentSourceFile, ts.isSourceFile); - if (sourceFile && !sourceFile.symbol.exports.get("___esModule")) { - if (languageVersion === 0) { - statements = ts.append(statements, ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createTrue()))); - } - else { - statements = ts.append(statements, ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ - ts.createIdentifier("exports"), - ts.createLiteral("__esModule"), - ts.createObjectLiteral([ - ts.createPropertyAssignment("value", ts.createTrue()) - ]) - ]))); - } - } - } statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); return statements; } + function createUnderscoreUnderscoreESModule() { + var statement; + if (languageVersion === 0) { + statement = ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(true))); + } + else { + statement = ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ])); + } + ts.setEmitFlags(statement, 524288); + return statement; + } function createExportStatement(name, value, location, allowComments) { var statement = ts.setTextRange(ts.createStatement(createExportExpression(name, value)), location); ts.startOnNewLine(statement); @@ -47535,12 +47695,16 @@ var ts; function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); - if (type) { + var shouldUseResolverType = declaration.kind === 145 && + resolver.isRequiredInitializedParameter(declaration); + if (type && !shouldUseResolverType) { emitType(type); } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); + var format = 2 | 1024 | + (shouldUseResolverType ? 4096 : 0); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } } @@ -49120,6 +49284,7 @@ var ts; emitNodeWithComments: emitNodeWithComments, emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, + emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition, }; function emitNodeWithComments(hint, node, emitCallback) { if (disabled) { @@ -49253,6 +49418,12 @@ var ts; writer.write(" "); } } + function emitLeadingCommentsOfPosition(pos) { + if (disabled || pos === -1) { + return; + } + emitLeadingComments(pos, true); + } function emitTrailingComments(pos) { forEachTrailingCommentToEmit(pos, emitTrailingComment); } @@ -49518,7 +49689,7 @@ var ts; var newLine = ts.getNewLineCharacter(printerOptions); var languageVersion = ts.getEmitScriptTarget(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); - var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; + var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; var currentSourceFile; var nodeIdToGeneratedName; var autoGeneratedIdToGeneratedName; @@ -50428,6 +50599,9 @@ var ts; else { writeToken(16, node.pos, node); emitBlockStatements(node); + increaseIndent(); + emitLeadingCommentsOfPosition(node.statements.end); + decreaseIndent(); writeToken(17, node.statements.end, node); } } @@ -51130,6 +51304,9 @@ var ts; for (var i = 0; i < count; i++) { var child = children[start + i]; if (previousSibling) { + if (delimiter && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } write(delimiter); if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { if ((format & (3 | 64)) === 0) { @@ -51163,6 +51340,9 @@ var ts; if (format & 16 && hasTrailingComma) { write(","); } + if (previousSibling && delimiter && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } if (format & 64) { decreaseIndent(); } @@ -57511,7 +57691,7 @@ var ts; if (isObjectBindingPatternElementWithoutPropertyName(symbol)) { return undefined; } - if (symbol.parent || (symbol.flags & 268435456)) { + if (symbol.parent || (symbol.flags & 134217728 && symbol.checkFlags & 2)) { return undefined; } var scope; @@ -57666,7 +57846,7 @@ var ts; if (relatedSymbol) { addReferenceToRelatedSymbol(referenceLocation, relatedSymbol); } - else if (!(referenceSymbol.flags & 67108864) && ts.contains(searchSymbols, shorthandValueSymbol)) { + else if (!(referenceSymbol.flags & 134217728) && ts.contains(searchSymbols, shorthandValueSymbol)) { addReferenceToRelatedSymbol(referenceSymbolDeclaration.name, shorthandValueSymbol); } else if (searchLocation.kind === 122) { @@ -60919,7 +61099,7 @@ var ts; if (flags & 16384) return ts.ScriptElementKind.constructorImplementationElement; if (flags & 4) { - if (flags & 268435456) { + if (flags & 134217728 && symbol.checkFlags & 2) { var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { var rootSymbolFlags = rootSymbol.getFlags(); if (rootSymbolFlags & (98308 | 3)) { diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index b93f69df770..e4b99514255 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -1448,9 +1448,21 @@ declare namespace ts { ArrayMutation = 256, Referenced = 512, Shared = 1024, + PreFinally = 2048, + AfterFinally = 4096, Label = 12, Condition = 96, } + interface FlowLock { + locked?: boolean; + } + interface AfterFinallyFlow extends FlowNode, FlowLock { + antecedent: FlowNode; + } + interface PreFinallyFlow extends FlowNode { + antecedent: FlowNode; + lock: FlowLock; + } interface FlowNode { flags: FlowFlags; id?: number; @@ -1697,6 +1709,7 @@ declare namespace ts { InTypeAlias = 512, UseTypeAliasValue = 1024, SuppressAnyReturnType = 2048, + AddUndefined = 4096, } enum SymbolFormatFlags { None = 0, @@ -1746,13 +1759,10 @@ declare namespace ts { ExportType = 2097152, ExportNamespace = 4194304, Alias = 8388608, - Instantiated = 16777216, - Merged = 33554432, - Transient = 67108864, - Prototype = 134217728, - SyntheticProperty = 268435456, - Optional = 536870912, - ExportStar = 1073741824, + Prototype = 16777216, + ExportStar = 33554432, + Optional = 67108864, + Transient = 134217728, Enum = 384, Variable = 3, Value = 107455, @@ -1943,9 +1953,8 @@ declare namespace ts { isReadonly: boolean; declaration?: SignatureDeclaration; } - interface FileExtensionInfo { + interface JsFileExtensionInfo { extension: string; - scriptKind: ScriptKind; isMixedContent: boolean; } interface DiagnosticMessage { @@ -2918,7 +2927,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: FileExtensionInfo[]): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine; function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; diff --git a/lib/typescript.js b/lib/typescript.js index d3284aaaa51..c6df692fb3a 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -483,6 +483,8 @@ var ts; FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; + FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; + FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; FlowFlags[FlowFlags["Label"] = 12] = "Label"; FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); @@ -519,6 +521,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 2048] = "SuppressAnyReturnType"; + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 4096] = "AddUndefined"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -600,13 +603,10 @@ var ts; SymbolFlags[SymbolFlags["ExportType"] = 2097152] = "ExportType"; SymbolFlags[SymbolFlags["ExportNamespace"] = 4194304] = "ExportNamespace"; SymbolFlags[SymbolFlags["Alias"] = 8388608] = "Alias"; - SymbolFlags[SymbolFlags["Instantiated"] = 16777216] = "Instantiated"; - SymbolFlags[SymbolFlags["Merged"] = 33554432] = "Merged"; - SymbolFlags[SymbolFlags["Transient"] = 67108864] = "Transient"; - SymbolFlags[SymbolFlags["Prototype"] = 134217728] = "Prototype"; - SymbolFlags[SymbolFlags["SyntheticProperty"] = 268435456] = "SyntheticProperty"; - SymbolFlags[SymbolFlags["Optional"] = 536870912] = "Optional"; - SymbolFlags[SymbolFlags["ExportStar"] = 1073741824] = "ExportStar"; + SymbolFlags[SymbolFlags["Prototype"] = 16777216] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 33554432] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 67108864] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 134217728] = "Transient"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; @@ -650,6 +650,19 @@ var ts; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); /* @internal */ + var CheckFlags; + (function (CheckFlags) { + CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; + CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; + CheckFlags[CheckFlags["Readonly"] = 4] = "Readonly"; + CheckFlags[CheckFlags["Partial"] = 8] = "Partial"; + CheckFlags[CheckFlags["HasNonUniformType"] = 16] = "HasNonUniformType"; + CheckFlags[CheckFlags["ContainsPublic"] = 32] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 64] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 128] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 256] = "ContainsStatic"; + })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + /* @internal */ var NodeCheckFlags; (function (NodeCheckFlags) { NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; @@ -3083,13 +3096,13 @@ var ts; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0) { + if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + var extensions = allSupportedExtensions.slice(0); for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { var extInfo = extraFileExtensions_1[_i]; - if (needAllExtensions || extInfo.scriptKind === 3 /* TS */) { + if (extensions.indexOf(extInfo.extension) === -1) { extensions.push(extInfo.extension); } } @@ -3126,14 +3139,13 @@ var ts; (function (ExtensionPriority) { ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; - ExtensionPriority[ExtensionPriority["Limit"] = 5] = "Limit"; ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { - return adjustExtensionPriority(i); + return adjustExtensionPriority(i, supportedExtensions); } } // If its not in the list of supported extensions, this is likely a @@ -3144,27 +3156,27 @@ var ts; /** * Adjusts an extension priority to be the highest priority within the same range. */ - function adjustExtensionPriority(extensionPriority) { + function adjustExtensionPriority(extensionPriority, supportedExtensions) { if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { return 0 /* TypeScriptFiles */; } - else if (extensionPriority < 5 /* Limit */) { + else if (extensionPriority < supportedExtensions.length) { return 2 /* DeclarationAndJavaScriptFiles */; } else { - return 5 /* Limit */; + return supportedExtensions.length; } } ts.adjustExtensionPriority = adjustExtensionPriority; /** * Gets the next lowest extension priority for a given priority. */ - function getNextLowestExtensionPriority(extensionPriority) { + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { return 2 /* DeclarationAndJavaScriptFiles */; } else { - return 5 /* Limit */; + return supportedExtensions.length; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; @@ -3770,7 +3782,7 @@ var ts; // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) var options; if (!directoryExists(directoryName) || (isUNCPath(directoryName) && process.platform === "win32")) { - // do nothing if either + // do nothing if either // - target folder does not exist // - this is UNC path on Windows (https://github.com/Microsoft/TypeScript/issues/13874) return noOpFileWatcher; @@ -3856,6 +3868,7 @@ var ts; require("source-map-support").install(); } catch (e) { + // Could not enable source maps. } }, setTimeout: setTimeout, @@ -4112,6 +4125,7 @@ var ts; Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", message: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", message: "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", message: "Generators are only available when targeting ECMAScript 2015 or higher." }, @@ -4391,6 +4405,7 @@ var ts; Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: { code: 2543, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", message: "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference." }, Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: { code: 2544, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", message: "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference." }, A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: { code: 2545, category: ts.DiagnosticCategory.Error, key: "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", message: "A mixin class must have a constructor with a single rest parameter of type 'any[]'." }, + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: { code: 2546, category: ts.DiagnosticCategory.Error, key: "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", message: "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4644,7 +4659,7 @@ var ts; File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, Loading_module_0_from_node_modules_folder_target_file_type_1: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", message: "Loading module '{0}' from 'node_modules' folder, target file type '{1}'." }, Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_a_types_or_main_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_types_or_main_field_6100", message: "'package.json' does not have a 'types' or 'main' field." }, + package_json_does_not_have_a_0_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_0_field_6100", message: "'package.json' does not have a '{0}' field." }, package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, @@ -4681,7 +4696,6 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, - No_types_specified_in_package_json_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json', so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -7952,6 +7966,11 @@ var ts; return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); } ts.getCommentsFromJSDoc = getCommentsFromJSDoc; + function hasJSDocParameterTags(node) { + var parameterTags = getJSDocTags(node, 284 /* JSDocParameterTag */); + return parameterTags && parameterTags.length > 0; + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; function getJSDocTags(node, kind) { var docs = getJSDocs(node); if (docs) { @@ -21653,7 +21672,32 @@ var ts; if (node.finallyBlock) { // in finally flow is combined from pre-try/flow from try/flow from catch // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable - addAntecedent(preFinallyLabel, preTryFlow); + // also for finally blocks we inject two extra edges into the flow graph. + // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it + // second -> edge that represents post-finally flow. + // these edges are used in following scenario: + // let a; (1) + // try { a = someOperation(); (2)} + // finally { (3) console.log(a) } (4) + // (5) a + // flow graph for this case looks roughly like this (arrows show ): + // (1-pre-try-flow) <--.. <-- (2-post-try-flow) + // ^ ^ + // |*****(3-pre-finally-label) -----| + // ^ + // |-- ... <-- (4-post-finally-label) <--- (5) + // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account + // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) + // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable + // Simply speaking code inside finally block is treated as reachable as pre-try-flow + // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. + // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from + // final flows of these blocks without taking pre-try flow into account. + // + // extra edges that we inject allows to control this behavior + // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. + var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); // if flow after finally is unreachable - keep it @@ -21669,6 +21713,11 @@ var ts; : unreachableFlow; } } + if (!(currentFlow.flags & 1 /* Unreachable */)) { + var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } } else { currentFlow = finishFlowLabel(preFinallyLabel); @@ -22483,7 +22532,7 @@ var ts; case 148 /* PropertyDeclaration */: case 147 /* PropertySignature */: case 274 /* JSDocRecordMember */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); case 289 /* JSDocPropertyTag */: return bindJSDocProperty(node); case 259 /* PropertyAssignment */: @@ -22516,7 +22565,7 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); case 227 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 151 /* Constructor */: @@ -22648,11 +22697,11 @@ var ts; function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { // Export * in some sort of block construct - bindAnonymousDeclaration(node, 1073741824 /* ExportStar */, getDeclarationName(node)); + bindAnonymousDeclaration(node, 33554432 /* ExportStar */, getDeclarationName(node)); } else if (!node.exportClause) { // All export * declarations are collected in an __export symbol - declareSymbol(container.symbol.exports, container.symbol, node, 1073741824 /* ExportStar */, 0 /* None */); + declareSymbol(container.symbol.exports, container.symbol, node, 33554432 /* ExportStar */, 0 /* None */); } } function bindImportClause(node) { @@ -22751,7 +22800,7 @@ var 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. - var prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype"); + var prototypeSymbol = createSymbol(4 /* Property */ | 16777216 /* Prototype */, "prototype"); var symbolExport = symbol.exports.get(prototypeSymbol.name); if (symbolExport) { if (node.name) { @@ -22808,7 +22857,7 @@ var ts; // containing class. if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); } } function bindFunctionDeclaration(node) { @@ -23728,37 +23777,28 @@ var ts; } ts.moduleHasNonRelativeName = moduleHasNonRelativeName; /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, baseDirectory, state) { + function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { var jsonContent = readJson(packageJsonPath, state.host); - switch (extensions) { - case Extensions.DtsOnly: - case Extensions.TypeScript: - return tryReadFromField("typings") || tryReadFromField("types"); - case Extensions.JavaScript: - if (typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main); - } - return ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - } - return undefined; - } + return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); - } - return typesFilePath; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } + return; } + var fileName = jsonContent[fieldName]; + if (typeof fileName !== "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + } + return; + } + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; } } function readJson(path, host) { @@ -23794,6 +23834,7 @@ var ts; function getDefaultTypeRoots(currentDirectory, host) { if (!host.directoryExists) { return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + // And if it doesn't exist, tough. } var typeRoots; forEachAncestorDirectory(currentDirectory, function (directory) { @@ -24270,7 +24311,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state); + var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); } @@ -24284,7 +24326,7 @@ var ts; } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); } } @@ -24300,7 +24342,7 @@ var ts; } return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } @@ -24328,7 +24370,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } /* @internal */ function directoryProbablyExists(directoryName, host) { @@ -24397,47 +24439,51 @@ var ts; failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var mainOrTypesFile = tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, candidate, state); - if (mainOrTypesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(mainOrTypesFile), state.host); - // A package.json "typings" may specify an exact filename, or may choose to omit an extension. - var fromExactFile = tryFile(mainOrTypesFile, failedLookupLocations, onlyRecordFailures_1, state); - if (fromExactFile) { - var resolved_3 = fromExactFile && resolvedIfExtensionMatches(extensions, fromExactFile); - if (resolved_3) { - return resolved_3; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromExactFile); - } - } - var resolved = tryAddingExtensions(mainOrTypesFile, Extensions.TypeScript, failedLookupLocations, onlyRecordFailures_1, state); - if (resolved) { - return resolved; + if (considerPackageJson) { + var packageJsonPath = pathToPackageJson(candidate); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; } } else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_types_or_main_field); + if (directoryExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + failedLookupLocations.push(packageJsonPath); } } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - } return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); } + function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + if (!file) { + return undefined; + } + var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); + var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); + if (fromFile) { + var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return resolved; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); + } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { var extension = ts.tryGetExtensionFromPath(path); @@ -24529,7 +24575,7 @@ var ts; var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (moduleHasNonRelativeName(moduleName)) { // Climb up parent directories looking for a module. - var resolved_4 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { return resolutionFromCache; @@ -24537,8 +24583,8 @@ var ts; var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); }); - if (resolved_4) { - return resolved_4; + if (resolved_3) { + return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. @@ -24643,9 +24689,9 @@ var ts; var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; var strictNullChecks = compilerOptions.strictNullChecks; var emitResolver = createResolver(); - var undefinedSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "undefined"); + var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); undefinedSymbol.declarations = []; - var argumentsSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "arguments"); + var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, @@ -24711,8 +24757,8 @@ var ts; var numericLiteralTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; - var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown"); - var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__"); + var unknownSymbol = createSymbol(4 /* Property */, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__"); var anyType = createIntrinsicType(1 /* Any */, "any"); var autoType = createIntrinsicType(1 /* Any */, "any"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); @@ -24731,7 +24777,7 @@ var ts; var silentNeverType = createIntrinsicType(8192 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */ | 67108864 /* Transient */, "__type"); + var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); emptyTypeLiteralSymbol.members = ts.createMap(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -24961,7 +25007,9 @@ var ts; } function createSymbol(flags, name) { symbolCount++; - return new Symbol(flags, name); + var symbol = (new Symbol(flags | 134217728 /* Transient */, name)); + symbol.checkFlags = 0; + return symbol; } function getExcludedSymbolFlags(flags) { var result = 0; @@ -25007,7 +25055,7 @@ var ts; mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { - var result = createSymbol(symbol.flags | 33554432 /* Merged */, symbol.name); + var result = createSymbol(symbol.flags, symbol.name); result.declarations = symbol.declarations.slice(0); result.parent = symbol.parent; if (symbol.valueDeclaration) @@ -25068,7 +25116,7 @@ var ts; target.set(id, sourceSymbol); } else { - if (!(targetSymbol.flags & 33554432 /* Merged */)) { + if (!(targetSymbol.flags & 134217728 /* Transient */)) { targetSymbol = cloneSymbol(targetSymbol); target.set(id, targetSymbol); } @@ -25103,7 +25151,7 @@ var ts; if (mainModule.flags & 1920 /* Namespace */) { // if module symbol has already been merged - it is safe to use it. // otherwise clone it - mainModule = mainModule.flags & 33554432 /* Merged */ ? mainModule : cloneSymbol(mainModule); + mainModule = mainModule.flags & 134217728 /* Transient */ ? mainModule : cloneSymbol(mainModule); mergeSymbol(mainModule, moduleAugmentation.symbol); } else { @@ -25127,7 +25175,7 @@ var ts; } } function getSymbolLinks(symbol) { - if (symbol.flags & 67108864 /* Transient */) + if (symbol.flags & 134217728 /* Transient */) return symbol; var id = getSymbolId(symbol); return symbolLinks[id] || (symbolLinks[id] = {}); @@ -25139,6 +25187,9 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 /* Object */ ? type.objectFlags : 0; } + function getCheckFlags(symbol) { + return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; + } function isGlobalSourceFile(node) { return node.kind === 263 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } @@ -25146,7 +25197,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -25904,7 +25955,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -26108,20 +26159,7 @@ var ts; : symbol; } function symbolIsValue(symbol) { - // If it is an instantiated symbol, then it is a value if the symbol it is an - // instantiation of is a value. - if (symbol.flags & 16777216 /* Instantiated */) { - return symbolIsValue(getSymbolLinks(symbol).target); - } - // If the symbol has the value flag, it is trivially a value. - if (symbol.flags & 107455 /* Value */) { - return true; - } - // If it is an alias, then it is a value if the symbol it resolves to is a value. - if (symbol.flags & 8388608 /* Alias */) { - return (resolveAlias(symbol).flags & 107455 /* Value */) !== 0; - } - return false; + return !!(symbol.flags & 107455 /* Value */ || symbol.flags & 8388608 /* Alias */ && resolveAlias(symbol).flags & 107455 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -26617,7 +26655,7 @@ var ts; if (parentSymbol) { // Write type arguments of instantiated class/interface here if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (symbol.flags & 16777216 /* Instantiated */) { + if (getCheckFlags(symbol) & 1 /* Instantiated */) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -26891,7 +26929,7 @@ var ts; writeSpace(writer); } buildSymbolDisplay(prop, writer); - if (prop.flags & 536870912 /* Optional */) { + if (prop.flags & 67108864 /* Optional */) { writePunctuation(writer, 54 /* QuestionToken */); } } @@ -27052,7 +27090,11 @@ var ts; } writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); - buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); + var type = getTypeOfSymbol(p); + if (isRequiredInitializedParameter(parameterNode)) { + type = includeFalsyTypes(type, 2048 /* Undefined */); + } + buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. @@ -27563,7 +27605,7 @@ var ts; getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : type; } - function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + function getTypeForDeclarationFromJSDocComment(declaration) { var jsdocType = ts.getJSDocType(declaration); if (jsdocType) { return getTypeFromTypeNode(jsdocType); @@ -27581,13 +27623,22 @@ var ts; function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } + /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ + function removeOptionalityFromAnnotation(annotatedType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 145 /* Parameter */ && + declaration.initializer && + getFalsyFlags(annotatedType) & 2048 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048 /* Undefined */); + return annotationIncludesUndefined ? getNonNullableType(annotatedType) : annotatedType; + } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536 /* JavaScriptFile */) { // If this is a variable in a JavaScript file, then use the JSDoc type (if it has // one as its type), otherwise fallback to the below standard TS codepaths to // try to figure it out. - var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); + var type = getTypeForDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { return type; } @@ -27610,7 +27661,8 @@ var ts; } // Use type from type annotation if one is present if (declaration.type) { - return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality); + var declaredType = removeOptionalityFromAnnotation(getTypeFromTypeNode(declaration.type), declaration); + return addOptionality(declaredType, /*optional*/ declaration.questionToken && includeOptionality); } if ((compilerOptions.noImplicitAny || declaration.flags & 65536 /* JavaScriptFile */) && declaration.kind === 225 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && @@ -27671,6 +27723,23 @@ var ts; // No type specified and nothing can be inferred return undefined; } + // Return the inferred type for a variable, parameter, or property declaration + function getTypeForJSSpecialPropertyDeclaration(declaration) { + var expression = declaration.kind === 193 /* BinaryExpression */ ? declaration : + declaration.kind === 178 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 193 /* BinaryExpression */) : + undefined; + if (!expression) { + return unknownType; + } + if (expression.flags & 65536 /* JavaScriptFile */) { + // If there is a JSDoc type, use it + var type = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type && type !== unknownType) { + return getWidenedType(type); + } + } + return getWidenedLiteralType(checkExpressionCached(expression.right)); + } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding // pattern. Otherwise, it is the type any. @@ -27703,7 +27772,7 @@ var ts; return; } var text = ts.getTextOfPropertyName(name); - var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); + var flags = 4 /* Property */ | (e.initializer ? 67108864 /* Optional */ : 0); var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; @@ -27788,7 +27857,7 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { // Handle prototype property - if (symbol.flags & 134217728 /* Prototype */) { + if (symbol.flags & 16777216 /* Prototype */) { return links.type = getTypeOfPrototypeProperty(symbol); } // Handle catch clause variables @@ -27815,17 +27884,7 @@ var ts; // * className.prototype.method = expr if (declaration.kind === 193 /* BinaryExpression */ || declaration.kind === 178 /* PropertyAccessExpression */ && declaration.parent.kind === 193 /* BinaryExpression */) { - // Use JS Doc type if present on parent expression statement - if (declaration.flags & 65536 /* JavaScriptFile */) { - var jsdocType = ts.getJSDocType(declaration.parent); - if (jsdocType) { - return links.type = getTypeFromTypeNode(jsdocType); - } - } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 193 /* BinaryExpression */ ? - checkExpressionCached(decl.right) : - checkExpressionCached(decl.parent.right); }); - type = getUnionType(declaredTypes, /*subtypeReduction*/ true); + type = getWidenedType(getUnionType(ts.map(symbol.declarations, getTypeForJSSpecialPropertyDeclaration), /*subtypeReduction*/ true)); } else { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); @@ -27862,7 +27921,7 @@ var ts; var getter = ts.getDeclarationOfKind(symbol, 152 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 153 /* SetAccessor */); if (getter && getter.flags & 65536 /* JavaScriptFile */) { - var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; } @@ -27929,7 +27988,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } } } @@ -27984,7 +28043,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (symbol.flags & 16777216 /* Instantiated */) { + if (getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -28745,7 +28804,7 @@ var ts; s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); - s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); + s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); } // Clear resolved return type we possibly got from cloneSignature s.resolvedReturnType = undefined; @@ -28934,10 +28993,10 @@ var ts; if (t.flags & 32 /* StringLiteral */) { var propName = t.text; var modifiersProp = getPropertyOfType(modifiersType, propName); - var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912 /* Optional */); - var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | (isOptional ? 536870912 /* Optional */ : 0), propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864 /* Optional */); + var prop = createSymbol(4 /* Property */ | (isOptional ? 67108864 /* Optional */ : 0), propName); + prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 4 /* Readonly */ : 0; prop.type = propType; - prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); if (propertySymbol) { prop.mappedTypeOrigin = propertySymbol; } @@ -29151,19 +29210,20 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var types = containingType.types; - var excludeModifiers = containingType.flags & 65536 /* Union */ ? 8 /* Private */ | 16 /* Protected */ : 0; var props; + var types = containingType.types; + var isUnion = containingType.flags & 65536 /* Union */; + var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols - var commonFlags = (containingType.flags & 131072 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; - var isReadonly = false; - var isPartial = false; + var commonFlags = isUnion ? 0 /* None */ : 67108864 /* Optional */; + var checkFlags = 2 /* SyntheticProperty */; for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & excludeModifiers)) { + var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { props = [prop]; @@ -29171,25 +29231,26 @@ var ts; else if (!ts.contains(props, prop)) { props.push(prop); } - if (isReadonlySymbol(prop)) { - isReadonly = true; - } + checkFlags |= (isReadonlySymbol(prop) ? 4 /* Readonly */ : 0) | + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 32 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 64 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 128 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 256 /* ContainsStatic */ : 0); } - else if (containingType.flags & 65536 /* Union */) { - isPartial = true; + else if (isUnion) { + checkFlags |= 8 /* Partial */; } } } if (!props) { return undefined; } - if (props.length === 1 && !isPartial) { + if (props.length === 1 && !(checkFlags & 8 /* Partial */)) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -29200,17 +29261,15 @@ var ts; commonType = type; } else if (type !== commonType) { - hasNonUniformType = true; + checkFlags |= 16 /* HasNonUniformType */; } propTypes.push(type); } - var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */ | commonFlags, name); + var result = createSymbol(4 /* Property */ | commonFlags, name); + result.checkFlags = checkFlags; result.containingType = containingType; - result.hasNonUniformType = hasNonUniformType; - result.isPartial = isPartial; result.declarations = declarations; - result.isReadonly = isReadonly; - result.type = containingType.flags & 65536 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } // Return the symbol for a given property in a union or intersection type, or undefined if the property @@ -29232,7 +29291,7 @@ var ts; function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); // We need to filter out partial properties in union types - return property && !(property.flags & 268435456 /* SyntheticProperty */ && property.isPartial) ? property : undefined; + return property && !(getCheckFlags(property) & 8 /* Partial */) ? property : undefined; } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when @@ -29380,6 +29439,12 @@ var ts; ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + } return false; } function createTypePredicateFromTypePredicateNode(node) { @@ -29409,6 +29474,7 @@ var ts; var hasThisParameter = void 0; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); // If this is a JSDoc construct signature, then skip the first parameter in the // parameter list. The first parameter represents the return type of the construct // signature. @@ -29433,7 +29499,8 @@ var ts; // Record a new minimum argument count if this is not an optional parameter var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param); + isJSDocOptionalParameter(param) || + isUntypedSignatureInJSFile; if (!isOptionalParameter_1) { minArgumentCount = parameters.length; } @@ -29956,7 +30023,7 @@ var ts; for (var i = 0; i < arity; i++) { var typeParameter = createType(16384 /* TypeParameter */); typeParameters.push(typeParameter); - var property = createSymbol(4 /* Property */ | 67108864 /* Transient */, "" + i); + var property = createSymbol(4 /* Property */, "" + i); property.type = typeParameter; properties.push(property); } @@ -30181,7 +30248,10 @@ var ts; if (type.flags & 65536 /* Union */ && typeSet.unionIndex === undefined) { typeSet.unionIndex = typeSet.length; } - typeSet.push(type); + if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + typeSet.push(type); + } } } // Add the given types to the given type set. Order is preserved, duplicates are removed, @@ -30499,15 +30569,15 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 536870912 /* Optional */) { + if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 67108864 /* Optional */) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); - var flags = 4 /* Property */ | 67108864 /* Transient */ | (leftProp.flags & 536870912 /* Optional */); + var flags = 4 /* Property */ | (leftProp.flags & 67108864 /* Optional */); var result = createSymbol(flags, leftProp.name); + result.checkFlags = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp) ? 4 /* Readonly */ : 0; result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; - result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp); members.set(leftProp.name, result); } } @@ -30803,7 +30873,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (symbol.flags & 16777216 /* Instantiated */) { + if (getCheckFlags(symbol) & 1 /* Instantiated */) { var 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 @@ -30813,7 +30883,8 @@ var ts; } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - var result = createSymbol(16777216 /* Instantiated */ | 67108864 /* Transient */ | symbol.flags, symbol.name); + var result = createSymbol(symbol.flags, symbol.name); + result.checkFlags = 1 /* Instantiated */; result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -31726,20 +31797,42 @@ var ts; if (target.flags & 65536 /* Union */ && containsType(targetTypes, source)) { return -1 /* True */; } - var len = targetTypes.length; - for (var i = 0; i < len; i++) { - var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, /*reportErrors*/ false); if (related) { return related; } } + if (reportErrors) { + var discriminantType = findMatchingDiscriminantType(source, target); + isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); + } return 0 /* False */; } + function findMatchingDiscriminantType(source, target) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProperty = sourceProperties_1[_i]; + if (isDiscriminantProperty(target, sourceProperty.name)) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _a = 0, _b = target.types; _a < _b.length; _a++) { + var type = _b[_a]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.name); + if (targetType && isRelatedTo(sourceType, targetType)) { + return type; + } + } + } + } + } + } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; var targetTypes = target.types; - for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { - var targetType = targetTypes_1[_i]; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; var related = isRelatedTo(source, targetType, reportErrors); if (!related) { return 0 /* False */; @@ -31923,17 +32016,23 @@ var ts; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { - if (!(targetProp.flags & 536870912 /* Optional */) || requireOptionalProperties) { + if (!(targetProp.flags & 67108864 /* Optional */) || requireOptionalProperties) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); } return 0 /* False */; } } - else if (!(targetProp.flags & 134217728 /* Prototype */)) { + else if (!(targetProp.flags & 16777216 /* Prototype */)) { var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { + if (getCheckFlags(sourceProp) & 128 /* ContainsPrivate */) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); + } + return 0 /* False */; + } if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { @@ -31947,12 +32046,9 @@ var ts; } } else if (targetPropFlags & 16 /* Protected */) { - var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32 /* Class */; - var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined; - var targetClass = getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp)); - if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { + if (!isValidOverrideOf(sourceProp, targetProp)) { if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass)); + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); } return 0 /* False */; } @@ -31972,7 +32068,7 @@ var ts; } result &= related; // When checking for comparability, be more lenient with optional properties. - if (relation !== comparableRelation && sourceProp.flags & 536870912 /* Optional */ && !(targetProp.flags & 536870912 /* Optional */)) { + if (relation !== comparableRelation && sourceProp.flags & 67108864 /* Optional */ && !(targetProp.flags & 67108864 /* Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -32000,8 +32096,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProp = sourceProperties_1[_i]; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProp = sourceProperties_2[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return 0 /* False */; @@ -32174,6 +32270,45 @@ var ts; return false; } } + // Invoke the callback for each underlying property symbol of the given symbol and return the first + // value that isn't undefined. + function forEachProperty(prop, callback) { + if (getCheckFlags(prop) & 2 /* SyntheticProperty */) { + for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var p = getPropertyOfType(t, prop.name); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + // Return the declaring class type of a property or undefined if property not declared in class + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + // Return true if some underlying source property is declared in a class that derives + // from the given base class. + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + // Return true if source property is a valid override of protected parts of target property. + function isValidOverrideOf(sourceProp, targetProp) { + return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? + !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); + } + // Return true if the given class derives from each of the declaring classes of the protected + // constituents of the given property. + function isClassDerivedFromDeclaringClasses(checkClass, prop) { + return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { if (getObjectFlags(type) & 16 /* Anonymous */) { @@ -32229,7 +32364,7 @@ var ts; } } else { - if ((sourceProp.flags & 536870912 /* Optional */) !== (targetProp.flags & 536870912 /* Optional */)) { + if ((sourceProp.flags & 67108864 /* Optional */) !== (targetProp.flags & 67108864 /* Optional */)) { return 0 /* False */; } } @@ -32462,7 +32597,7 @@ var ts; types.push(undefinedType); if (flags & 4096 /* Null */) types.push(nullType); - return getUnionType(types, /*subtypeReduction*/ true); + return getUnionType(types); } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? @@ -32481,8 +32616,8 @@ var ts; getSignaturesOfType(type, 0 /* Call */).length === 0 && getSignaturesOfType(type, 1 /* Construct */).length === 0; } - function createTransientSymbol(source, type) { - var symbol = createSymbol(source.flags | 67108864 /* Transient */, source.name); + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.name); symbol.declarations = source.declarations; symbol.parent = source.parent; symbol.type = type; @@ -32498,7 +32633,7 @@ var ts; var property = _a[_i]; var original = getTypeOfSymbol(property); var updated = f(original); - members.set(property.name, updated === original ? property : createTransientSymbol(property, updated)); + members.set(property.name, updated === original ? property : createSymbolWithType(property, updated)); } ; return members; @@ -32711,7 +32846,7 @@ var ts; var typeInferencesArray = [typeInferences]; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 536870912 /* Optional */; + var optionalMask = target.declaration.questionToken ? 0 : 67108864 /* Optional */; var members = createSymbolTable(properties); for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; @@ -32719,10 +32854,10 @@ var ts; if (!inferredPropType) { return undefined; } - var inferredProp = createSymbol(4 /* Property */ | 67108864 /* Transient */ | prop.flags & optionalMask, prop.name); + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.name); + inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 4 /* Readonly */ : 0; inferredProp.declarations = prop.declarations; inferredProp.type = inferredPropType; - inferredProp.isReadonly = readonlyMask && isReadonlySymbol(prop); members.set(prop.name, inferredProp); } if (indexInfo) { @@ -32860,8 +32995,8 @@ var ts; var typeVariableCount = 0; var typeVariable = void 0; // First infer to each type in union or intersection that isn't a type variable - for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { - var t = targetTypes_2[_d]; + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; if (t.flags & 540672 /* TypeVariable */ && ts.contains(typeVariables, t)) { typeVariable = t; typeVariableCount++; @@ -33182,9 +33317,9 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && prop.flags & 268435456 /* SyntheticProperty */) { + if (prop && getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.checkFlags & 16 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -33337,10 +33472,16 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - return node.parent.kind === 176 /* ArrayLiteralExpression */ || node.parent.kind === 259 /* PropertyAssignment */ ? + var isDestructuringDefaultAssignment = node.parent.kind === 176 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 259 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 193 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 215 /* ForOfStatement */ && parent.parent.initializer === parent; + } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); } @@ -33645,7 +33786,19 @@ var ts; } } var type = void 0; - if (flow.flags & 16 /* Assignment */) { + if (flow.flags & 4096 /* AfterFinally */) { + // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flow.flags & 2048 /* PreFinally */) { + // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel + // so here just redirect to antecedent + flow = flow.antecedent; + continue; + } + else if (flow.flags & 16 /* Assignment */) { type = getTypeAtFlowAssignment(flow); if (!type) { flow = flow.antecedent; @@ -33798,6 +33951,12 @@ var ts; var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; + if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) { + // if flow correspond to branch from pre-try to finally and this branch is locked - this means that + // we initially have started following the flow outside the finally block. + // in this case we should ignore this branch. + continue; + } var flowType = getTypeAtFlowNode(antecedent); var type = getTypeFromFlowType(flowType); // If the type at a particular antecedent path is the declared type and the @@ -34540,12 +34699,14 @@ var ts; case 151 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; case 148 /* PropertyDeclaration */: case 147 /* PropertySignature */: if (ts.getModifierFlags(container) & 32 /* Static */) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; case 143 /* ComputedPropertyName */: @@ -35434,14 +35595,14 @@ var ts; type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; - var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | member.flags, member.name); + var prop = createSymbol(4 /* Property */ | 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. var isOptional = (memberDecl.kind === 259 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || (memberDecl.kind === 260 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { - prop.flags |= 536870912 /* Optional */; + prop.flags |= 67108864 /* Optional */; } if (ts.hasDynamicName(memberDecl)) { patternWithComputedProperties = true; @@ -35452,7 +35613,7 @@ var ts; // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { - prop.flags |= impliedProp.flags & 536870912 /* Optional */; + prop.flags |= impliedProp.flags & 67108864 /* Optional */; } else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); @@ -35516,7 +35677,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { var prop = _a[_i]; if (!propertiesTable.get(prop.name)) { - if (!(prop.flags & 536870912 /* Optional */)) { + if (!(prop.flags & 67108864 /* Optional */)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } propertiesTable.set(prop.name, prop); @@ -35978,7 +36139,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var _i = 0, targetProperties_1 = targetProperties; _i < targetProperties_1.length; _i++) { var targetProperty = targetProperties_1[_i]; - if (!(targetProperty.flags & 536870912 /* Optional */) && !nameTable.get(targetProperty.name)) { + if (!(targetProperty.flags & 67108864 /* Optional */) && !nameTable.get(targetProperty.name)) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperty.name, typeToString(targetAttributesType)); } } @@ -36002,7 +36163,22 @@ var ts; return s.valueDeclaration ? s.valueDeclaration.kind : 148 /* PropertyDeclaration */; } function getDeclarationModifierFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 4 /* Public */ | 32 /* Static */ : 0; + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 2 /* SyntheticProperty */) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 128 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 32 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 256 /* ContainsStatic */ ? 32 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; + } + return 0; } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; @@ -36015,12 +36191,16 @@ var ts; * @param type The type of left. * @param prop The symbol for the right hand side of the property access. */ - function checkClassPropertyAccess(node, left, type, prop) { + function checkPropertyAccessibility(node, left, type, prop) { var flags = getDeclarationModifierFlagsFromSymbol(prop); - var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); var errorNode = node.kind === 178 /* PropertyAccessExpression */ || node.kind === 225 /* VariableDeclaration */ ? node.name : node.right; + if (getCheckFlags(prop) & 128 /* ContainsPrivate */) { + // Synthetic property with private constituent property + error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); + return false; + } if (left.kind === 96 /* SuperKeyword */) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or @@ -36043,7 +36223,7 @@ var ts; // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an // additional error elsewhere. - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } } @@ -36056,7 +36236,7 @@ var ts; if (flags & 8 /* Private */) { var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } return true; @@ -36066,14 +36246,15 @@ var ts; if (left.kind === 96 /* SuperKeyword */) { return true; } - // Get the enclosing class that has the declaring class as its base type + // Find the first enclosing class that has the declaring classes of the protected constituents + // of the property as base classes var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return hasBaseType(enclosingClass, declaringClass) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); return false; } // No further restrictions for static properties @@ -36085,7 +36266,6 @@ var ts; // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter(type); } - // TODO: why is the first part of this check here? if (!(getObjectFlags(getTargetType(type)) & 3 /* ClassOrInterface */ && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; @@ -36132,7 +36312,7 @@ var ts; noUnusedIdentifiers && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { - if (prop.flags & 16777216 /* Instantiated */) { + if (getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } else { @@ -36177,9 +36357,7 @@ var ts; } markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; - if (prop.parent && prop.parent.flags & 32 /* Class */) { - checkClassPropertyAccess(node, left, apparentType, prop); - } + checkPropertyAccessibility(node, left, apparentType, prop); var propType = getTypeOfSymbol(prop); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -36206,8 +36384,8 @@ var ts; var type = checkExpression(left); if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(getWidenedType(type), propertyName); - if (prop && prop.parent && prop.parent.flags & 32 /* Class */) { - return checkClassPropertyAccess(node, left, type, prop); + if (prop) { + return checkPropertyAccessibility(node, left, type, prop); } } return true; @@ -36772,6 +36950,8 @@ var ts; // For a constructor parameter decorator, the `propertyKey` will be `undefined`. return anyType; } + // For a non-constructor parameter decorator, the `propertyKey` will be either + // a string or a symbol, based on the name of the parameter's containing method. } if (node.kind === 148 /* PropertyDeclaration */ || node.kind === 150 /* MethodDeclaration */ || @@ -37532,7 +37712,7 @@ var ts; var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { if (!parameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + signature.thisParameter = createSymbolWithType(context.thisParameter, undefined); } assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } @@ -37934,11 +38114,11 @@ var ts; // Get accessors without matching set accessors // Enum members // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) - return symbol.isReadonly || - symbol.flags & 4 /* Property */ && (getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */) !== 0 || - symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 || + return !!(getCheckFlags(symbol) & 4 /* Readonly */ || + symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || - (symbol.flags & 8 /* EnumMember */) !== 0; + symbol.flags & 8 /* EnumMember */); } function isReferenceToReadonlyEntity(expr, symbol) { if (isReadonlySymbol(symbol)) { @@ -40588,6 +40768,7 @@ var ts; } current = current.parent; } + // fall through to report error } error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); } @@ -40628,8 +40809,8 @@ var ts; var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); markPropertyAsReferenced(property); - if (parent.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent, parent.initializer, parentType, property); + if (parent.initializer && property) { + checkPropertyAccessibility(parent, parent.initializer, parentType, property); } } // For a binding pattern, check contained binding elements @@ -41520,7 +41701,7 @@ var ts; function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags - return s.flags & 16777216 /* Instantiated */ ? getSymbolLinks(s).target : s; + return getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -41544,7 +41725,7 @@ var ts; 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 */) { + if (base.flags & 16777216 /* Prototype */) { continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); @@ -42034,7 +42215,7 @@ var ts; // We can detect if augmentation was applied using following rules: // - augmentation for a global scope is always applied // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). - var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Merged */); + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 134217728 /* Transient */); if (checkBody && node.body) { // body of ambient external module is always a module block for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { @@ -42114,7 +42295,7 @@ var ts; // this is done it two steps // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error // 2. main check - report error if value declaration of the parent symbol is module augmentation) - var reportError = !(symbol.flags & 33554432 /* Merged */); + var reportError = !(symbol.flags & 134217728 /* Transient */); if (!reportError) { // symbol should not originate in augmentation reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); @@ -43100,7 +43281,7 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (symbol.flags & 268435456 /* SyntheticProperty */) { + if (getCheckFlags(symbol) & 2 /* SyntheticProperty */) { var symbols_3 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { @@ -43111,7 +43292,7 @@ var ts; }); return symbols_3; } - else if (symbol.flags & 67108864 /* Transient */) { + else if (symbol.flags & 134217728 /* Transient */) { if (symbol.leftSpread) { var links = symbol; return [links.leftSpread, links.rightSpread]; @@ -43371,6 +43552,12 @@ var ts; } return false; } + function isRequiredInitializedParameter(parameter) { + return strictNullChecks && + !isOptionalParameter(parameter) && + parameter.initializer && + !(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); + } function getNodeCheckFlags(node) { node = ts.getParseTreeNode(node); return node ? getNodeLinks(node).flags : undefined; @@ -43455,6 +43642,9 @@ var ts; var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; + if (flags & 4096 /* AddUndefined */) { + type = includeFalsyTypes(type, 2048 /* Undefined */); + } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { @@ -43541,6 +43731,7 @@ var ts; isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, @@ -43778,7 +43969,7 @@ var ts; } function createThenableType() { // build the thenable type that is used to verify against a non-promise "thenable" operand to `await`. - var thenPropertySymbol = createSymbol(67108864 /* Transient */ | 4 /* Property */, "then"); + var thenPropertySymbol = createSymbol(4 /* Property */, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; var thenableType = createObjectType(16 /* Anonymous */); thenableType.properties = [thenPropertySymbol]; @@ -44627,6 +44818,10 @@ var ts; } } } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { + checkESModuleMarker(node.name); + } var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); // 1. LexicalDeclaration : LetOrConst BindingList ; // It is a Syntax Error if the BoundNames of BindingList contains "let". @@ -44636,6 +44831,22 @@ var ts; // and its Identifier is eval or arguments return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } + function checkESModuleMarker(name) { + if (name.kind === 70 /* Identifier */) { + if (ts.unescapeIdentifier(name.text) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 70 /* Identifier */) { if (name.originalKeywordKind === 109 /* LetKeyword */) { @@ -44644,8 +44855,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -44815,6 +45026,9 @@ var ts; } } else { + // We must be parented by a statement. If so, there's no need + // to report the error as our parent will have already done it. + // Debug.assert(isStatement(node.parent)); } } } @@ -49010,8 +49224,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 261 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -55693,6 +55907,9 @@ var ts; startLexicalEnvironment(); var statements = []; var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (!currentModuleInfo.exportEquals) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, /*optional*/ true)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); ts.addRange(statements, endLexicalEnvironment()); @@ -55882,6 +56099,9 @@ var ts; startLexicalEnvironment(); var statements = []; var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (!currentModuleInfo.exportEquals) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } // Visit each statement of the module body. ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, /*optional*/ true)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); @@ -56432,27 +56652,27 @@ var ts; * @param allowComments Whether to allow comments on the export. */ function appendExportStatement(statements, exportName, expression, location, allowComments) { - if (exportName.text === "default") { - var sourceFile = ts.getOriginalNode(currentSourceFile, ts.isSourceFile); - if (sourceFile && !sourceFile.symbol.exports.get("___esModule")) { - if (languageVersion === 0 /* ES3 */) { - statements = ts.append(statements, ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createTrue()))); - } - else { - statements = ts.append(statements, ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), - /*typeArguments*/ undefined, [ - ts.createIdentifier("exports"), - ts.createLiteral("__esModule"), - ts.createObjectLiteral([ - ts.createPropertyAssignment("value", ts.createTrue()) - ]) - ]))); - } - } - } statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); return statements; } + function createUnderscoreUnderscoreESModule() { + var statement; + if (languageVersion === 0 /* ES3 */) { + statement = ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(true))); + } + else { + statement = ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ])); + } + ts.setEmitFlags(statement, 524288 /* CustomPrologue */); + return statement; + } /** * Creates a call to the current file's export function to export a value. * @@ -58868,6 +59088,7 @@ var ts; emitNodeWithComments: emitNodeWithComments, emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, + emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition, }; function emitNodeWithComments(hint, node, emitCallback) { if (disabled) { @@ -59019,6 +59240,12 @@ var ts; writer.write(" "); } } + function emitLeadingCommentsOfPosition(pos) { + if (disabled || pos === -1) { + return; + } + emitLeadingComments(pos, /*isEmittedNode*/ true); + } function emitTrailingComments(pos) { forEachTrailingCommentToEmit(pos, emitTrailingComment); } @@ -59406,13 +59633,19 @@ var ts; function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); - if (type) { + // use the checker's type, not the declared type, + // for non-optional initialized parameters that aren't a parameter property + var shouldUseResolverType = declaration.kind === 145 /* Parameter */ && + resolver.isRequiredInitializedParameter(declaration); + if (type && !shouldUseResolverType) { // Write the type emitType(type); } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + var format = 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */ | + (shouldUseResolverType ? 4096 /* AddUndefined */ : 0); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } } @@ -60976,7 +61209,7 @@ var ts; var newLine = ts.getNewLineCharacter(printerOptions); var languageVersion = ts.getEmitScriptTarget(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); - var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; + var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; var currentSourceFile; var nodeIdToGeneratedName; // Map of generated names for specific nodes. var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. @@ -61969,6 +62202,10 @@ var ts; else { writeToken(16 /* OpenBraceToken */, node.pos, /*contextNode*/ node); emitBlockStatements(node); + // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted + increaseIndent(); + emitLeadingCommentsOfPosition(node.statements.end); + decreaseIndent(); writeToken(17 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); } } @@ -62722,6 +62959,15 @@ var ts; var child = children[start + i]; // Write the delimiter if this is not the first node. if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , + if (delimiter && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } write(delimiter); // Write either a line terminator or whitespace to separate the elements. if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { @@ -62760,6 +63006,15 @@ var ts; if (format & 16 /* CommaDelimited */ && hasTrailingComma) { write(","); } + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && delimiter && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } // Decrease the indent, if requested. if (format & 64 /* Indented */) { decreaseIndent(); @@ -66131,7 +66386,7 @@ var ts; */ function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); - var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); @@ -66151,7 +66406,7 @@ var ts; */ function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); - var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); for (var i = nextExtensionPriority; i < extensions.length; i++) { var lowerPriorityExtension = extensions[i]; var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); @@ -71065,7 +71320,7 @@ var ts; } // if this symbol is visible from its parent container, e.g. exported, then bail out // if symbol correspond to the union property - bail out - if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { + if (symbol.parent || (symbol.flags & 134217728 /* Transient */ && symbol.checkFlags & 2 /* SyntheticProperty */)) { return undefined; } var scope; @@ -71246,7 +71501,7 @@ var ts; if (relatedSymbol) { addReferenceToRelatedSymbol(referenceLocation, relatedSymbol); } - else if (!(referenceSymbol.flags & 67108864 /* Transient */) && ts.contains(searchSymbols, shorthandValueSymbol)) { + else if (!(referenceSymbol.flags & 134217728 /* Transient */) && ts.contains(searchSymbols, shorthandValueSymbol)) { addReferenceToRelatedSymbol(referenceSymbolDeclaration.name, shorthandValueSymbol); } else if (searchLocation.kind === 122 /* ConstructorKeyword */) { @@ -73670,6 +73925,7 @@ var ts; break; } } + // fall through. } // Block was a standalone block. In this case we want to only collapse // the span of the block, independent of any parent span. @@ -75125,6 +75381,7 @@ var ts; if (argumentInfo) { return argumentInfo; } + // TODO: Handle generic call with incomplete syntax } return undefined; } @@ -75314,7 +75571,7 @@ var ts; if (flags & 16384 /* Constructor */) return ts.ScriptElementKind.constructorImplementationElement; if (flags & 4 /* Property */) { - if (flags & 268435456 /* SyntheticProperty */) { + if (flags & 134217728 /* Transient */ && symbol.checkFlags & 2 /* SyntheticProperty */) { // If union property is result of union of non method (property/accessors/variables), it is labeled as property var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { var rootSymbolFlags = rootSymbol.getFlags(); @@ -79144,7 +79401,7 @@ var ts; else { return removeSingleItem(namedImports.elements, token); } - // handle case where "import d, * as ns from './file'" + // handle case where "import d, * as ns from './file'" // or "'import {a, b as ns} from './file'" case 238 /* ImportClause */: var importClause = token.parent; @@ -80818,6 +81075,7 @@ var ts; ts.Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + path); return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } + // We didn't already have the file. Fall through and acquire it from the registry. } // Could not find this file in the old program, create a new SourceFile for it. return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index bf0de9939ff..6a8ffedc46a 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -1448,9 +1448,21 @@ declare namespace ts { ArrayMutation = 256, Referenced = 512, Shared = 1024, + PreFinally = 2048, + AfterFinally = 4096, Label = 12, Condition = 96, } + interface FlowLock { + locked?: boolean; + } + interface AfterFinallyFlow extends FlowNode, FlowLock { + antecedent: FlowNode; + } + interface PreFinallyFlow extends FlowNode { + antecedent: FlowNode; + lock: FlowLock; + } interface FlowNode { flags: FlowFlags; id?: number; @@ -1697,6 +1709,7 @@ declare namespace ts { InTypeAlias = 512, UseTypeAliasValue = 1024, SuppressAnyReturnType = 2048, + AddUndefined = 4096, } enum SymbolFormatFlags { None = 0, @@ -1746,13 +1759,10 @@ declare namespace ts { ExportType = 2097152, ExportNamespace = 4194304, Alias = 8388608, - Instantiated = 16777216, - Merged = 33554432, - Transient = 67108864, - Prototype = 134217728, - SyntheticProperty = 268435456, - Optional = 536870912, - ExportStar = 1073741824, + Prototype = 16777216, + ExportStar = 33554432, + Optional = 67108864, + Transient = 134217728, Enum = 384, Variable = 3, Value = 107455, @@ -1943,9 +1953,8 @@ declare namespace ts { isReadonly: boolean; declaration?: SignatureDeclaration; } - interface FileExtensionInfo { + interface JsFileExtensionInfo { extension: string; - scriptKind: ScriptKind; isMixedContent: boolean; } interface DiagnosticMessage { @@ -2918,7 +2927,7 @@ declare namespace ts { * @param basePath A root directory to resolve relative path entries in the config * file to. e.g. outDir */ - function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: FileExtensionInfo[]): ParsedCommandLine; + function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: JsFileExtensionInfo[]): ParsedCommandLine; function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index d3284aaaa51..c6df692fb3a 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -483,6 +483,8 @@ var ts; FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation"; FlowFlags[FlowFlags["Referenced"] = 512] = "Referenced"; FlowFlags[FlowFlags["Shared"] = 1024] = "Shared"; + FlowFlags[FlowFlags["PreFinally"] = 2048] = "PreFinally"; + FlowFlags[FlowFlags["AfterFinally"] = 4096] = "AfterFinally"; FlowFlags[FlowFlags["Label"] = 12] = "Label"; FlowFlags[FlowFlags["Condition"] = 96] = "Condition"; })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {})); @@ -519,6 +521,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 2048] = "SuppressAnyReturnType"; + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 4096] = "AddUndefined"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { @@ -600,13 +603,10 @@ var ts; SymbolFlags[SymbolFlags["ExportType"] = 2097152] = "ExportType"; SymbolFlags[SymbolFlags["ExportNamespace"] = 4194304] = "ExportNamespace"; SymbolFlags[SymbolFlags["Alias"] = 8388608] = "Alias"; - SymbolFlags[SymbolFlags["Instantiated"] = 16777216] = "Instantiated"; - SymbolFlags[SymbolFlags["Merged"] = 33554432] = "Merged"; - SymbolFlags[SymbolFlags["Transient"] = 67108864] = "Transient"; - SymbolFlags[SymbolFlags["Prototype"] = 134217728] = "Prototype"; - SymbolFlags[SymbolFlags["SyntheticProperty"] = 268435456] = "SyntheticProperty"; - SymbolFlags[SymbolFlags["Optional"] = 536870912] = "Optional"; - SymbolFlags[SymbolFlags["ExportStar"] = 1073741824] = "ExportStar"; + SymbolFlags[SymbolFlags["Prototype"] = 16777216] = "Prototype"; + SymbolFlags[SymbolFlags["ExportStar"] = 33554432] = "ExportStar"; + SymbolFlags[SymbolFlags["Optional"] = 67108864] = "Optional"; + SymbolFlags[SymbolFlags["Transient"] = 134217728] = "Transient"; SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum"; SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable"; SymbolFlags[SymbolFlags["Value"] = 107455] = "Value"; @@ -650,6 +650,19 @@ var ts; SymbolFlags[SymbolFlags["Classifiable"] = 788448] = "Classifiable"; })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {})); /* @internal */ + var CheckFlags; + (function (CheckFlags) { + CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated"; + CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty"; + CheckFlags[CheckFlags["Readonly"] = 4] = "Readonly"; + CheckFlags[CheckFlags["Partial"] = 8] = "Partial"; + CheckFlags[CheckFlags["HasNonUniformType"] = 16] = "HasNonUniformType"; + CheckFlags[CheckFlags["ContainsPublic"] = 32] = "ContainsPublic"; + CheckFlags[CheckFlags["ContainsProtected"] = 64] = "ContainsProtected"; + CheckFlags[CheckFlags["ContainsPrivate"] = 128] = "ContainsPrivate"; + CheckFlags[CheckFlags["ContainsStatic"] = 256] = "ContainsStatic"; + })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {})); + /* @internal */ var NodeCheckFlags; (function (NodeCheckFlags) { NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked"; @@ -3083,13 +3096,13 @@ var ts; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0) { + if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + var extensions = allSupportedExtensions.slice(0); for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { var extInfo = extraFileExtensions_1[_i]; - if (needAllExtensions || extInfo.scriptKind === 3 /* TS */) { + if (extensions.indexOf(extInfo.extension) === -1) { extensions.push(extInfo.extension); } } @@ -3126,14 +3139,13 @@ var ts; (function (ExtensionPriority) { ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles"; ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles"; - ExtensionPriority[ExtensionPriority["Limit"] = 5] = "Limit"; ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest"; ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest"; })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {})); function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { - return adjustExtensionPriority(i); + return adjustExtensionPriority(i, supportedExtensions); } } // If its not in the list of supported extensions, this is likely a @@ -3144,27 +3156,27 @@ var ts; /** * Adjusts an extension priority to be the highest priority within the same range. */ - function adjustExtensionPriority(extensionPriority) { + function adjustExtensionPriority(extensionPriority, supportedExtensions) { if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { return 0 /* TypeScriptFiles */; } - else if (extensionPriority < 5 /* Limit */) { + else if (extensionPriority < supportedExtensions.length) { return 2 /* DeclarationAndJavaScriptFiles */; } else { - return 5 /* Limit */; + return supportedExtensions.length; } } ts.adjustExtensionPriority = adjustExtensionPriority; /** * Gets the next lowest extension priority for a given priority. */ - function getNextLowestExtensionPriority(extensionPriority) { + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) { return 2 /* DeclarationAndJavaScriptFiles */; } else { - return 5 /* Limit */; + return supportedExtensions.length; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; @@ -3770,7 +3782,7 @@ var ts; // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) var options; if (!directoryExists(directoryName) || (isUNCPath(directoryName) && process.platform === "win32")) { - // do nothing if either + // do nothing if either // - target folder does not exist // - this is UNC path on Windows (https://github.com/Microsoft/TypeScript/issues/13874) return noOpFileWatcher; @@ -3856,6 +3868,7 @@ var ts; require("source-map-support").install(); } catch (e) { + // Could not enable source maps. } }, setTimeout: setTimeout, @@ -4112,6 +4125,7 @@ var ts; Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", message: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", message: "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", message: "Generators are only available when targeting ECMAScript 2015 or higher." }, @@ -4391,6 +4405,7 @@ var ts; Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: { code: 2543, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", message: "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference." }, Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: { code: 2544, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", message: "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference." }, A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: { code: 2545, category: ts.DiagnosticCategory.Error, key: "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", message: "A mixin class must have a constructor with a single rest parameter of type 'any[]'." }, + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: { code: 2546, category: ts.DiagnosticCategory.Error, key: "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", message: "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -4644,7 +4659,7 @@ var ts; File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, Loading_module_0_from_node_modules_folder_target_file_type_1: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", message: "Loading module '{0}' from 'node_modules' folder, target file type '{1}'." }, Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_a_types_or_main_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_types_or_main_field_6100", message: "'package.json' does not have a 'types' or 'main' field." }, + package_json_does_not_have_a_0_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_0_field_6100", message: "'package.json' does not have a '{0}' field." }, package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, @@ -4681,7 +4696,6 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, - No_types_specified_in_package_json_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json', so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -7952,6 +7966,11 @@ var ts; return ts.map(getJSDocs(node), function (doc) { return doc.comment; }); } ts.getCommentsFromJSDoc = getCommentsFromJSDoc; + function hasJSDocParameterTags(node) { + var parameterTags = getJSDocTags(node, 284 /* JSDocParameterTag */); + return parameterTags && parameterTags.length > 0; + } + ts.hasJSDocParameterTags = hasJSDocParameterTags; function getJSDocTags(node, kind) { var docs = getJSDocs(node); if (docs) { @@ -21653,7 +21672,32 @@ var ts; if (node.finallyBlock) { // in finally flow is combined from pre-try/flow from try/flow from catch // pre-flow is necessary to make sure that finally is reachable even if finally flows in both try and finally blocks are unreachable - addAntecedent(preFinallyLabel, preTryFlow); + // also for finally blocks we inject two extra edges into the flow graph. + // first -> edge that connects pre-try flow with the label at the beginning of the finally block, it has lock associated with it + // second -> edge that represents post-finally flow. + // these edges are used in following scenario: + // let a; (1) + // try { a = someOperation(); (2)} + // finally { (3) console.log(a) } (4) + // (5) a + // flow graph for this case looks roughly like this (arrows show ): + // (1-pre-try-flow) <--.. <-- (2-post-try-flow) + // ^ ^ + // |*****(3-pre-finally-label) -----| + // ^ + // |-- ... <-- (4-post-finally-label) <--- (5) + // In case when we walk the flow starting from inside the finally block we want to take edge '*****' into account + // since it ensures that finally is always reachable. However when we start outside the finally block and go through label (5) + // then edge '*****' should be discarded because label 4 is only reachable if post-finally label-4 is reachable + // Simply speaking code inside finally block is treated as reachable as pre-try-flow + // since we conservatively assume that any line in try block can throw or return in which case we'll enter finally. + // However code after finally is reachable only if control flow was not abrupted in try/catch or finally blocks - it should be composed from + // final flows of these blocks without taking pre-try flow into account. + // + // extra edges that we inject allows to control this behavior + // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. + var preFinallyFlow = { flags: 2048 /* PreFinally */, antecedent: preTryFlow, lock: {} }; + addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); // if flow after finally is unreachable - keep it @@ -21669,6 +21713,11 @@ var ts; : unreachableFlow; } } + if (!(currentFlow.flags & 1 /* Unreachable */)) { + var afterFinallyFlow = { flags: 4096 /* AfterFinally */, antecedent: currentFlow }; + preFinallyFlow.lock = afterFinallyFlow; + currentFlow = afterFinallyFlow; + } } else { currentFlow = finishFlowLabel(preFinallyLabel); @@ -22483,7 +22532,7 @@ var ts; case 148 /* PropertyDeclaration */: case 147 /* PropertySignature */: case 274 /* JSDocRecordMember */: - return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); case 289 /* JSDocPropertyTag */: return bindJSDocProperty(node); case 259 /* PropertyAssignment */: @@ -22516,7 +22565,7 @@ var ts; // as other properties in the object literal. So we use SymbolFlags.PropertyExcludes // so that it will conflict with any other object literal members with the same // name. - return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); + return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 99263 /* MethodExcludes */); case 227 /* FunctionDeclaration */: return bindFunctionDeclaration(node); case 151 /* Constructor */: @@ -22648,11 +22697,11 @@ var ts; function bindExportDeclaration(node) { if (!container.symbol || !container.symbol.exports) { // Export * in some sort of block construct - bindAnonymousDeclaration(node, 1073741824 /* ExportStar */, getDeclarationName(node)); + bindAnonymousDeclaration(node, 33554432 /* ExportStar */, getDeclarationName(node)); } else if (!node.exportClause) { // All export * declarations are collected in an __export symbol - declareSymbol(container.symbol.exports, container.symbol, node, 1073741824 /* ExportStar */, 0 /* None */); + declareSymbol(container.symbol.exports, container.symbol, node, 33554432 /* ExportStar */, 0 /* None */); } } function bindImportClause(node) { @@ -22751,7 +22800,7 @@ var 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. - var prototypeSymbol = createSymbol(4 /* Property */ | 134217728 /* Prototype */, "prototype"); + var prototypeSymbol = createSymbol(4 /* Property */ | 16777216 /* Prototype */, "prototype"); var symbolExport = symbol.exports.get(prototypeSymbol.name); if (symbolExport) { if (node.name) { @@ -22808,7 +22857,7 @@ var ts; // containing class. if (ts.isParameterPropertyDeclaration(node)) { var classDeclaration = node.parent.parent; - declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); + declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 67108864 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */); } } function bindFunctionDeclaration(node) { @@ -23728,37 +23777,28 @@ var ts; } ts.moduleHasNonRelativeName = moduleHasNonRelativeName; /** Reads from "main" or "types"/"typings" depending on `extensions`. */ - function tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, baseDirectory, state) { + function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { var jsonContent = readJson(packageJsonPath, state.host); - switch (extensions) { - case Extensions.DtsOnly: - case Extensions.TypeScript: - return tryReadFromField("typings") || tryReadFromField("types"); - case Extensions.JavaScript: - if (typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main); - } - return ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - } - return undefined; - } + return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); - } - return typesFilePath; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } + return; } + var fileName = jsonContent[fieldName]; + if (typeof fileName !== "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + } + return; + } + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; } } function readJson(path, host) { @@ -23794,6 +23834,7 @@ var ts; function getDefaultTypeRoots(currentDirectory, host) { if (!host.directoryExists) { return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + // And if it doesn't exist, tough. } var typeRoots; forEachAncestorDirectory(currentDirectory, function (directory) { @@ -24270,7 +24311,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state); + var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); } @@ -24284,7 +24326,7 @@ var ts; } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true); return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); } } @@ -24300,7 +24342,7 @@ var ts; } return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } @@ -24328,7 +24370,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } /* @internal */ function directoryProbablyExists(directoryName, host) { @@ -24397,47 +24439,51 @@ var ts; failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var mainOrTypesFile = tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, candidate, state); - if (mainOrTypesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(mainOrTypesFile), state.host); - // A package.json "typings" may specify an exact filename, or may choose to omit an extension. - var fromExactFile = tryFile(mainOrTypesFile, failedLookupLocations, onlyRecordFailures_1, state); - if (fromExactFile) { - var resolved_3 = fromExactFile && resolvedIfExtensionMatches(extensions, fromExactFile); - if (resolved_3) { - return resolved_3; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromExactFile); - } - } - var resolved = tryAddingExtensions(mainOrTypesFile, Extensions.TypeScript, failedLookupLocations, onlyRecordFailures_1, state); - if (resolved) { - return resolved; + if (considerPackageJson) { + var packageJsonPath = pathToPackageJson(candidate); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; } } else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_types_or_main_field); + if (directoryExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + failedLookupLocations.push(packageJsonPath); } } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocations.push(packageJsonPath); - } return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); } + function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + if (!file) { + return undefined; + } + var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); + var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); + if (fromFile) { + var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return resolved; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types" + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + // Don't do package.json lookup recursively, because Node.js' package lookup doesn't. + return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, /*considerPackageJson*/ false); + } /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */ function resolvedIfExtensionMatches(extensions, path) { var extension = ts.tryGetExtensionFromPath(path); @@ -24529,7 +24575,7 @@ var ts; var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (moduleHasNonRelativeName(moduleName)) { // Climb up parent directories looking for a module. - var resolved_4 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { return resolutionFromCache; @@ -24537,8 +24583,8 @@ var ts; var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, /*onlyRecordFailures*/ false, state)); }); - if (resolved_4) { - return resolved_4; + if (resolved_3) { + return resolved_3; } if (extensions === Extensions.TypeScript) { // If we didn't find the file normally, look it up in @types. @@ -24643,9 +24689,9 @@ var ts; var allowSyntheticDefaultImports = typeof compilerOptions.allowSyntheticDefaultImports !== "undefined" ? compilerOptions.allowSyntheticDefaultImports : modulekind === ts.ModuleKind.System; var strictNullChecks = compilerOptions.strictNullChecks; var emitResolver = createResolver(); - var undefinedSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "undefined"); + var undefinedSymbol = createSymbol(4 /* Property */, "undefined"); undefinedSymbol.declarations = []; - var argumentsSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "arguments"); + var argumentsSymbol = createSymbol(4 /* Property */, "arguments"); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, @@ -24711,8 +24757,8 @@ var ts; var numericLiteralTypes = ts.createMap(); var indexedAccessTypes = ts.createMap(); var evolvingArrayTypes = []; - var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown"); - var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__"); + var unknownSymbol = createSymbol(4 /* Property */, "unknown"); + var resolvingSymbol = createSymbol(0, "__resolving__"); var anyType = createIntrinsicType(1 /* Any */, "any"); var autoType = createIntrinsicType(1 /* Any */, "any"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); @@ -24731,7 +24777,7 @@ var ts; var silentNeverType = createIntrinsicType(8192 /* Never */, "never"); var nonPrimitiveType = createIntrinsicType(16777216 /* NonPrimitive */, "object"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */ | 67108864 /* Transient */, "__type"); + var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type"); emptyTypeLiteralSymbol.members = ts.createMap(); var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, emptyArray, emptyArray, undefined, undefined); var emptyGenericType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -24961,7 +25007,9 @@ var ts; } function createSymbol(flags, name) { symbolCount++; - return new Symbol(flags, name); + var symbol = (new Symbol(flags | 134217728 /* Transient */, name)); + symbol.checkFlags = 0; + return symbol; } function getExcludedSymbolFlags(flags) { var result = 0; @@ -25007,7 +25055,7 @@ var ts; mergedSymbols[source.mergeId] = target; } function cloneSymbol(symbol) { - var result = createSymbol(symbol.flags | 33554432 /* Merged */, symbol.name); + var result = createSymbol(symbol.flags, symbol.name); result.declarations = symbol.declarations.slice(0); result.parent = symbol.parent; if (symbol.valueDeclaration) @@ -25068,7 +25116,7 @@ var ts; target.set(id, sourceSymbol); } else { - if (!(targetSymbol.flags & 33554432 /* Merged */)) { + if (!(targetSymbol.flags & 134217728 /* Transient */)) { targetSymbol = cloneSymbol(targetSymbol); target.set(id, targetSymbol); } @@ -25103,7 +25151,7 @@ var ts; if (mainModule.flags & 1920 /* Namespace */) { // if module symbol has already been merged - it is safe to use it. // otherwise clone it - mainModule = mainModule.flags & 33554432 /* Merged */ ? mainModule : cloneSymbol(mainModule); + mainModule = mainModule.flags & 134217728 /* Transient */ ? mainModule : cloneSymbol(mainModule); mergeSymbol(mainModule, moduleAugmentation.symbol); } else { @@ -25127,7 +25175,7 @@ var ts; } } function getSymbolLinks(symbol) { - if (symbol.flags & 67108864 /* Transient */) + if (symbol.flags & 134217728 /* Transient */) return symbol; var id = getSymbolId(symbol); return symbolLinks[id] || (symbolLinks[id] = {}); @@ -25139,6 +25187,9 @@ var ts; function getObjectFlags(type) { return type.flags & 32768 /* Object */ ? type.objectFlags : 0; } + function getCheckFlags(symbol) { + return symbol.flags & 134217728 /* Transient */ ? symbol.checkFlags : 0; + } function isGlobalSourceFile(node) { return node.kind === 263 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node); } @@ -25146,7 +25197,7 @@ var ts; if (meaning) { var symbol = symbols.get(name); if (symbol) { - ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); if (symbol.flags & meaning) { return symbol; } @@ -25904,7 +25955,7 @@ var ts; else { ts.Debug.fail("Unknown entity name kind."); } - ts.Debug.assert((symbol.flags & 16777216 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); + ts.Debug.assert((getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here."); return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol); } function resolveExternalModuleName(location, moduleReferenceExpression) { @@ -26108,20 +26159,7 @@ var ts; : symbol; } function symbolIsValue(symbol) { - // If it is an instantiated symbol, then it is a value if the symbol it is an - // instantiation of is a value. - if (symbol.flags & 16777216 /* Instantiated */) { - return symbolIsValue(getSymbolLinks(symbol).target); - } - // If the symbol has the value flag, it is trivially a value. - if (symbol.flags & 107455 /* Value */) { - return true; - } - // If it is an alias, then it is a value if the symbol it resolves to is a value. - if (symbol.flags & 8388608 /* Alias */) { - return (resolveAlias(symbol).flags & 107455 /* Value */) !== 0; - } - return false; + return !!(symbol.flags & 107455 /* Value */ || symbol.flags & 8388608 /* Alias */ && resolveAlias(symbol).flags & 107455 /* Value */); } function findConstructorDeclaration(node) { var members = node.members; @@ -26617,7 +26655,7 @@ var ts; if (parentSymbol) { // Write type arguments of instantiated class/interface here if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (symbol.flags & 16777216 /* Instantiated */) { + if (getCheckFlags(symbol) & 1 /* Instantiated */) { buildDisplayForTypeArgumentsAndDelimiters(getTypeParametersOfClassOrInterface(parentSymbol), symbol.mapper, writer, enclosingDeclaration); } else { @@ -26891,7 +26929,7 @@ var ts; writeSpace(writer); } buildSymbolDisplay(prop, writer); - if (prop.flags & 536870912 /* Optional */) { + if (prop.flags & 67108864 /* Optional */) { writePunctuation(writer, 54 /* QuestionToken */); } } @@ -27052,7 +27090,11 @@ var ts; } writePunctuation(writer, 55 /* ColonToken */); writeSpace(writer); - buildTypeDisplay(getTypeOfSymbol(p), writer, enclosingDeclaration, flags, symbolStack); + var type = getTypeOfSymbol(p); + if (isRequiredInitializedParameter(parameterNode)) { + type = includeFalsyTypes(type, 2048 /* Undefined */); + } + buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); } function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. @@ -27563,7 +27605,7 @@ var ts; getUnionType([type, checkExpressionCached(declaration.initializer)], /*subtypeReduction*/ true) : type; } - function getTypeForVariableLikeDeclarationFromJSDocComment(declaration) { + function getTypeForDeclarationFromJSDocComment(declaration) { var jsdocType = ts.getJSDocType(declaration); if (jsdocType) { return getTypeFromTypeNode(jsdocType); @@ -27581,13 +27623,22 @@ var ts; function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } + /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */ + function removeOptionalityFromAnnotation(annotatedType, declaration) { + var annotationIncludesUndefined = strictNullChecks && + declaration.kind === 145 /* Parameter */ && + declaration.initializer && + getFalsyFlags(annotatedType) & 2048 /* Undefined */ && + !(getFalsyFlags(checkExpression(declaration.initializer)) & 2048 /* Undefined */); + return annotationIncludesUndefined ? getNonNullableType(annotatedType) : annotatedType; + } // Return the inferred type for a variable, parameter, or property declaration function getTypeForVariableLikeDeclaration(declaration, includeOptionality) { if (declaration.flags & 65536 /* JavaScriptFile */) { // If this is a variable in a JavaScript file, then use the JSDoc type (if it has // one as its type), otherwise fallback to the below standard TS codepaths to // try to figure it out. - var type = getTypeForVariableLikeDeclarationFromJSDocComment(declaration); + var type = getTypeForDeclarationFromJSDocComment(declaration); if (type && type !== unknownType) { return type; } @@ -27610,7 +27661,8 @@ var ts; } // Use type from type annotation if one is present if (declaration.type) { - return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality); + var declaredType = removeOptionalityFromAnnotation(getTypeFromTypeNode(declaration.type), declaration); + return addOptionality(declaredType, /*optional*/ declaration.questionToken && includeOptionality); } if ((compilerOptions.noImplicitAny || declaration.flags & 65536 /* JavaScriptFile */) && declaration.kind === 225 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && @@ -27671,6 +27723,23 @@ var ts; // No type specified and nothing can be inferred return undefined; } + // Return the inferred type for a variable, parameter, or property declaration + function getTypeForJSSpecialPropertyDeclaration(declaration) { + var expression = declaration.kind === 193 /* BinaryExpression */ ? declaration : + declaration.kind === 178 /* PropertyAccessExpression */ ? ts.getAncestor(declaration, 193 /* BinaryExpression */) : + undefined; + if (!expression) { + return unknownType; + } + if (expression.flags & 65536 /* JavaScriptFile */) { + // If there is a JSDoc type, use it + var type = getTypeForDeclarationFromJSDocComment(expression.parent); + if (type && type !== unknownType) { + return getWidenedType(type); + } + } + return getWidenedLiteralType(checkExpressionCached(expression.right)); + } // Return the type implied by a binding pattern element. This is the type of the initializer of the element if // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding // pattern. Otherwise, it is the type any. @@ -27703,7 +27772,7 @@ var ts; return; } var text = ts.getTextOfPropertyName(name); - var flags = 4 /* Property */ | 67108864 /* Transient */ | (e.initializer ? 536870912 /* Optional */ : 0); + var flags = 4 /* Property */ | (e.initializer ? 67108864 /* Optional */ : 0); var symbol = createSymbol(flags, text); symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors); symbol.bindingElement = e; @@ -27788,7 +27857,7 @@ var ts; var links = getSymbolLinks(symbol); if (!links.type) { // Handle prototype property - if (symbol.flags & 134217728 /* Prototype */) { + if (symbol.flags & 16777216 /* Prototype */) { return links.type = getTypeOfPrototypeProperty(symbol); } // Handle catch clause variables @@ -27815,17 +27884,7 @@ var ts; // * className.prototype.method = expr if (declaration.kind === 193 /* BinaryExpression */ || declaration.kind === 178 /* PropertyAccessExpression */ && declaration.parent.kind === 193 /* BinaryExpression */) { - // Use JS Doc type if present on parent expression statement - if (declaration.flags & 65536 /* JavaScriptFile */) { - var jsdocType = ts.getJSDocType(declaration.parent); - if (jsdocType) { - return links.type = getTypeFromTypeNode(jsdocType); - } - } - var declaredTypes = ts.map(symbol.declarations, function (decl) { return decl.kind === 193 /* BinaryExpression */ ? - checkExpressionCached(decl.right) : - checkExpressionCached(decl.parent.right); }); - type = getUnionType(declaredTypes, /*subtypeReduction*/ true); + type = getWidenedType(getUnionType(ts.map(symbol.declarations, getTypeForJSSpecialPropertyDeclaration), /*subtypeReduction*/ true)); } else { type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); @@ -27862,7 +27921,7 @@ var ts; var getter = ts.getDeclarationOfKind(symbol, 152 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 153 /* SetAccessor */); if (getter && getter.flags & 65536 /* JavaScriptFile */) { - var jsDocType = getTypeForVariableLikeDeclarationFromJSDocComment(getter); + var jsDocType = getTypeForDeclarationFromJSDocComment(getter); if (jsDocType) { return links.type = jsDocType; } @@ -27929,7 +27988,7 @@ var ts; links.type = baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type; } else { - links.type = strictNullChecks && symbol.flags & 536870912 /* Optional */ ? includeFalsyTypes(type, 2048 /* Undefined */) : type; + links.type = strictNullChecks && symbol.flags & 67108864 /* Optional */ ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } } } @@ -27984,7 +28043,7 @@ var ts; return anyType; } function getTypeOfSymbol(symbol) { - if (symbol.flags & 16777216 /* Instantiated */) { + if (getCheckFlags(symbol) & 1 /* Instantiated */) { return getTypeOfInstantiatedSymbol(symbol); } if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) { @@ -28745,7 +28804,7 @@ var ts; s = cloneSignature(signature); if (ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; })) { var thisType = getUnionType(ts.map(unionSignatures, function (sig) { return getTypeOfSymbol(sig.thisParameter) || anyType; }), /*subtypeReduction*/ true); - s.thisParameter = createTransientSymbol(signature.thisParameter, thisType); + s.thisParameter = createSymbolWithType(signature.thisParameter, thisType); } // Clear resolved return type we possibly got from cloneSignature s.resolvedReturnType = undefined; @@ -28934,10 +28993,10 @@ var ts; if (t.flags & 32 /* StringLiteral */) { var propName = t.text; var modifiersProp = getPropertyOfType(modifiersType, propName); - var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 536870912 /* Optional */); - var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | (isOptional ? 536870912 /* Optional */ : 0), propName); + var isOptional = templateOptional || !!(modifiersProp && modifiersProp.flags & 67108864 /* Optional */); + var prop = createSymbol(4 /* Property */ | (isOptional ? 67108864 /* Optional */ : 0), propName); + prop.checkFlags = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp) ? 4 /* Readonly */ : 0; prop.type = propType; - prop.isReadonly = templateReadonly || modifiersProp && isReadonlySymbol(modifiersProp); if (propertySymbol) { prop.mappedTypeOrigin = propertySymbol; } @@ -29151,19 +29210,20 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var types = containingType.types; - var excludeModifiers = containingType.flags & 65536 /* Union */ ? 8 /* Private */ | 16 /* Protected */ : 0; var props; + var types = containingType.types; + var isUnion = containingType.flags & 65536 /* Union */; + var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; // Flags we want to propagate to the result if they exist in all source symbols - var commonFlags = (containingType.flags & 131072 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; - var isReadonly = false; - var isPartial = false; + var commonFlags = isUnion ? 0 /* None */ : 67108864 /* Optional */; + var checkFlags = 2 /* SyntheticProperty */; for (var _i = 0, types_3 = types; _i < types_3.length; _i++) { var current = types_3[_i]; var type = getApparentType(current); if (type !== unknownType) { var prop = getPropertyOfType(type, name); - if (prop && !(getDeclarationModifierFlagsFromSymbol(prop) & excludeModifiers)) { + var modifiers = prop ? getDeclarationModifierFlagsFromSymbol(prop) : 0; + if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; if (!props) { props = [prop]; @@ -29171,25 +29231,26 @@ var ts; else if (!ts.contains(props, prop)) { props.push(prop); } - if (isReadonlySymbol(prop)) { - isReadonly = true; - } + checkFlags |= (isReadonlySymbol(prop) ? 4 /* Readonly */ : 0) | + (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 32 /* ContainsPublic */ : 0) | + (modifiers & 16 /* Protected */ ? 64 /* ContainsProtected */ : 0) | + (modifiers & 8 /* Private */ ? 128 /* ContainsPrivate */ : 0) | + (modifiers & 32 /* Static */ ? 256 /* ContainsStatic */ : 0); } - else if (containingType.flags & 65536 /* Union */) { - isPartial = true; + else if (isUnion) { + checkFlags |= 8 /* Partial */; } } } if (!props) { return undefined; } - if (props.length === 1 && !isPartial) { + if (props.length === 1 && !(checkFlags & 8 /* Partial */)) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -29200,17 +29261,15 @@ var ts; commonType = type; } else if (type !== commonType) { - hasNonUniformType = true; + checkFlags |= 16 /* HasNonUniformType */; } propTypes.push(type); } - var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */ | commonFlags, name); + var result = createSymbol(4 /* Property */ | commonFlags, name); + result.checkFlags = checkFlags; result.containingType = containingType; - result.hasNonUniformType = hasNonUniformType; - result.isPartial = isPartial; result.declarations = declarations; - result.isReadonly = isReadonly; - result.type = containingType.flags & 65536 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); + result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } // Return the symbol for a given property in a union or intersection type, or undefined if the property @@ -29232,7 +29291,7 @@ var ts; function getPropertyOfUnionOrIntersectionType(type, name) { var property = getUnionOrIntersectionProperty(type, name); // We need to filter out partial properties in union types - return property && !(property.flags & 268435456 /* SyntheticProperty */ && property.isPartial) ? property : undefined; + return property && !(getCheckFlags(property) & 8 /* Partial */) ? property : undefined; } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when @@ -29380,6 +29439,12 @@ var ts; ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } + var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent); + if (iife) { + return !node.type && + !node.dotDotDotToken && + ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + } return false; } function createTypePredicateFromTypePredicateNode(node) { @@ -29409,6 +29474,7 @@ var ts; var hasThisParameter = void 0; var iife = ts.getImmediatelyInvokedFunctionExpression(declaration); var isJSConstructSignature = ts.isJSDocConstructSignature(declaration); + var isUntypedSignatureInJSFile = !iife && !isJSConstructSignature && ts.isInJavaScriptFile(declaration) && !ts.hasJSDocParameterTags(declaration); // If this is a JSDoc construct signature, then skip the first parameter in the // parameter list. The first parameter represents the return type of the construct // signature. @@ -29433,7 +29499,8 @@ var ts; // Record a new minimum argument count if this is not an optional parameter var isOptionalParameter_1 = param.initializer || param.questionToken || param.dotDotDotToken || iife && parameters.length > iife.arguments.length && !param.type || - isJSDocOptionalParameter(param); + isJSDocOptionalParameter(param) || + isUntypedSignatureInJSFile; if (!isOptionalParameter_1) { minArgumentCount = parameters.length; } @@ -29956,7 +30023,7 @@ var ts; for (var i = 0; i < arity; i++) { var typeParameter = createType(16384 /* TypeParameter */); typeParameters.push(typeParameter); - var property = createSymbol(4 /* Property */ | 67108864 /* Transient */, "" + i); + var property = createSymbol(4 /* Property */, "" + i); property.type = typeParameter; properties.push(property); } @@ -30181,7 +30248,10 @@ var ts; if (type.flags & 65536 /* Union */ && typeSet.unionIndex === undefined) { typeSet.unionIndex = typeSet.length; } - typeSet.push(type); + if (!(type.flags & 32768 /* Object */ && type.objectFlags & 16 /* Anonymous */ && + type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */) && containsIdenticalType(typeSet, type))) { + typeSet.push(type); + } } } // Add the given types to the given type set. Order is preserved, duplicates are removed, @@ -30499,15 +30569,15 @@ var ts; if (members.has(leftProp.name)) { var rightProp = members.get(leftProp.name); var rightType = getTypeOfSymbol(rightProp); - if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 536870912 /* Optional */) { + if (maybeTypeOfKind(rightType, 2048 /* Undefined */) || rightProp.flags & 67108864 /* Optional */) { var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations); - var flags = 4 /* Property */ | 67108864 /* Transient */ | (leftProp.flags & 536870912 /* Optional */); + var flags = 4 /* Property */ | (leftProp.flags & 67108864 /* Optional */); var result = createSymbol(flags, leftProp.name); + result.checkFlags = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp) ? 4 /* Readonly */ : 0; result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 131072 /* NEUndefined */)]); result.leftSpread = leftProp; result.rightSpread = rightProp; result.declarations = declarations; - result.isReadonly = isReadonlySymbol(leftProp) || isReadonlySymbol(rightProp); members.set(leftProp.name, result); } } @@ -30803,7 +30873,7 @@ var ts; return result; } function instantiateSymbol(symbol, mapper) { - if (symbol.flags & 16777216 /* Instantiated */) { + if (getCheckFlags(symbol) & 1 /* Instantiated */) { var 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 @@ -30813,7 +30883,8 @@ var ts; } // Keep the flags from the symbol we're instantiating. Mark that is instantiated, and // also transient so that we can just store data on it directly. - var result = createSymbol(16777216 /* Instantiated */ | 67108864 /* Transient */ | symbol.flags, symbol.name); + var result = createSymbol(symbol.flags, symbol.name); + result.checkFlags = 1 /* Instantiated */; result.declarations = symbol.declarations; result.parent = symbol.parent; result.target = symbol; @@ -31726,20 +31797,42 @@ var ts; if (target.flags & 65536 /* Union */ && containsType(targetTypes, source)) { return -1 /* True */; } - var len = targetTypes.length; - for (var i = 0; i < len; i++) { - var related = isRelatedTo(source, targetTypes[i], reportErrors && i === len - 1); + for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { + var type = targetTypes_1[_i]; + var related = isRelatedTo(source, type, /*reportErrors*/ false); if (related) { return related; } } + if (reportErrors) { + var discriminantType = findMatchingDiscriminantType(source, target); + isRelatedTo(source, discriminantType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true); + } return 0 /* False */; } + function findMatchingDiscriminantType(source, target) { + var sourceProperties = getPropertiesOfObjectType(source); + if (sourceProperties) { + for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { + var sourceProperty = sourceProperties_1[_i]; + if (isDiscriminantProperty(target, sourceProperty.name)) { + var sourceType = getTypeOfSymbol(sourceProperty); + for (var _a = 0, _b = target.types; _a < _b.length; _a++) { + var type = _b[_a]; + var targetType = getTypeOfPropertyOfType(type, sourceProperty.name); + if (targetType && isRelatedTo(sourceType, targetType)) { + return type; + } + } + } + } + } + } function typeRelatedToEachType(source, target, reportErrors) { var result = -1 /* True */; var targetTypes = target.types; - for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) { - var targetType = targetTypes_1[_i]; + for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) { + var targetType = targetTypes_2[_i]; var related = isRelatedTo(source, targetType, reportErrors); if (!related) { return 0 /* False */; @@ -31923,17 +32016,23 @@ var ts; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { - if (!(targetProp.flags & 536870912 /* Optional */) || requireOptionalProperties) { + if (!(targetProp.flags & 67108864 /* Optional */) || requireOptionalProperties) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); } return 0 /* False */; } } - else if (!(targetProp.flags & 134217728 /* Prototype */)) { + else if (!(targetProp.flags & 16777216 /* Prototype */)) { var sourcePropFlags = getDeclarationModifierFlagsFromSymbol(sourceProp); var targetPropFlags = getDeclarationModifierFlagsFromSymbol(targetProp); if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) { + if (getCheckFlags(sourceProp) & 128 /* ContainsPrivate */) { + if (reportErrors) { + reportError(ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(sourceProp), typeToString(source)); + } + return 0 /* False */; + } if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) { if (reportErrors) { if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) { @@ -31947,12 +32046,9 @@ var ts; } } else if (targetPropFlags & 16 /* Protected */) { - var sourceDeclaredInClass = sourceProp.parent && sourceProp.parent.flags & 32 /* Class */; - var sourceClass = sourceDeclaredInClass ? getDeclaredTypeOfSymbol(getParentOfSymbol(sourceProp)) : undefined; - var targetClass = getDeclaredTypeOfSymbol(getParentOfSymbol(targetProp)); - if (!sourceClass || !hasBaseType(sourceClass, targetClass)) { + if (!isValidOverrideOf(sourceProp, targetProp)) { if (reportErrors) { - reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(sourceClass || source), typeToString(targetClass)); + reportError(ts.Diagnostics.Property_0_is_protected_but_type_1_is_not_a_class_derived_from_2, symbolToString(targetProp), typeToString(getDeclaringClass(sourceProp) || source), typeToString(getDeclaringClass(targetProp) || target)); } return 0 /* False */; } @@ -31972,7 +32068,7 @@ var ts; } result &= related; // When checking for comparability, be more lenient with optional properties. - if (relation !== comparableRelation && sourceProp.flags & 536870912 /* Optional */ && !(targetProp.flags & 536870912 /* Optional */)) { + if (relation !== comparableRelation && sourceProp.flags & 67108864 /* Optional */ && !(targetProp.flags & 67108864 /* Optional */)) { // TypeScript 1.0 spec (April 2014): 3.8.3 // S is a subtype of a type T, and T is a supertype of S if ... // S' and T are object types and, for each member M in T.. @@ -32000,8 +32096,8 @@ var ts; return 0 /* False */; } var result = -1 /* True */; - for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) { - var sourceProp = sourceProperties_1[_i]; + for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) { + var sourceProp = sourceProperties_2[_i]; var targetProp = getPropertyOfObjectType(target, sourceProp.name); if (!targetProp) { return 0 /* False */; @@ -32174,6 +32270,45 @@ var ts; return false; } } + // Invoke the callback for each underlying property symbol of the given symbol and return the first + // value that isn't undefined. + function forEachProperty(prop, callback) { + if (getCheckFlags(prop) & 2 /* SyntheticProperty */) { + for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) { + var t = _a[_i]; + var p = getPropertyOfType(t, prop.name); + var result = p && forEachProperty(p, callback); + if (result) { + return result; + } + } + return undefined; + } + return callback(prop); + } + // Return the declaring class type of a property or undefined if property not declared in class + function getDeclaringClass(prop) { + return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined; + } + // Return true if some underlying source property is declared in a class that derives + // from the given base class. + function isPropertyInClassDerivedFrom(prop, baseClass) { + return forEachProperty(prop, function (sp) { + var sourceClass = getDeclaringClass(sp); + return sourceClass ? hasBaseType(sourceClass, baseClass) : false; + }); + } + // Return true if source property is a valid override of protected parts of target property. + function isValidOverrideOf(sourceProp, targetProp) { + return !forEachProperty(targetProp, function (tp) { return getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ? + !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; }); + } + // Return true if the given class derives from each of the declaring classes of the protected + // constituents of the given property. + function isClassDerivedFromDeclaringClasses(checkClass, prop) { + return forEachProperty(prop, function (p) { return getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ? + !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass; + } // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { if (getObjectFlags(type) & 16 /* Anonymous */) { @@ -32229,7 +32364,7 @@ var ts; } } else { - if ((sourceProp.flags & 536870912 /* Optional */) !== (targetProp.flags & 536870912 /* Optional */)) { + if ((sourceProp.flags & 67108864 /* Optional */) !== (targetProp.flags & 67108864 /* Optional */)) { return 0 /* False */; } } @@ -32462,7 +32597,7 @@ var ts; types.push(undefinedType); if (flags & 4096 /* Null */) types.push(nullType); - return getUnionType(types, /*subtypeReduction*/ true); + return getUnionType(types); } function removeDefinitelyFalsyTypes(type) { return getFalsyFlags(type) & 7392 /* DefinitelyFalsy */ ? @@ -32481,8 +32616,8 @@ var ts; getSignaturesOfType(type, 0 /* Call */).length === 0 && getSignaturesOfType(type, 1 /* Construct */).length === 0; } - function createTransientSymbol(source, type) { - var symbol = createSymbol(source.flags | 67108864 /* Transient */, source.name); + function createSymbolWithType(source, type) { + var symbol = createSymbol(source.flags, source.name); symbol.declarations = source.declarations; symbol.parent = source.parent; symbol.type = type; @@ -32498,7 +32633,7 @@ var ts; var property = _a[_i]; var original = getTypeOfSymbol(property); var updated = f(original); - members.set(property.name, updated === original ? property : createTransientSymbol(property, updated)); + members.set(property.name, updated === original ? property : createSymbolWithType(property, updated)); } ; return members; @@ -32711,7 +32846,7 @@ var ts; var typeInferencesArray = [typeInferences]; var templateType = getTemplateTypeFromMappedType(target); var readonlyMask = target.declaration.readonlyToken ? false : true; - var optionalMask = target.declaration.questionToken ? 0 : 536870912 /* Optional */; + var optionalMask = target.declaration.questionToken ? 0 : 67108864 /* Optional */; var members = createSymbolTable(properties); for (var _i = 0, properties_4 = properties; _i < properties_4.length; _i++) { var prop = properties_4[_i]; @@ -32719,10 +32854,10 @@ var ts; if (!inferredPropType) { return undefined; } - var inferredProp = createSymbol(4 /* Property */ | 67108864 /* Transient */ | prop.flags & optionalMask, prop.name); + var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.name); + inferredProp.checkFlags = readonlyMask && isReadonlySymbol(prop) ? 4 /* Readonly */ : 0; inferredProp.declarations = prop.declarations; inferredProp.type = inferredPropType; - inferredProp.isReadonly = readonlyMask && isReadonlySymbol(prop); members.set(prop.name, inferredProp); } if (indexInfo) { @@ -32860,8 +32995,8 @@ var ts; var typeVariableCount = 0; var typeVariable = void 0; // First infer to each type in union or intersection that isn't a type variable - for (var _d = 0, targetTypes_2 = targetTypes; _d < targetTypes_2.length; _d++) { - var t = targetTypes_2[_d]; + for (var _d = 0, targetTypes_3 = targetTypes; _d < targetTypes_3.length; _d++) { + var t = targetTypes_3[_d]; if (t.flags & 540672 /* TypeVariable */ && ts.contains(typeVariables, t)) { typeVariable = t; typeVariableCount++; @@ -33182,9 +33317,9 @@ var ts; function isDiscriminantProperty(type, name) { if (type && type.flags & 65536 /* Union */) { var prop = getUnionOrIntersectionProperty(type, name); - if (prop && prop.flags & 268435456 /* SyntheticProperty */) { + if (prop && getCheckFlags(prop) & 2 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.checkFlags & 16 /* HasNonUniformType */ && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -33337,10 +33472,16 @@ var ts; return createArrayType(checkIteratedTypeOrElementType(type, /*errorNode*/ undefined, /*allowStringInput*/ false) || unknownType); } function getAssignedTypeOfBinaryExpression(node) { - return node.parent.kind === 176 /* ArrayLiteralExpression */ || node.parent.kind === 259 /* PropertyAssignment */ ? + var isDestructuringDefaultAssignment = node.parent.kind === 176 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || + node.parent.kind === 259 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent); + return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right); } + function isDestructuringAssignmentTarget(parent) { + return parent.parent.kind === 193 /* BinaryExpression */ && parent.parent.left === parent || + parent.parent.kind === 215 /* ForOfStatement */ && parent.parent.initializer === parent; + } function getAssignedTypeOfArrayLiteralElement(node, element) { return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); } @@ -33645,7 +33786,19 @@ var ts; } } var type = void 0; - if (flow.flags & 16 /* Assignment */) { + if (flow.flags & 4096 /* AfterFinally */) { + // block flow edge: finally -> pre-try (for larger explanation check comment in binder.ts - bindTryStatement + flow.locked = true; + type = getTypeAtFlowNode(flow.antecedent); + flow.locked = false; + } + else if (flow.flags & 2048 /* PreFinally */) { + // locked pre-finally flows are filtered out in getTypeAtFlowBranchLabel + // so here just redirect to antecedent + flow = flow.antecedent; + continue; + } + else if (flow.flags & 16 /* Assignment */) { type = getTypeAtFlowAssignment(flow); if (!type) { flow = flow.antecedent; @@ -33798,6 +33951,12 @@ var ts; var seenIncomplete = false; for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) { var antecedent = _a[_i]; + if (antecedent.flags & 2048 /* PreFinally */ && antecedent.lock.locked) { + // if flow correspond to branch from pre-try to finally and this branch is locked - this means that + // we initially have started following the flow outside the finally block. + // in this case we should ignore this branch. + continue; + } var flowType = getTypeAtFlowNode(antecedent); var type = getTypeFromFlowType(flowType); // If the type at a particular antecedent path is the declared type and the @@ -34540,12 +34699,14 @@ var ts; case 151 /* Constructor */: if (isInConstructorArgumentInitializer(node, container)) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; case 148 /* PropertyDeclaration */: case 147 /* PropertySignature */: if (ts.getModifierFlags(container) & 32 /* Static */) { error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); + // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks } break; case 143 /* ComputedPropertyName */: @@ -35434,14 +35595,14 @@ var ts; type = checkExpressionForMutableLocation(memberDecl.name, contextualMapper); } typeFlags |= type.flags; - var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | member.flags, member.name); + var prop = createSymbol(4 /* Property */ | 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. var isOptional = (memberDecl.kind === 259 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) || (memberDecl.kind === 260 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer); if (isOptional) { - prop.flags |= 536870912 /* Optional */; + prop.flags |= 67108864 /* Optional */; } if (ts.hasDynamicName(memberDecl)) { patternWithComputedProperties = true; @@ -35452,7 +35613,7 @@ var ts; // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { - prop.flags |= impliedProp.flags & 536870912 /* Optional */; + prop.flags |= impliedProp.flags & 67108864 /* Optional */; } else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) { error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType)); @@ -35516,7 +35677,7 @@ var ts; for (var _i = 0, _a = getPropertiesOfType(contextualType); _i < _a.length; _i++) { var prop = _a[_i]; if (!propertiesTable.get(prop.name)) { - if (!(prop.flags & 536870912 /* Optional */)) { + if (!(prop.flags & 67108864 /* Optional */)) { error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } propertiesTable.set(prop.name, prop); @@ -35978,7 +36139,7 @@ var ts; var targetProperties = getPropertiesOfType(targetAttributesType); for (var _i = 0, targetProperties_1 = targetProperties; _i < targetProperties_1.length; _i++) { var targetProperty = targetProperties_1[_i]; - if (!(targetProperty.flags & 536870912 /* Optional */) && !nameTable.get(targetProperty.name)) { + if (!(targetProperty.flags & 67108864 /* Optional */) && !nameTable.get(targetProperty.name)) { error(node, ts.Diagnostics.Property_0_is_missing_in_type_1, targetProperty.name, typeToString(targetAttributesType)); } } @@ -36002,7 +36163,22 @@ var ts; return s.valueDeclaration ? s.valueDeclaration.kind : 148 /* PropertyDeclaration */; } function getDeclarationModifierFlagsFromSymbol(s) { - return s.valueDeclaration ? ts.getCombinedModifierFlags(s.valueDeclaration) : s.flags & 134217728 /* Prototype */ ? 4 /* Public */ | 32 /* Static */ : 0; + if (s.valueDeclaration) { + var flags = ts.getCombinedModifierFlags(s.valueDeclaration); + return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */; + } + if (getCheckFlags(s) & 2 /* SyntheticProperty */) { + var checkFlags = s.checkFlags; + var accessModifier = checkFlags & 128 /* ContainsPrivate */ ? 8 /* Private */ : + checkFlags & 32 /* ContainsPublic */ ? 4 /* Public */ : + 16 /* Protected */; + var staticModifier = checkFlags & 256 /* ContainsStatic */ ? 32 /* Static */ : 0; + return accessModifier | staticModifier; + } + if (s.flags & 16777216 /* Prototype */) { + return 4 /* Public */ | 32 /* Static */; + } + return 0; } function getDeclarationNodeFlagsFromSymbol(s) { return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0; @@ -36015,12 +36191,16 @@ var ts; * @param type The type of left. * @param prop The symbol for the right hand side of the property access. */ - function checkClassPropertyAccess(node, left, type, prop) { + function checkPropertyAccessibility(node, left, type, prop) { var flags = getDeclarationModifierFlagsFromSymbol(prop); - var declaringClass = getDeclaredTypeOfSymbol(getParentOfSymbol(prop)); var errorNode = node.kind === 178 /* PropertyAccessExpression */ || node.kind === 225 /* VariableDeclaration */ ? node.name : node.right; + if (getCheckFlags(prop) & 128 /* ContainsPrivate */) { + // Synthetic property with private constituent property + error(errorNode, ts.Diagnostics.Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1, symbolToString(prop), typeToString(type)); + return false; + } if (left.kind === 96 /* SuperKeyword */) { // TS 1.0 spec (April 2014): 4.8.2 // - In a constructor, instance member function, instance member accessor, or @@ -36043,7 +36223,7 @@ var ts; // This error could mask a private property access error. But, a member // cannot simultaneously be private and abstract, so this will trigger an // additional error elsewhere. - error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } } @@ -36056,7 +36236,7 @@ var ts; if (flags & 8 /* Private */) { var declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop)); if (!isNodeWithinClass(node, declaringClassDeclaration)) { - error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop))); return false; } return true; @@ -36066,14 +36246,15 @@ var ts; if (left.kind === 96 /* SuperKeyword */) { return true; } - // Get the enclosing class that has the declaring class as its base type + // Find the first enclosing class that has the declaring classes of the protected constituents + // of the property as base classes var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) { var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration)); - return hasBaseType(enclosingClass, declaringClass) ? enclosingClass : undefined; + return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined; }); // A protected property is accessible if the property is within the declaring class or classes derived from it if (!enclosingClass) { - error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(declaringClass)); + error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type)); return false; } // No further restrictions for static properties @@ -36085,7 +36266,6 @@ var ts; // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter(type); } - // TODO: why is the first part of this check here? if (!(getObjectFlags(getTargetType(type)) & 3 /* ClassOrInterface */ && hasBaseType(type, enclosingClass))) { error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass)); return false; @@ -36132,7 +36312,7 @@ var ts; noUnusedIdentifiers && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration && (ts.getModifierFlags(prop.valueDeclaration) & 8 /* Private */)) { - if (prop.flags & 16777216 /* Instantiated */) { + if (getCheckFlags(prop) & 1 /* Instantiated */) { getSymbolLinks(prop).target.isReferenced = true; } else { @@ -36177,9 +36357,7 @@ var ts; } markPropertyAsReferenced(prop); getNodeLinks(node).resolvedSymbol = prop; - if (prop.parent && prop.parent.flags & 32 /* Class */) { - checkClassPropertyAccess(node, left, apparentType, prop); - } + checkPropertyAccessibility(node, left, apparentType, prop); var propType = getTypeOfSymbol(prop); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { @@ -36206,8 +36384,8 @@ var ts; var type = checkExpression(left); if (type !== unknownType && !isTypeAny(type)) { var prop = getPropertyOfType(getWidenedType(type), propertyName); - if (prop && prop.parent && prop.parent.flags & 32 /* Class */) { - return checkClassPropertyAccess(node, left, type, prop); + if (prop) { + return checkPropertyAccessibility(node, left, type, prop); } } return true; @@ -36772,6 +36950,8 @@ var ts; // For a constructor parameter decorator, the `propertyKey` will be `undefined`. return anyType; } + // For a non-constructor parameter decorator, the `propertyKey` will be either + // a string or a symbol, based on the name of the parameter's containing method. } if (node.kind === 148 /* PropertyDeclaration */ || node.kind === 150 /* MethodDeclaration */ || @@ -37532,7 +37712,7 @@ var ts; var parameter = signature.thisParameter; if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) { if (!parameter) { - signature.thisParameter = createTransientSymbol(context.thisParameter, undefined); + signature.thisParameter = createSymbolWithType(context.thisParameter, undefined); } assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter), mapper); } @@ -37934,11 +38114,11 @@ var ts; // Get accessors without matching set accessors // Enum members // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation) - return symbol.isReadonly || - symbol.flags & 4 /* Property */ && (getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */) !== 0 || - symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 || + return !!(getCheckFlags(symbol) & 4 /* Readonly */ || + symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ || + symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || - (symbol.flags & 8 /* EnumMember */) !== 0; + symbol.flags & 8 /* EnumMember */); } function isReferenceToReadonlyEntity(expr, symbol) { if (isReadonlySymbol(symbol)) { @@ -40588,6 +40768,7 @@ var ts; } current = current.parent; } + // fall through to report error } error(n, ts.Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(node.name), ts.declarationNameToString(n)); } @@ -40628,8 +40809,8 @@ var ts; var name = node.propertyName || node.name; var property = getPropertyOfType(parentType, ts.getTextOfPropertyName(name)); markPropertyAsReferenced(property); - if (parent.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent, parent.initializer, parentType, property); + if (parent.initializer && property) { + checkPropertyAccessibility(parent, parent.initializer, parentType, property); } } // For a binding pattern, check contained binding elements @@ -41520,7 +41701,7 @@ var ts; function getTargetSymbol(s) { // if symbol is instantiated its flags are not copied from the 'target' // so we'll need to get back original 'target' symbol to work with correct set of flags - return s.flags & 16777216 /* Instantiated */ ? getSymbolLinks(s).target : s; + return getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s; } function getClassLikeDeclarationOfSymbol(symbol) { return ts.forEach(symbol.declarations, function (d) { return ts.isClassLike(d) ? d : undefined; }); @@ -41544,7 +41725,7 @@ var ts; 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 */) { + if (base.flags & 16777216 /* Prototype */) { continue; } var derived = getTargetSymbol(getPropertyOfObjectType(type, base.name)); @@ -42034,7 +42215,7 @@ var ts; // We can detect if augmentation was applied using following rules: // - augmentation for a global scope is always applied // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module). - var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Merged */); + var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 134217728 /* Transient */); if (checkBody && node.body) { // body of ambient external module is always a module block for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) { @@ -42114,7 +42295,7 @@ var ts; // this is done it two steps // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error // 2. main check - report error if value declaration of the parent symbol is module augmentation) - var reportError = !(symbol.flags & 33554432 /* Merged */); + var reportError = !(symbol.flags & 134217728 /* Transient */); if (!reportError) { // symbol should not originate in augmentation reportError = ts.isExternalModuleAugmentation(symbol.parent.declarations[0]); @@ -43100,7 +43281,7 @@ var ts; return getNamedMembers(propsByName); } function getRootSymbols(symbol) { - if (symbol.flags & 268435456 /* SyntheticProperty */) { + if (getCheckFlags(symbol) & 2 /* SyntheticProperty */) { var symbols_3 = []; var name_2 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { @@ -43111,7 +43292,7 @@ var ts; }); return symbols_3; } - else if (symbol.flags & 67108864 /* Transient */) { + else if (symbol.flags & 134217728 /* Transient */) { if (symbol.leftSpread) { var links = symbol; return [links.leftSpread, links.rightSpread]; @@ -43371,6 +43552,12 @@ var ts; } return false; } + function isRequiredInitializedParameter(parameter) { + return strictNullChecks && + !isOptionalParameter(parameter) && + parameter.initializer && + !(ts.getModifierFlags(parameter) & 92 /* ParameterPropertyModifier */); + } function getNodeCheckFlags(node) { node = ts.getParseTreeNode(node); return node ? getNodeLinks(node).flags : undefined; @@ -43455,6 +43642,9 @@ var ts; var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */)) ? getWidenedLiteralType(getTypeOfSymbol(symbol)) : unknownType; + if (flags & 4096 /* AddUndefined */) { + type = includeFalsyTypes(type, 2048 /* Undefined */); + } getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { @@ -43541,6 +43731,7 @@ var ts; isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName, isDeclarationVisible: isDeclarationVisible, isImplementationOfOverload: isImplementationOfOverload, + isRequiredInitializedParameter: isRequiredInitializedParameter, writeTypeOfDeclaration: writeTypeOfDeclaration, writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration, writeTypeOfExpression: writeTypeOfExpression, @@ -43778,7 +43969,7 @@ var ts; } function createThenableType() { // build the thenable type that is used to verify against a non-promise "thenable" operand to `await`. - var thenPropertySymbol = createSymbol(67108864 /* Transient */ | 4 /* Property */, "then"); + var thenPropertySymbol = createSymbol(4 /* Property */, "then"); getSymbolLinks(thenPropertySymbol).type = globalFunctionType; var thenableType = createObjectType(16 /* Anonymous */); thenableType.properties = [thenPropertySymbol]; @@ -44627,6 +44818,10 @@ var ts; } } } + if (compilerOptions.module !== ts.ModuleKind.ES2015 && compilerOptions.module !== ts.ModuleKind.System && !compilerOptions.noEmit && + !ts.isInAmbientContext(node.parent.parent) && ts.hasModifier(node.parent.parent, 1 /* Export */)) { + checkESModuleMarker(node.name); + } var checkLetConstNames = (ts.isLet(node) || ts.isConst(node)); // 1. LexicalDeclaration : LetOrConst BindingList ; // It is a Syntax Error if the BoundNames of BindingList contains "let". @@ -44636,6 +44831,22 @@ var ts; // and its Identifier is eval or arguments return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name); } + function checkESModuleMarker(name) { + if (name.kind === 70 /* Identifier */) { + if (ts.unescapeIdentifier(name.text) === "__esModule") { + return grammarErrorOnNode(name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules); + } + } + else { + var elements = name.elements; + for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { + var element = elements_2[_i]; + if (!ts.isOmittedExpression(element)) { + return checkESModuleMarker(element.name); + } + } + } + } function checkGrammarNameInLetOrConstDeclarations(name) { if (name.kind === 70 /* Identifier */) { if (name.originalKeywordKind === 109 /* LetKeyword */) { @@ -44644,8 +44855,8 @@ var ts; } else { var elements = name.elements; - for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) { - var element = elements_2[_i]; + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; if (!ts.isOmittedExpression(element)) { checkGrammarNameInLetOrConstDeclarations(element.name); } @@ -44815,6 +45026,9 @@ var ts; } } else { + // We must be parented by a statement. If so, there's no need + // to report the error as our parent will have already done it. + // Debug.assert(isStatement(node.parent)); } } } @@ -49010,8 +49224,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 261 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -55693,6 +55907,9 @@ var ts; startLexicalEnvironment(); var statements = []; var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (!currentModuleInfo.exportEquals) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, /*optional*/ true)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); ts.addRange(statements, endLexicalEnvironment()); @@ -55882,6 +56099,9 @@ var ts; startLexicalEnvironment(); var statements = []; var statementOffset = ts.addPrologueDirectives(statements, node.statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor); + if (!currentModuleInfo.exportEquals) { + ts.append(statements, createUnderscoreUnderscoreESModule()); + } // Visit each statement of the module body. ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement, /*optional*/ true)); ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); @@ -56432,27 +56652,27 @@ var ts; * @param allowComments Whether to allow comments on the export. */ function appendExportStatement(statements, exportName, expression, location, allowComments) { - if (exportName.text === "default") { - var sourceFile = ts.getOriginalNode(currentSourceFile, ts.isSourceFile); - if (sourceFile && !sourceFile.symbol.exports.get("___esModule")) { - if (languageVersion === 0 /* ES3 */) { - statements = ts.append(statements, ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createTrue()))); - } - else { - statements = ts.append(statements, ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), - /*typeArguments*/ undefined, [ - ts.createIdentifier("exports"), - ts.createLiteral("__esModule"), - ts.createObjectLiteral([ - ts.createPropertyAssignment("value", ts.createTrue()) - ]) - ]))); - } - } - } statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments)); return statements; } + function createUnderscoreUnderscoreESModule() { + var statement; + if (languageVersion === 0 /* ES3 */) { + statement = ts.createStatement(createExportExpression(ts.createIdentifier("__esModule"), ts.createLiteral(true))); + } + else { + statement = ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Object"), "defineProperty"), + /*typeArguments*/ undefined, [ + ts.createIdentifier("exports"), + ts.createLiteral("__esModule"), + ts.createObjectLiteral([ + ts.createPropertyAssignment("value", ts.createLiteral(true)) + ]) + ])); + } + ts.setEmitFlags(statement, 524288 /* CustomPrologue */); + return statement; + } /** * Creates a call to the current file's export function to export a value. * @@ -58868,6 +59088,7 @@ var ts; emitNodeWithComments: emitNodeWithComments, emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition, + emitLeadingCommentsOfPosition: emitLeadingCommentsOfPosition, }; function emitNodeWithComments(hint, node, emitCallback) { if (disabled) { @@ -59019,6 +59240,12 @@ var ts; writer.write(" "); } } + function emitLeadingCommentsOfPosition(pos) { + if (disabled || pos === -1) { + return; + } + emitLeadingComments(pos, /*isEmittedNode*/ true); + } function emitTrailingComments(pos) { forEachTrailingCommentToEmit(pos, emitTrailingComment); } @@ -59406,13 +59633,19 @@ var ts; function writeTypeOfDeclaration(declaration, type, getSymbolAccessibilityDiagnostic) { writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; write(": "); - if (type) { + // use the checker's type, not the declared type, + // for non-optional initialized parameters that aren't a parameter property + var shouldUseResolverType = declaration.kind === 145 /* Parameter */ && + resolver.isRequiredInitializedParameter(declaration); + if (type && !shouldUseResolverType) { // Write the type emitType(type); } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + var format = 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */ | + (shouldUseResolverType ? 4096 /* AddUndefined */ : 0); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } } @@ -60976,7 +61209,7 @@ var ts; var newLine = ts.getNewLineCharacter(printerOptions); var languageVersion = ts.getEmitScriptTarget(printerOptions); var comments = ts.createCommentWriter(printerOptions, onEmitSourceMapOfPosition); - var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; + var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition, emitLeadingCommentsOfPosition = comments.emitLeadingCommentsOfPosition; var currentSourceFile; var nodeIdToGeneratedName; // Map of generated names for specific nodes. var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables. @@ -61969,6 +62202,10 @@ var ts; else { writeToken(16 /* OpenBraceToken */, node.pos, /*contextNode*/ node); emitBlockStatements(node); + // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted + increaseIndent(); + emitLeadingCommentsOfPosition(node.statements.end); + decreaseIndent(); writeToken(17 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); } } @@ -62722,6 +62959,15 @@ var ts; var child = children[start + i]; // Write the delimiter if this is not the first node. if (previousSibling) { + // i.e + // function commentedParameters( + // /* Parameter a */ + // a + // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline + // , + if (delimiter && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } write(delimiter); // Write either a line terminator or whitespace to separate the elements. if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { @@ -62760,6 +63006,15 @@ var ts; if (format & 16 /* CommaDelimited */ && hasTrailingComma) { write(","); } + // Emit any trailing comment of the last element in the list + // i.e + // var array = [... + // 2 + // /* end of element 2 */ + // ]; + if (previousSibling && delimiter && previousSibling.end !== parentNode.end) { + emitLeadingCommentsOfPosition(previousSibling.end); + } // Decrease the indent, if requested. if (format & 64 /* Indented */) { decreaseIndent(); @@ -66131,7 +66386,7 @@ var ts; */ function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); - var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); @@ -66151,7 +66406,7 @@ var ts; */ function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); - var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); for (var i = nextExtensionPriority; i < extensions.length; i++) { var lowerPriorityExtension = extensions[i]; var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); @@ -71065,7 +71320,7 @@ var ts; } // if this symbol is visible from its parent container, e.g. exported, then bail out // if symbol correspond to the union property - bail out - if (symbol.parent || (symbol.flags & 268435456 /* SyntheticProperty */)) { + if (symbol.parent || (symbol.flags & 134217728 /* Transient */ && symbol.checkFlags & 2 /* SyntheticProperty */)) { return undefined; } var scope; @@ -71246,7 +71501,7 @@ var ts; if (relatedSymbol) { addReferenceToRelatedSymbol(referenceLocation, relatedSymbol); } - else if (!(referenceSymbol.flags & 67108864 /* Transient */) && ts.contains(searchSymbols, shorthandValueSymbol)) { + else if (!(referenceSymbol.flags & 134217728 /* Transient */) && ts.contains(searchSymbols, shorthandValueSymbol)) { addReferenceToRelatedSymbol(referenceSymbolDeclaration.name, shorthandValueSymbol); } else if (searchLocation.kind === 122 /* ConstructorKeyword */) { @@ -73670,6 +73925,7 @@ var ts; break; } } + // fall through. } // Block was a standalone block. In this case we want to only collapse // the span of the block, independent of any parent span. @@ -75125,6 +75381,7 @@ var ts; if (argumentInfo) { return argumentInfo; } + // TODO: Handle generic call with incomplete syntax } return undefined; } @@ -75314,7 +75571,7 @@ var ts; if (flags & 16384 /* Constructor */) return ts.ScriptElementKind.constructorImplementationElement; if (flags & 4 /* Property */) { - if (flags & 268435456 /* SyntheticProperty */) { + if (flags & 134217728 /* Transient */ && symbol.checkFlags & 2 /* SyntheticProperty */) { // If union property is result of union of non method (property/accessors/variables), it is labeled as property var unionPropertyKind = ts.forEach(typeChecker.getRootSymbols(symbol), function (rootSymbol) { var rootSymbolFlags = rootSymbol.getFlags(); @@ -79144,7 +79401,7 @@ var ts; else { return removeSingleItem(namedImports.elements, token); } - // handle case where "import d, * as ns from './file'" + // handle case where "import d, * as ns from './file'" // or "'import {a, b as ns} from './file'" case 238 /* ImportClause */: var importClause = token.parent; @@ -80818,6 +81075,7 @@ var ts; ts.Debug.assert(hostFileInformation.scriptKind === oldSourceFile.scriptKind, "Registered script kind (" + oldSourceFile.scriptKind + ") should match new script kind (" + hostFileInformation.scriptKind + ") for file: " + path); return documentRegistry.updateDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); } + // We didn't already have the file. Fall through and acquire it from the registry. } // Could not find this file in the old program, create a new SourceFile for it. return documentRegistry.acquireDocumentWithKey(fileName, path, newSettings, documentRegistryBucketKey, hostFileInformation.scriptSnapshot, hostFileInformation.version, hostFileInformation.scriptKind); diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 576c7f6cd72..78fd2fa2a6a 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -1763,13 +1763,13 @@ var ts; var allSupportedExtensions = ts.supportedTypeScriptExtensions.concat(ts.supportedJavascriptExtensions); function getSupportedExtensions(options, extraFileExtensions) { var needAllExtensions = options && options.allowJs; - if (!extraFileExtensions || extraFileExtensions.length === 0) { + if (!extraFileExtensions || extraFileExtensions.length === 0 || !needAllExtensions) { return needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } - var extensions = (needAllExtensions ? allSupportedExtensions : ts.supportedTypeScriptExtensions).slice(0); + var extensions = allSupportedExtensions.slice(0); for (var _i = 0, extraFileExtensions_1 = extraFileExtensions; _i < extraFileExtensions_1.length; _i++) { var extInfo = extraFileExtensions_1[_i]; - if (needAllExtensions || extInfo.scriptKind === 3) { + if (extensions.indexOf(extInfo.extension) === -1) { extensions.push(extInfo.extension); } } @@ -1800,30 +1800,30 @@ var ts; function getExtensionPriority(path, supportedExtensions) { for (var i = supportedExtensions.length - 1; i >= 0; i--) { if (fileExtensionIs(path, supportedExtensions[i])) { - return adjustExtensionPriority(i); + return adjustExtensionPriority(i, supportedExtensions); } } return 0; } ts.getExtensionPriority = getExtensionPriority; - function adjustExtensionPriority(extensionPriority) { + function adjustExtensionPriority(extensionPriority, supportedExtensions) { if (extensionPriority < 2) { return 0; } - else if (extensionPriority < 5) { + else if (extensionPriority < supportedExtensions.length) { return 2; } else { - return 5; + return supportedExtensions.length; } } ts.adjustExtensionPriority = adjustExtensionPriority; - function getNextLowestExtensionPriority(extensionPriority) { + function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) { if (extensionPriority < 2) { return 2; } else { - return 5; + return supportedExtensions.length; } } ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority; @@ -2689,6 +2689,7 @@ var ts; Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode: { code: 1213, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_stric_1213", message: "Identifier expected. '{0}' is a reserved word in strict mode. Class definitions are automatically in strict mode." }, Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode: { code: 1214, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode_1214", message: "Identifier expected. '{0}' is a reserved word in strict mode. Modules are automatically in strict mode." }, Invalid_use_of_0_Modules_are_automatically_in_strict_mode: { code: 1215, category: ts.DiagnosticCategory.Error, key: "Invalid_use_of_0_Modules_are_automatically_in_strict_mode_1215", message: "Invalid use of '{0}'. Modules are automatically in strict mode." }, + Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules: { code: 1216, category: ts.DiagnosticCategory.Error, key: "Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules_1216", message: "Identifier expected. '__esModule' is reserved as an exported marker when transforming ECMAScript modules." }, Export_assignment_is_not_supported_when_module_flag_is_system: { code: 1218, category: ts.DiagnosticCategory.Error, key: "Export_assignment_is_not_supported_when_module_flag_is_system_1218", message: "Export assignment is not supported when '--module' flag is 'system'." }, Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_the_experimentalDecorators_option_to_remove_this_warning: { code: 1219, category: ts.DiagnosticCategory.Error, key: "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219", message: "Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning." }, Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher: { code: 1220, category: ts.DiagnosticCategory.Error, key: "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220", message: "Generators are only available when targeting ECMAScript 2015 or higher." }, @@ -2968,6 +2969,7 @@ var ts; Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference: { code: 2543, category: ts.DiagnosticCategory.Error, key: "Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_me_2543", message: "Duplicate identifier '_newTarget'. Compiler uses variable declaration '_newTarget' to capture 'new.target' meta-property reference." }, Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference: { code: 2544, category: ts.DiagnosticCategory.Error, key: "Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta__2544", message: "Expression resolves to variable declaration '_newTarget' that compiler uses to capture 'new.target' meta-property reference." }, A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any: { code: 2545, category: ts.DiagnosticCategory.Error, key: "A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any_2545", message: "A mixin class must have a constructor with a single rest parameter of type 'any[]'." }, + Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1: { code: 2546, category: ts.DiagnosticCategory.Error, key: "Property_0_has_conflicting_declarations_and_is_inaccessible_in_type_1_2546", message: "Property '{0}' has conflicting declarations and is inaccessible in type '{1}'." }, JSX_element_attributes_type_0_may_not_be_a_union_type: { code: 2600, category: ts.DiagnosticCategory.Error, key: "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", message: "JSX element attributes type '{0}' may not be a union type." }, The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: ts.DiagnosticCategory.Error, key: "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", message: "The return type of a JSX element constructor must return an object type." }, JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: ts.DiagnosticCategory.Error, key: "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", message: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." }, @@ -3221,7 +3223,7 @@ var ts; File_0_exist_use_it_as_a_name_resolution_result: { code: 6097, category: ts.DiagnosticCategory.Message, key: "File_0_exist_use_it_as_a_name_resolution_result_6097", message: "File '{0}' exist - use it as a name resolution result." }, Loading_module_0_from_node_modules_folder_target_file_type_1: { code: 6098, category: ts.DiagnosticCategory.Message, key: "Loading_module_0_from_node_modules_folder_target_file_type_1_6098", message: "Loading module '{0}' from 'node_modules' folder, target file type '{1}'." }, Found_package_json_at_0: { code: 6099, category: ts.DiagnosticCategory.Message, key: "Found_package_json_at_0_6099", message: "Found 'package.json' at '{0}'." }, - package_json_does_not_have_a_types_or_main_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_types_or_main_field_6100", message: "'package.json' does not have a 'types' or 'main' field." }, + package_json_does_not_have_a_0_field: { code: 6100, category: ts.DiagnosticCategory.Message, key: "package_json_does_not_have_a_0_field_6100", message: "'package.json' does not have a '{0}' field." }, package_json_has_0_field_1_that_references_2: { code: 6101, category: ts.DiagnosticCategory.Message, key: "package_json_has_0_field_1_that_references_2_6101", message: "'package.json' has '{0}' field '{1}' that references '{2}'." }, Allow_javascript_files_to_be_compiled: { code: 6102, category: ts.DiagnosticCategory.Message, key: "Allow_javascript_files_to_be_compiled_6102", message: "Allow javascript files to be compiled." }, Option_0_should_have_array_of_strings_as_a_value: { code: 6103, category: ts.DiagnosticCategory.Error, key: "Option_0_should_have_array_of_strings_as_a_value_6103", message: "Option '{0}' should have array of strings as a value." }, @@ -3258,7 +3260,6 @@ var ts; Report_errors_on_unused_locals: { code: 6134, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_locals_6134", message: "Report errors on unused locals." }, Report_errors_on_unused_parameters: { code: 6135, category: ts.DiagnosticCategory.Message, key: "Report_errors_on_unused_parameters_6135", message: "Report errors on unused parameters." }, The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files: { code: 6136, category: ts.DiagnosticCategory.Message, key: "The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files_6136", message: "The maximum dependency depth to search under node_modules and load JavaScript files" }, - No_types_specified_in_package_json_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json', so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, @@ -6001,7 +6002,7 @@ var ts; } function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); - var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority); + var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions); for (var i = 0; i < adjustedExtensionPriority; i++) { var higherPriorityExtension = extensions[i]; var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension)); @@ -6013,7 +6014,7 @@ var ts; } function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) { var extensionPriority = ts.getExtensionPriority(file, extensions); - var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority); + var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions); for (var i = nextExtensionPriority; i < extensions.length; i++) { var lowerPriorityExtension = extensions[i]; var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension)); @@ -6249,37 +6250,28 @@ var ts; return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); } ts.moduleHasNonRelativeName = moduleHasNonRelativeName; - function tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, baseDirectory, state) { + function tryReadPackageJsonFields(readTypes, packageJsonPath, baseDirectory, state) { var jsonContent = readJson(packageJsonPath, state.host); - switch (extensions) { - case Extensions.DtsOnly: - case Extensions.TypeScript: - return tryReadFromField("typings") || tryReadFromField("types"); - case Extensions.JavaScript: - if (typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_so_returning_main_value_of_0, jsonContent.main); - } - return ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - } - return undefined; - } + return readTypes ? tryReadFromField("typings") || tryReadFromField("types") : tryReadFromField("main"); function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath); - } - return typesFilePath; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } + if (!ts.hasProperty(jsonContent, fieldName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName); } + return; } + var fileName = jsonContent[fieldName]; + if (typeof fileName !== "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof fileName); + } + return; + } + var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path); + } + return path; } } function readJson(path, host) { @@ -6680,7 +6672,8 @@ var ts; } return { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; function tryResolve(extensions) { - var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, state); + var loader = function (extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, true); }; + var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, failedLookupLocations, state); if (resolved) { return toSearchResult({ resolved: resolved, isExternalLibraryImport: false }); } @@ -6693,7 +6686,7 @@ var ts; } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state); + var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, false, state, true); return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: false }); } } @@ -6709,7 +6702,7 @@ var ts; } return real; } - function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { + function nodeLoadModuleByRelativeName(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]); } @@ -6737,7 +6730,7 @@ var ts; onlyRecordFailures = true; } } - return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); + return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } function directoryProbablyExists(directoryName, host) { return !host.directoryExists || host.directoryExists(directoryName); @@ -6794,45 +6787,48 @@ var ts; failedLookupLocations.push(fileName); return undefined; } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson) { + if (considerPackageJson === void 0) { considerPackageJson = true; } var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var mainOrTypesFile = tryReadPackageJsonMainOrTypes(extensions, packageJsonPath, candidate, state); - if (mainOrTypesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(mainOrTypesFile), state.host); - var fromExactFile = tryFile(mainOrTypesFile, failedLookupLocations, onlyRecordFailures_1, state); - if (fromExactFile) { - var resolved_3 = fromExactFile && resolvedIfExtensionMatches(extensions, fromExactFile); - if (resolved_3) { - return resolved_3; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromExactFile); - } - } - var resolved = tryAddingExtensions(mainOrTypesFile, Extensions.TypeScript, failedLookupLocations, onlyRecordFailures_1, state); - if (resolved) { - return resolved; + if (considerPackageJson) { + var packageJsonPath = pathToPackageJson(candidate); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + var fromPackageJson = loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state); + if (fromPackageJson) { + return fromPackageJson; } } else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_a_types_or_main_field); + if (directoryExists && state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); } + failedLookupLocations.push(packageJsonPath); } } - else { - if (directoryExists && state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocations.push(packageJsonPath); - } return loadModuleFromFile(extensions, ts.combinePaths(candidate, "index"), failedLookupLocations, !directoryExists, state); } + function loadModuleFromPackageJson(packageJsonPath, extensions, candidate, failedLookupLocations, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, packageJsonPath, candidate, state); + if (!file) { + return undefined; + } + var onlyRecordFailures = !directoryProbablyExists(ts.getDirectoryPath(file), state.host); + var fromFile = tryFile(file, failedLookupLocations, onlyRecordFailures, state); + if (fromFile) { + var resolved = fromFile && resolvedIfExtensionMatches(extensions, fromFile); + if (resolved) { + return resolved; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile); + } + } + var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions; + return nodeLoadModuleByRelativeName(nextExtensions, file, failedLookupLocations, onlyRecordFailures, state, false); + } function resolvedIfExtensionMatches(extensions, path) { var extension = ts.tryGetExtensionFromPath(path); return extension !== undefined && extensionIsOk(extensions, extension) ? { path: path, extension: extension } : undefined; @@ -6919,7 +6915,7 @@ var ts; } var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName); if (moduleHasNonRelativeName(moduleName)) { - var resolved_4 = forEachAncestorDirectory(containingDirectory, function (directory) { + var resolved_3 = forEachAncestorDirectory(containingDirectory, function (directory) { var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, directory, traceEnabled, host); if (resolutionFromCache) { return resolutionFromCache; @@ -6927,8 +6923,8 @@ var ts; var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName)); return toSearchResult(loadModuleFromFile(extensions, searchName, failedLookupLocations, false, state)); }); - if (resolved_4) { - return resolved_4; + if (resolved_3) { + return resolved_3; } if (extensions === Extensions.TypeScript) { return loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state);